<template>
<div class="wrap driverAdd">
  <div class="navBar">
    <van-nav-bar
        :title="id ? '修改司机信息' : '添加司机'"
        left-arrow
        left-arrow-color="#FFFFFF"
        :border="false"
        :fixed="true"
        :safe-area-inset-top="true"
        @click-left="h5GoBack"
    />
  </div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>身份证正面</span>
    </div>
    <van-uploader
      v-model="identityCardFrontList"
      :after-read="identityCardFrontHandler"
      :max-size="5 * 1024 * 1024"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="lineBot"></div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>身份证反面</span>
    </div>
    <van-uploader
      v-model="identityCardContraryList"
      :after-read="identityCardBackHandler"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="lineBot"></div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>驾驶证主页</span>
    </div>
    <van-uploader
      v-model="drivingLicenceFrontList"
      :after-read="drivingLicenceFrontHandler"
      max-count="1"
      :max-size="5 * 1024 * 1024"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="lineBot"></div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>驾驶证副页</span>
    </div>
    <van-uploader
      v-model="drivingLicenceContraryList"
      :after-read="drivingLicenceContraryHandler"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="lineBot"></div>
  <div class="itemContent">
    <div class="titleType">
      <span>头像</span>
    </div>
    <van-uploader
      v-model="iconList"
      :after-read="iconListHandler"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="lineBot"></div>
<!--  :disabled="supplierType ==1 ? true:false"-->
  <cell-group label="司机姓名" placeholder="司机姓名"  v-model="driverName" disabled />
  <cell-group label="手机号码"  v-model="driverPhone"   placeholder="手机号码" />
  <cell-group label="身份证号" v-model="identityCardNumber"   placeholder="身份证号" disabled  />
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>准驾车型</span>
    </div>
    <select id="mySelect" class="mySelect" v-model="drivingModel" disabled >
      <option value="A1">A1</option>
      <option value="A2">A2</option>
      <option value="A3">A3</option>
      <option value="B1">B1</option>
      <option value="B2">B2</option>
      <option value="C1">C1</option>
      <option value="C2">C2</option>
    </select>
  </div>
  <div class="lineBot"></div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>司机状态</span>
    </div>
    <div class="isJoin">
      <van-radio-group v-model="states" @change="isUse"  class="joinWrap">
        <van-radio :name="1" style="margin-right: 26px" class="item">
          启用
          <img
              slot="icon"
              slot-scope="props"
              :src="props.checked ? activeIcon : inactiveIcon"
          >
        </van-radio>
        <van-radio :name="0" class="item">
          停用
          <img
              slot="icon"
              slot-scope="props"
              :src="props.checked ? activeIcon : inactiveIcon"
          >
        </van-radio>
      </van-radio-group>
    </div>
  </div>
  <div class="lineBot"></div>
  <two-common-btn class="btn" @cancelClick="h5GoBack" @submitClick="submitBtn" />
</div>
</template>

