<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-image @click="handlePreview"   @remove="handleRemove" style="width: 54px;height: 54px;" class="camerImg" v-if="identityCardFront" :src="identityCardFront" />-->
<!--    <el-upload-->
<!--        v-else-->
<!--        :action="baseURL + '/order/uploadImage'"-->
<!--        :headers='authorization'-->
<!--        accept=".png,.jpg,.jpeg,.zip,.rar,.xlsx,.xsavels,.pdf,.PDF,.doc,.docx"-->
<!--        :on-success="changeHandle"-->
<!--        :before-upload="checkImgType"-->
<!--        class="upload-demo"-->
<!--        :show-file-list="false"-->
<!--    >-->
<!--      <van-icon  slot="default" name="plus" style="font-size: 54px" />-->
<!--    </el-upload>-->
    <van-uploader
        v-model="identityCardFrontList"
        :after-read="identityCardFrontHandler"
        :max-count="1"
        :preview-size="54"
        :max-size="5 * 1024 * 1024"
        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">
      <img class="startImg" src="@/assets/start.png" />
      <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" :disabled="statesDisabled" :class="{ 'disabled-tree': statesDisabled }" 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 {formatDate1} from "@/utils/common"
// import {ImagePreview} from "vant";

export default {
  name: "driverAdd",
  mixins:[myMixins],
  data(){
    return{
      // baseURL:'',
      // licenseOcrInfo:'',
      id:'',
      supplierId: '',
      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: '',
      potentialFlag: '',
      idCardAuthority:'',
      idCardValidStartTime:'',
      idCardValidEndTime:'',
      // authorization:{Authorization: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzb25nIiwiYXVkIjpbInN1cHBsaWVyLWFwcCJdLCJuYmYiOjE3MjY4MDk4MTQsInVzZXJfaW5mbyI6eyJ1c2VySWQiOjU0NjU0LCJwaG9uZSI6IjE3NjMwMDM1NjU4IiwibmFtZSI6InNvbmciLCJzdXBwbGllck5hbWUiOiLkuIrmtbfmtYvor5XkvpvlupTllYYiLCJzdXBwbGllcklkIjozMzA0MSwic3VwcGxpZXJUeXBlIjoyLCJ1c2VybmFtZSI6InNvbmciLCJ1c2VyVHlwZSI6InJlc2N1ZUFwcCIsImRldmljZUlkIjoiMTkwZTM1ZjdlMTRhYzdjMDAwNyIsImF1dGhvcml0aWVzIjpbXX0sInNjb3BlIjpbImFsbCJdLCJpc3MiOiJodHRwczovL3Npbm9hc3Npc3QuY29tIiwiZXhwIjoxNzI2ODk2MjE0LCJpYXQiOjE3MjY4MDk4MTR9.5KTAMXZf8ll6HS4Z49YJQ1HiRvHr79Q1goDAGEtsBmY'},
      // authorization:{Authorization:''},
      }
  },
  mounted() {
  /*  if (window.location.href.includes('www.sinoassist.com')) {
      this.baseURL = 'https://api.sinoassist.com'
    } else if (window.location.href.includes('ccreview.sino-assist.com')) {
      this.baseURL = 'https://api.sinoassist.com'
    } else {
      this.baseURL = 'https://api1.sino-assist.com'
      // this.baseURL = 'http://localhost:8080'

    }
    let token=localStorage.getItem('token')
    this.authorization.Authorization=token;*/
    this.id = this.$route.params?.id;
    this.supplierId = this.$route.params?.supplierId || '';
    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;
    this.potentialFlag = this.$route.params?.potentialFlag || '';
    console.log('this.potentialFlagthis.potentialFlag', this.potentialFlag)
    if(!this.id && this.potentialFlag === '1') {
      this.states = 0;
    }
    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
    });
    console.log('statesDisabled', this.statesDisabled)
  },
  methods:{
    isUse(e){
      this.states=e
    },
    /* checkImgType(file) {
      const FileExt = file.name.replace(/.+\./, "");
      const isLt5M = file.size / 1024 / 1024 < 5;
      const whiteList = ['png', 'jpeg', 'jpg'];
      if (whiteList.indexOf(FileExt.toLowerCase()) === -1) {
        this.$message.error("请上传正确的文件格式:" + whiteList.join('、'))
        return false
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false
      }
    },
   handleRemove() {
      this.identityCardFront = ''
    },
    handlePreview() {
      ImagePreview({
        images: this.identityCardFront,
        startPosition: 1,
        closeable: true,
      });
    },
    async changeHandle(response) {
      if (response.success === true) {
        this.$toast('上传成功')
        // this.form.identityCardFront = response.data;
        // await this.ocrFrontHandler()
        this.identityCardFront = response.data;
        console.log("this.identityCardFront",this.identityCardFront)
        await this.idCardOcrHandler();
      } else {
        this.$toast('上传失败')
      }
    },*/
    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
      if(!res.data.validDate){
        return
      }
      let date=res.data.validDate.split('-')
      if(date[0]){
        this.idCardValidStartTime=formatDate1(date[0]) +' '+ '00:00:00';
      }
      if(date[1]){
        if(date[1] == '长期'){
          this.idCardValidEndTime='2099/12/12' +' '+ '00:00:00';
        }else{
          this.idCardValidEndTime=formatDate1(date[1]) +' '+ '00:00:00';
        }
      }
    },
    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
      }*/
       if(!this.icon) {
       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 : '',
         supplierId: this.supplierId || undefined,
         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)
      },
  },
  computed: {
    statesDisabled() {
      return !this.id && this.potentialFlag === '1';
    }
  },
  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>
