<template>
  <div class="content">
    <div class="navBar">
      <van-nav-bar
          title="车辆信息认证"
          left-arrow
          left-arrow-color="#FFFFFF"
          :border="false"
          :fixed="true"
          :safe-area-inset-top="true"
          @click-left="goListPage"
      />
    </div>
    <tip-bar :title="'应国家政策要求：从事货运行业的司机用户，身份证照片、驾驶证信息、行驶证信息、人车合影及承运资质信息必须进行实名认证。'"></tip-bar>
    <div class="titleWrap">
      <div class="natureWrap">
        <span class="title"><span class="star">*</span>业务性质</span>
        <van-radio-group @change="radioChange" v-model="form.businessNature" class="flexWrap">
          <van-radio :name="1">全国跑圈业务</van-radio>
          <van-radio :name="2">固定区域救援业务</van-radio>
        </van-radio-group>
      </div>
      <div class="natureWrap regionWrap" v-if="form.businessNature == 2" >
        <span class="title"><span class="star">*</span>所在地区</span>
        <div class="pickerWrap picker" @click="areaShow = true" >{{regionText}}</div>
      </div>
    </div>
    <photo-item title="上传行驶证" :left-url="form.vehicleLicenseFront || driveFront" :right-url="form.vehicleLicenseBack || driveBack" v-if="type != 'simple'"
                :show="show" @leftImg="vehicleFrontHandler" @rightImg="vehicleBackHandler"></photo-item>
    <photo-item title="上传车辆照片" :left-url="form.vehicleFrontPhoto || carHead" :right-url="form.peopleVehiclePhoto || personCar" v-if="type != 'simple'"
                :show="show" @leftImg="carPhotoHandler" @rightImg="personPhotoHandler"></photo-item>
    <photo-item title="是否有救援责任险/货物运输险" :url-list="form.carrierLiabilityInsurancePhoto" :in-sure="form.hasInsurancePhoto"
                :show="show" @urlList="carrierHandler" @insureHandle="insureHandle"></photo-item>
    <div class="titleWrap">
      <div class="natureWrap">
        <span class="title"><span class="star">*</span>随车小轮个数</span>
        <van-radio-group v-model="form.wheelNum" class="flexWrap">
          <van-radio v-for="item in tyreOptions" :key="item.value"  :name="item.value">{{item.name}}</van-radio>
        </van-radio-group>
      </div>
    </div>
    <div class="carInfo" v-if="type != 'simple'">
      <div class="left_wrap title">
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>车牌号</span>
          </div>
          <span class="phone">{{form.licensePlateNumber}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>车架号</span>
          </div>
          <span class="phone">{{form.vinCode}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>车型</span>
          </div>
          <span class="phone">{{form.vehicleType}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>品牌车型</span>
          </div>
          <span class="phone">{{form.vehicleLicenseModel}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>行驶证人</span>
          </div>
          <span class="phone">{{form.vehicleLicenseOwner}}</span>
        </div>
        <div class="form_item">
          <div>
            <span>检验记录</span>
          </div>
          <span class="phone">{{form.inspectionRecord}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>总质量</span>
          </div>
          <span class="phone">{{form.totalWeight}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>整备质量</span>
          </div>
          <span class="phone">{{form.curbWeight}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>外廓尺寸</span>
          </div>
          <span class="phone">{{form.overallDimension}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star"></span>
            <span>档案编号</span>
          </div>
          <span class="phone">{{form.vehicleLicenseRecordNumber}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star"></span>
            <span>行驶证备注</span>
          </div>
          <span class="phone">{{form.vehicleLicenseRemarks}}</span>
        </div>
        <div class="form_item">
          <div>
            <span class="star">*</span>
            <span>车头照片中的车牌号码</span>
          </div>
          <span class="phone">{{form.carNumber}}</span>
        </div>
      </div>
    </div>
    <fixed-button @myClick="clickHandler" v-if="showFun()" :noBg="true"></fixed-button>
    <van-popup
        v-model="areaShow"
        position="bottom"
    >
      <van-area title="标题" :area-list="areaList" :columns-num="3"  closeable="true" :value="form.areaCode ? String(form.areaCode) : ''"
                @cancel="areaShow = false" @confirm="confirmHandle"/>
    </van-popup>
  </div>
</template>

<script>
  import fixedButton from "./component/fixedButton";
  import photoItem from "./component/photoItem";
  import tipBar from "./component/tipBar";
  import {ocrRecognize, driverInfoVerify, driverInfoVerifyDetail, infoVerifyProgress} from '@/api/authentication.js'
  import { leftCopy } from '@/utils/common.js'
  import { myMixins } from '@/utils/myMixins.js'
  import {areaList} from "@vant/area-data";
  export default {
    name: "carInfoAudit",
    components: {
      tipBar,
      photoItem,
      fixedButton,
    },
    mixins: [myMixins],
    data() {
      return {
        areaList: areaList,
        areaShow:false,
        region: [],
        driveFront: require('@/assets/authentication/carInfo_icon1.png'),
        driveBack: require('@/assets/authentication/carInfo_icon2.png'),
        carHead:require('@/assets/authentication/carInfo_icon3.png'),
        personCar:require('@/assets/authentication/carInfo_icon4.png'),
        liabilityInsurance:require('@/assets/authentication/carInfo_icon5.png'),
        form: {
          vehicleLicenseFront: '',   // 行驶证主页照片
          vehicleLicenseBack: '',    // 行驶证副页照片
          vehicleLicenseAddress: '', // 行驶证地址
					engineNumber: '',          // 行驶证发动机号
          licensePlateNumber: '',    // 车牌号
          vinCode: '',               // 车架号
          vehicleType: '',           // 车型
          vehicleLicenseModel: '',   // 行驶证车辆品牌车型
          vehicleLicenseOwner: '',   // 行驶证所有人
          inspectionRecord: '',      // 检验记录
          totalWeight: '',           // 总质量
          curbWeight: '',            // 整备质量
          overallDimension: '',      // 外廓尺寸
          vehicleLicenseRecordNumber: '',          // 行驶证档案编号
          vehicleLicenseRemarks: '',               // 行驶证备注
          vehicleFrontPhoto: '',     // 车头照片
          carNumber: '',             // 车头照片中的车牌号码
          peopleVehiclePhoto: '',    // 人车合影照片
          carrierLiabilityInsurancePhoto: [],   // 承运人责任险照片,如多张用英文逗号分开
          businessNature:'',
          areaCode:'',
          hasInsurancePhoto:'',
          wheelNum:-1,
          region:[],
        },
        show: undefined,
        type:  'full',
        tyreOptions:[{value:0,name:'0'},{value:2,name:'2'},{value:4,name:'4'}]
      }
    },
    async mounted() {
      // 禁止双击放大
      let lastTouchEnd = 0;
      document.addEventListener('touchend', (event) => {
        const now = Date.now();
        if (now - lastTouchEnd <= 300) {
          event.preventDefault(); // 阻止双击放大
        }
        lastTouchEnd = now;
      }, { passive: false });

      // if(options?.show) {
        this.show = true
      // }
      if(this.show) {
        await this.getDetail()
      }
    },
    methods: {
      confirmHandle(val){
        this.region=[]
        val?.forEach(item => this.region.push(item.name))
        let code=[]
        val?.forEach(item => code.push(item.code))
        this.form.areaCode=code[code.length - 1]
        this.areaShow=false
      },
      radioChange(){
        if(this.form.businessNature==1){
          this.region=[]
          this.form.areaCode=''
        }
      },
      async getDetail() {   // 认证详情
        let res = await driverInfoVerifyDetail( {
          verifyType: 3
        })
        leftCopy(this.form, {...res?.data?.vehicleInfoData})
        console.log("this.form",this.form)
        this.form.carrierLiabilityInsurancePhoto=this.form.carrierLiabilityInsurancePhoto ? res?.data?.vehicleInfoData?.carrierLiabilityInsurancePhoto?.split(',') : []
        if(this.form.businessNature==2){
          this.region=res?.data?.vehicleInfoData?.region
          if(this.region[0].includes('市')){
            this.region?.unshift(this.region[0])
          }
        }else {
          this.region=[]
        }
      },
      async clickHandler() {
        if( this.type != 'simple' ) {
          if(!this.form.businessNature){
            this.$toast('请选择业务性质')
            return
          }
          if(this.form.businessNature==2 && !this.form.areaCode){
            this.$toast('请选择所在地区')
            return
          }
          if(!this.form.vehicleLicenseFront) {
            this.$toast('行驶证主页未上传')
            return
          }
          if(!this.form.licensePlateNumber || !this.form.vehicleType ) {
            this.$toast('行驶证主页信息识别错误')
            return
          }
          if(!this.form.vehicleLicenseBack) {
            this.$toast('行驶证副页未上传')
            return
          }
          if(!this.form.totalWeight) {
            this.$toast('行驶证副页信息识别错误')
            return
          }
          if(!this.form.carNumber) {
            this.$toast('车辆信息识别错误')
            return
          }
          if( !this.form.peopleVehiclePhoto ) {
            this.$toast('人车合影未上传')
            return
          }
          if(this.form.hasInsurancePhoto == -1){
            this.$toast('请选择是否有救援责任险')
            return
          }
          if(this.form.hasInsurancePhoto==1 && this.form.carrierLiabilityInsurancePhoto?.length<=0){
            this.$toast('救援责任险/货物运输险未上传')
            return
          }
          if(this.form.wheelNum==-1){
            this.$toast('请选择随车小轮个数')
            return
          }
        }
        await driverInfoVerify( {
          verifyType: 3,
          type: this.type || 'full',
          ...this.form,
          carrierLiabilityInsurancePhoto:this.form.carrierLiabilityInsurancePhoto?.length>0 ? this.form.carrierLiabilityInsurancePhoto?.join(',') : ''
        })
        this.$toast('操作成功')
        await this.getRegisterInfo({
          verifyType: 3
        })
        setTimeout(() => {
          this.goListPage()
        }, 100)
      },
      async getRegisterInfo(data) {
        let res = await infoVerifyProgress( data)
        localStorage.setItem('infoVerify', res?.data?.infoVerify?.code)
        localStorage.setItem('failReason', res?.data?.verifyRemark)
        localStorage.setItem('authIsSuccess', res?.data?.authIsSuccess)
        localStorage.setItem('name', res?.data?.name)
      },
      carrierHandler(data) {    // 承运人责任险照片
        console.log("data",data)
        this.form.carrierLiabilityInsurancePhoto = data
      },
      insureHandle(val){
        this.form.hasInsurancePhoto=val
      },
      vehicleFrontInit() {
        this.form.licensePlateNumber = ''
        this.form.vinCode = ''
        this.form.vehicleType = ''
        this.form.vehicleLicenseModel = ''
        this.form.vehicleLicenseOwner = ''
      },
      async vehicleFrontHandler(data) {   // 行驶证正面照，及ocr识别
        console.log("vehicleFrontHandler",data)
        await this.vehicleFrontInit()
        this.form.vehicleLicenseFront = data
        let vehicleInfo = await this.orcHandler(this.form.vehicleLicenseFront, 3)
        let tempInfo = vehicleInfo?.data?.data?.face?.data
        this.form.licensePlateNumber = tempInfo.licensePlateNumber
        this.form.vinCode = tempInfo.vinCode
        this.form.vehicleType = tempInfo.vehicleType
        this.form.vehicleLicenseModel = tempInfo.model
        this.form.vehicleLicenseOwner = tempInfo.owner
        this.form.vehicleLicenseAddress = tempInfo.address
				this.form.engineNumber = tempInfo.engineNumber
      },
      vehicleBackInit() {
        this.form.inspectionRecord = ''
        this.form.totalWeight = ''
        this.form.curbWeight = ''
        this.form.overallDimension = ''
        this.form.vehicleLicenseRecordNumber = ''
        this.form.vehicleLicenseRemarks = ''
      },
      async vehicleBackHandler(data) {
        await this.vehicleBackInit()
        this.form.vehicleLicenseBack = data
        let vehicleInfo = await this.orcHandler(this.form.vehicleLicenseBack, 3)
        let tempInfo = vehicleInfo?.data?.data?.back?.data
        this.form.inspectionRecord = tempInfo.inspectionRecord
        this.form.totalWeight = tempInfo.totalWeight
        this.form.curbWeight = tempInfo.curbWeight
        this.form.overallDimension = tempInfo.overallDimension
        this.form.vehicleLicenseRecordNumber = tempInfo.recordNumber
        this.form.vehicleLicenseRemarks = tempInfo.remarks
      },
      async carPhotoHandler(data) {   // 车头照
        this.form.carNumber = ''
        this.form.vehicleFrontPhoto = data
        let carInfo = await this.orcHandler(this.form.vehicleFrontPhoto, 6)
        this.form.carNumber = carInfo?.data
      },
      personPhotoHandler(data){     // 人车合影
        this.form.peopleVehiclePhoto = data
      },
      async orcHandler(url, type) {     // ocr 识别
        let res = await ocrRecognize( {
          ocrType: type,
          imageUrl: url
        });
        return res;
      },
      goListPage(){
        this.goPage('auditList',{
          token:localStorage.getItem('token')
        })
      },
    },
    computed: {
      regionText() {
        return this.region.length ? `${this.region[0]}/${this.region[1]}/${this.region[2]}` : '请选择所在地区';
      }
    },
  }
</script>

<style lang="scss">
  @import "@/styles/common.scss";
  @import "@/styles/infoShow.scss";
  page {
    background: #F4F5F7;
  }
  .navBar{
    margin-bottom: 46px;
  }
  .content {
    padding-bottom: 86px;
    height: 100%;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* 启用iOS惯性滚动 */
    scroll-behavior: smooth; /* 平滑滚动（部分浏览器支持） */
  }
  .carInfo .title {
    width: 100% !important;
  }
  .form_item {
    line-height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .carInfo {
    padding-bottom: 86px;
  }
  .star{
    color: red;
    margin-right: 3px;
  }
  .titleWrap{
    margin-bottom: 10px;
    background-color: #FFFFFF;
    padding: 15px 12px 15px 17px;
    .natureWrap{
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 13px !important;
    }
    .regionWrap{
      margin-top: 8px;
    }
    .flexWrap{
      display:flex;
      align-items: center;
      ::v-deep .van-radio__icon{
        transform: scale(0.8);
        transform-origin: center; /* 保持中心点不变 */
      }
    }
  }
</style>