<script>
import {myMixins} from  "@/utils/myMixins"
import {saveDriver, uploadImage, ocrHandler} from "@/api/mine"
import TwoCommonBtn from "@/components/twoBtnCommon.vue"
import CellGroup  from "@/components/cellGroup.vue"
import {formatDate} from "@/utils/common"
export default {
  name: "driverAdd",
  mixins:[myMixins],
  data(){
    return{
      id:'',
      driverName:"",
      driverPhone:"",
      identityCardNumber:"",
      drivingModel:'',
      states:'',
      activeIcon: require('@/assets/check.png'),
      inactiveIcon: require('@/assets/uncheck.png'),
      supplierType:'',
      createTime:'',
      identityCardFront: '',           // 身份证正面
      identityCardFrontList: [],       // 身份证正面 列表
      identityCardContrary: '',        // 身份证反面
      identityCardContraryList: [],    // 身份证反面 列表
      drivingLicenceFront: '',         // 驾驶证正面
      drivingLicenceFrontList: [],     // 驾驶证正面 列表
      drivingLicenceContrary: '',      // 驾驶证反面
      drivingLicenceContraryList: [],  // 驾驶证反面 列表
      icon: '',
      iconList: [],
      driverInfo: {},
      drivingLicenceName: '',
      idCardAuthority:'',
      idCardValidStartTime:'',
      idCardValidEndTime:'',
    }
  },
  mounted() {
    this.id = this.$route.params?.id;
    this.driverName = this.$route.params?.name;
    this.driverPhone = this.$route.params?.phone;
    this.drivingModel = this.$route.params?.drivingModel;
    this.identityCardNumber = this.$route.params?.identityCardNumber;
    this.states = this.$route.params?.states;
    this.supplierType=this.$route.params?.supplierType;
    this.createTime=this.$route.params?.createTime;
    this.driverInfo.drivingBeginDate = this.$route.params?.drivingBeginDate;
    this.drivingLicenceContrary = this.$route.params?.drivingLicenceContrary;
    this.drivingLicenceFront = this.$route.params?.drivingLicenceFront;
    this.driverInfo.drivingLicenceValidityDate = this.$route.params?.drivingLicenceValidityDate;
    this.icon = this.$route.params?.icon;
    this.identityCardContrary = this.$route.params?.identityCardContrary;
    this.identityCardFront = this.$route.params?.identityCardFront;
    this.driverInfo.lssueDate = this.$route.params?.lssueDate;
    this.drivingLicenceName =  this.$route.params?.drivingLicenceName;
    if( this.identityCardFront ) {
      this.identityCardFrontList = [{ url : this.identityCardFront }];
    }
    if( this.identityCardContrary ) {
      this.identityCardContraryList = [{ url : this.identityCardContrary }];
    }
    if( this.drivingLicenceFront ) {
      this.drivingLicenceFrontList = [{ url : this.drivingLicenceFront }];
    }
    if( this.drivingLicenceContrary ) {
      this.drivingLicenceContraryList = [{ url : this.drivingLicenceContrary }];
    }
    if( this.icon ) {
      this.iconList = [{ url : this.icon }];
    }
    const selectElement = document.getElementById('mySelect');
    selectElement.addEventListener('change', function() {
      const selectedValue = selectElement.value;
      this.drivingModel=selectedValue
    });

  },
  methods:{
    isUse(e){
      this.states=e
    },
    async identityCardFrontHandler(file) {    // 上传身份证正面照片
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData)
      this.identityCardFront = res.data;
      await this.idCardOcrHandler();
    },
    async identityCardBackHandler(file) {  // 上传身份证反面照片
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData)
      this.identityCardContrary = res.data;
      await this.idCardBackOcrHandler();
    },
    async drivingLicenceFrontHandler(file) {   // 上传驾驶证主页
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData)
      this.drivingLicenceFront = res.data;
      await this.drivingLicenceOcrHandler();
    },
    async drivingLicenceContraryHandler(file) {   // 上传驾驶证副页
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData)
      this.drivingLicenceContrary = res.data;
    },
    async iconListHandler(file) {           // 上传头像
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData)
      this.icon = res.data;
    },
    async idCardOcrHandler() {    // 身份证正面 ocr识别
      this.driverName = '';
      this.identityCardNumber = '';
      let res = await ocrHandler({
        ocrType: 1,
        imageUrl: this.identityCardFront,
        cardSide: 'FRONT'
      })
      this.driverName = res?.data?.name;
      this.identityCardNumber = res?.data?.idNum;
      let aaa=''
      if(this.drivingLicenceName){
        aaa = this.drivingLicenceName.replace(/[^\u4e00-\u9fff]+/g, '');
      }
      let bbb=this.driverName.replace(/[^\u4e00-\u9fff]+/g, '');
      if( this.drivingLicenceName && aaa != bbb ) {
        this.$toast('身份证信息与驾驶证信息不匹配')
      }
    },
    async idCardBackOcrHandler() {    // 身份证反面 ocr识别
      let res = await ocrHandler({
        ocrType: 1,
        imageUrl: this.identityCardContrary,
        cardSide: 'BACK'
      });
      this.idCardAuthority=res.data.authority
      let date=res.data.validDate.split('-')
      this.$toast("date=="+date[0])
      // let dateStartTime=date[0].split('.')
      // console.log("dateStartTime",dateStartTime)
      // this.idCardValidStartTime=dateStartTime[0] + dateStartTime[1] +dateStartTime[2] +' '+ '00:00:00';
      this.idCardValidStartTime=formatDate(date[0]) +' '+ '00:00:00';
      // this.$toast("idCardValidStartTime=="+this.idCardValidStartTime)
      console.log("==",this.idCardValidStartTime)
      if(date[1] == '长期'){
        this.idCardValidEndTime='2099-12-12' +' '+ '00:00:00';
      }else{
        this.idCardValidEndTime=formatDate(date[1]) +' '+ '00:00:00';
      }
      console.log("==",this.idCardValidEndTime)
    },
    async drivingLicenceOcrHandler() {      // 驾驶证正面 ocr识别
      this.driverInfo.drivingLicenceValidityDate = '';
      this.driverInfo.drivingBeginDate = '';
      this.driverInfo.lssueDate = '';
      this.drivingModel = '';
      this.drivingLicenceName = '';
      let res = await ocrHandler({
        ocrType: 2,
        imageUrl: this.drivingLicenceFront,
        cardSide: 'FRONT'
      });
      if( res?.data ) {
        this.driverInfo.drivingBeginDate = res?.data?.dateOfFirstIssue || '';
        this.driverInfo.lssueDate = res?.data?.dateOfFirstIssue ? (res?.data?.dateOfFirstIssue + ' 00:00:00') : '';
        if( res?.data?.endDate.indexOf('长期') != -1 ) {
          this.driverInfo.drivingLicenceValidityDate = '2099-01-01';
        } else {
          this.driverInfo.drivingLicenceValidityDate = res?.data?.endDate;
        }

        this.drivingModel = res.data?.class_;
        this.drivingLicenceName = res.data?.name
        let aaa=''
        if(this.driverName){
           aaa = this.driverName.replace(/[^\u4e00-\u9fff]+/g, '');
        }
        let bbb = this.drivingLicenceName.replace(/[^\u4e00-\u9fff]+/g, '');
        if( this.driverName && bbb != aaa ) {
          this.$toast('身份证信息与驾驶证信息不匹配')
        }
      }
    },
    async submitBtn(){
      if(!this.identityCardFront) {
        this.$toast('身份证正面照未上传')
        return
      }
      if(!this.identityCardContrary) {
        this.$toast('身份证反面照未上传')
        return
      }
      if(!this.drivingLicenceFront) {
        this.$toast('驾驶证首页未上传')
        return
      }
      if(!this.drivingLicenceContrary) {
        this.$toast('驾驶证副页未上传')
        return
      }
      let drivingLicenceName=this.drivingLicenceName.replace(/[^\u4e00-\u9fff]+/g, '');
      let driverName=this.driverName.replace(/[^\u4e00-\u9fff]+/g, '');

      if( drivingLicenceName != driverName ) {
        this.$toast('身份证信息与驾驶证信息不匹配')
        return
      }
      if( this.driverInfo.drivingLicenceValidityDate ) {
        if(this.driverInfo.drivingLicenceValidityDate && new Date(this.driverInfo.drivingLicenceValidityDate).getTime() < new Date().getTime() ) {
          this.$toast('驾驶证已过期')
          return
        }
      } else {
        this.$toast('驾驶证信息识别错误，请重新上传')
        return
      }
       await saveDriver({
         driverId:this.id ? this.id : '',
         driverName:this.driverName ,
         driverPhone:this.driverPhone,
         identityCardNumber:this.identityCardNumber,
         drivingModel:this.drivingModel,
         states:Number(this.states),
         createTime:this.createTime || '',
         identityCardFront: this.identityCardFront,
         identityCardContrary: this.identityCardContrary,
         drivingLicenceFront: this.drivingLicenceFront,
         drivingLicenceContrary: this.drivingLicenceContrary,
         icon: this.icon,
         drivingLicenceName: this.drivingLicenceName,
         idCardAuthority:this.idCardAuthority,
         idCardValidStartTime:this.idCardValidStartTime,
         idCardValidEndTime:this.idCardValidEndTime,
         ...this.driverInfo
      })
      if(this.id){
        this.$toast('修改成功')
      }else{
        this.$toast('添加成功')
      }
        setTimeout(()=>{
          this.$router.back();
        },2000)
      },
  },
  components:{
    TwoCommonBtn,
    CellGroup
  }
}
</script>
<style>
  .driverAdd .van-field__control:disabled {
    color: #323643 !important;
    -webkit-text-fill-color: #323643 !important;
  }
</style>
<style scoped lang="scss">
@import "@/styles/mixin.scss";
@import "@/styles/common.scss";
.wrap{
  @include wh(100%,100%);
  box-sizing: border-box;
  padding-left: 16px;
  padding-bottom: 100px;
  overflow-y: auto;
}
.mySelect{
  @include fontWeightSize(bold,13px);
  width: 44px;
  color: #323643;
  appearance: none;
  padding-right: 16px;
  background: url('@/assets/arrow_bot.png') no-repeat right center / 15px 14px;
}
.navBar{
  margin-bottom: 46px;
}
.itemContent{
  @include flexColBet;
  line-height: 56px;
  box-sizing: border-box;
  padding-right: 25px;
  .titleType{
    @include fontWeightSize(bold,14px);
    color: #323643;
  }
  .isJoin{
    display: flex;
    .joinWrap, .item{
      @include flexCenter;
    }
    img{
      @include widHeiMar(16px,16px,6px)
    }
  }
  .startImg{
    @include widHeiMar(6px,6px,3px);
    vertical-align: super;
  }
  input{
    border: none;
    text-align: right;
    @include fontWeightSize(bold,13px);
    opacity: .5;
  }

}
.lineBot{
  @include wh(100%,1px);
  background: #E9E9EA;
  opacity: 0.6;
}
.btn{
  margin-left: 8px;
  width: 91%;
  position: fixed;
  bottom: 30px;
}
</style>
