<template>
<div class="wrap vehicleAdd">
  <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="addContentWrap">
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>行驶证首页</span>
    </div>
    <van-uploader
      v-model="vehicleLicenseFrontList"
      :after-read="vehicleLicenseFrontHandler"
      :max-size="5 * 1024 * 1024"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>行驶证副页</span>
    </div>
    <van-uploader
      v-model="vehicleLicenseBackList"
      :after-read="vehicleLicenseBackHandler"
      :max-size="5 * 1024 * 1024"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>车头照</span>
    </div>
    <van-uploader
      v-model="vehicleFrontPhotoList"
      :after-read="vehicleFrontPhotoHandler"
      max-count="1"
      :preview-size="54"
      accept="image "
    />
  </div>

  <cell-group label="车牌号" placeholder="车牌号" disabled v-model="carNum" />
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>车辆类型</span>
    </div>
    <select id="mySelect"  class="mySelect"  v-model="selectedOption">
      <option v-for="(item,index) in typeList" :key="index" :value="index">{{item}}</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="isJoin" @change="isChange"  class="joinWrap">
        <van-radio :name="1" style="margin-right: 26px">
          参与
          <img
              slot="icon"
              slot-scope="props"
              :src="props.checked ? activeIcon : inactiveIcon"
          >
        </van-radio>
        <van-radio :name="0">
          不参与
          <img
              slot="icon"
              slot-scope="props"
              :src="props.checked ? activeIcon : inactiveIcon"
          >
        </van-radio>
      </van-radio-group>
    </div>
  </div>
  <div class="lineBot"></div>
  <div class="itemContent">
    <div class="titleType">
      <img class="startImg" src="@/assets/start.png" />
      <span>选择服务种类</span>
    </div>
  </div>
  <div class="serviceType">

    <div class="trailerService" v-for="(item,index) in supplierServiceList" :key="index">
      <div class="serviceline"  @click="loadAll(index)">
        <img  :ref="'serviceline' + index" :src="imageUrl" style="width: 20px;height: 15px" >
        <span  class="service">{{ item.name }}:</span>
        <span class="line"></span>
      </div>
      <div :ref="'checkboxGroup' + index"  class="checkbox-group">
        <van-checkbox-group  v-model="serviceIds" v-for="(item2,index2) in item.children" :key="index2" class="radioWrap" >
          <van-checkbox class="item" :name="item2.id">{{item2.name }}</van-checkbox>
        </van-checkbox-group>
      </div>

    </div>
  </div>
  <two-common-btn class="btn" @cancelClick="h5GoBack" @submitClick="submitBtn" />
</div>
</div>
</template>

<script>
  // uploadImage
import {myMixins} from "@/utils/myMixins"
import {vehicleTypeList,saveVehicle,getInfoById,supplierServiceTree, uploadImage, ocrHandler} from "@/api/mine"
import TwoCommonBtn from "@/components/twoBtnCommon.vue"
import CellGroup from "@/components/cellGroup.vue";
export default {
  name: "vehicleAdd",
  mixins:[myMixins],
  data(){
    return{
      trailerService: '',//拖车服务
      isJoin:'',//是否参与
      activeIcon: require('@/assets/check.png'),
      inactiveIcon: require('@/assets/uncheck.png'),
      // result: [],
      checked: true,
      carNum:"",//车牌号
      typeList:[],//车辆类型列表
      selectedOption:'1',//车辆类型
      id:'',//车辆Id
      serviceIds:[],//车辆服务种类,
      supplierServiceList:[],
      show:false,
      imageUrl: require('@/assets/arr_right.png'),
      vehicleLicenseFrontList: [],
      vehicleLicenseBackList: [],
      vehicleFrontPhotoList: [],
      vehicleLicenseFront: '',  // 行驶证首页
      vehicleLicenseBack: '',   // 行驶证副页
      vehicleFrontPhoto: '',    // 车头照
      vehicleLicenseInfo: {},
      vehicleLicenseBackOcrFlag: false,   // 行驶证副页 修改时默认不需要 ocr识别
    }
  },
  async mounted() {
    this.id=this.$route.params?.id
    const selectElement = document.getElementById('mySelect');
    selectElement.addEventListener('change', function() {
     this.selectedOption=selectElement.value;
    });
    await this.getTypeList();
    if( this.id){
      await this.vehicleInfo()
    }
    await this.getSupplierServiceTree();
  },
  methods:{
    async vehicleLicenseFrontHandler(file) {    // 上传 行驶证首页
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData)
      this.vehicleLicenseFront = res.data;
      await this.vehicleOcrHandler();
    },
    async vehicleLicenseBackHandler(file) {     // 上传 行驶证副页
      this.vehicleLicenseBackOcrFlag = true;
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData);
      this.vehicleLicenseBack = res.data;
      await this.vehicleBackOcrHandler();
    },
    async vehicleFrontPhotoHandler(file) {     // 上传 车头照
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData);
      this.vehicleFrontPhoto = res.data;
    },
    async vehicleOcrHandler() {     // 行驶证首页 ocr 识别
      this.vehicleLicenseInfo.licensePlateNumber = '';
      this.vehicleLicenseInfo.vehicleType = '';
      this.vehicleLicenseInfo.owner = '';
      this.vehicleLicenseInfo.address = '';
      this.vehicleLicenseInfo.useNature = '';
      this.vehicleLicenseInfo.model = '';
      this.vehicleLicenseInfo.vinCode = '';
      this.vehicleLicenseInfo.engineNumber = '';
      this.vehicleLicenseInfo.registrationDate = '';
      this.vehicleLicenseInfo.issueDate = '';
      this.vehicleLicenseInfo.issueAuthority = '';
      let res = await ocrHandler({
        ocrType: 3,
        imageUrl: this.vehicleLicenseFront,
        cardSide: 'FRONT'
      })
      if ( res?.data?.frontInfo ) {
        let frontInfo = res?.data?.frontInfo;
        this.carNum = frontInfo?.plateNo;
        this.vehicleLicenseInfo.licensePlateNumber = frontInfo?.plateNo;
        this.vehicleLicenseInfo.vehicleType = frontInfo?.vehicleType;
        this.vehicleLicenseInfo.owner = frontInfo?.owner;
        this.vehicleLicenseInfo.address = frontInfo?.address;
        this.vehicleLicenseInfo.useNature = frontInfo?.useCharacter;
        this.vehicleLicenseInfo.model = frontInfo?.model;
        this.vehicleLicenseInfo.vinCode = frontInfo?.vin;
        this.vehicleLicenseInfo.engineNumber = frontInfo?.engineNo;
        this.vehicleLicenseInfo.registrationDate = frontInfo?.registerDate;
        this.vehicleLicenseInfo.issueDate = frontInfo?.issueDate;
        this.vehicleLicenseInfo.issueAuthority = frontInfo?.seal;
      }
    },
    async vehicleBackOcrHandler() {     // 行驶证副页 ocr 识别
      this.vehicleLicenseInfo.recordNumber = '';
      this.vehicleLicenseInfo.passengerCapacity = '';
      this.vehicleLicenseInfo.totalWeight = '';
      this.vehicleLicenseInfo.curbWeight = '';
      this.vehicleLicenseInfo.permittedWeight = '';
      this.vehicleLicenseInfo.overallDimension = '';
      this.vehicleLicenseInfo.tractionWeight = '';
      this.vehicleLicenseInfo.backPlateNo = '';     // 行驶证副页 车牌号，仅用来判断 ocr 识别是否成功
      let res = await ocrHandler({
        ocrType: 3,
        imageUrl: this.vehicleLicenseBack,
        cardSide: 'BACK'
      })
      if(res?.data?.backInfo) {
        let backInfo = res?.data?.backInfo;
        this.vehicleLicenseInfo.recordNumber = backInfo?.fileNo;
        this.vehicleLicenseInfo.passengerCapacity = backInfo?.allowNum;
        this.vehicleLicenseInfo.totalWeight = backInfo?.totalMass;
        this.vehicleLicenseInfo.curbWeight = backInfo?.curbWeight;
        this.vehicleLicenseInfo.permittedWeight = backInfo?.loadQuality;
        this.vehicleLicenseInfo.overallDimension = backInfo?.externalSize;
        this.vehicleLicenseInfo.tractionWeight = backInfo?.TotalQuasiMass;
        this.vehicleLicenseInfo.backPlateNo = backInfo?.plateNo;
      }
      console.log('this.vehicle', this.vehicleLicenseInfo)
    },
    loadAll(i){
      // console.log(i)
      this.show = !this.show
      const refName='checkboxGroup' + i;
      const element1 = this.$refs[refName]; // 通过动态属性名访问引用this.$refs.checkboxGroup.style.display = 'block';
      const refName1='serviceline' + i;
      const element = this.$refs[refName1];
      if(this.show){
        element1[0].style.display = 'block'
        element[0].src= require('@/assets/arr_bot.png')
      }else {
        element1[0].style.display = 'none'
        element[0].src= require('@/assets/arr_right.png')
      }
    },
    async getTypeList() {
        let result=await vehicleTypeList();
        if(result.code === 200){
          this.typeList=result.data
        }
    },
    async getSupplierServiceTree(){
      let res = await supplierServiceTree();
      this.supplierServiceList=res.data
    },
    async vehicleInfo(){
      let res= await  getInfoById({
        vehicleId:this.id
      })
      let result=res.data;
      this.id=result.vehicleId
      this.carNum=result.plateNumber
      this.isJoin=result.hasPolymerization.code
      this.selectedOption=result.vehicleType;
      this.serviceIds=result.serviceIds
      this.vehicleLicenseFront = result.vehicleLicenseFront;
      this.vehicleLicenseBack = result.vehicleLicenseBack;
      this.vehicleFrontPhoto = result.vehicleFrontPhoto;
      this.vehicleLicenseInfo = result.vehicleLicenseInfo;
      this.vehicleLicenseFrontList = [{ url : this.vehicleLicenseFront }];
      this.vehicleLicenseBackList = [{ url : this.vehicleLicenseBack }];
      this.vehicleFrontPhotoList = [{ url : this.vehicleFrontPhoto }];
    },
    isChange(e){
      this.isJoin=e
    },
    async submitBtn(){
        if( !this.vehicleLicenseFront ) {
          this.$toast('行驶证主页照片不能为空')
          return
        }
      if( !this.vehicleLicenseBack ) {
        this.$toast('行驶证副页照片不能为空')
        return
      }
      if( !this.vehicleLicenseBack ) {
        this.$toast('车头照片不能为空')
        return
      }
      if( !this.vehicleLicenseInfo.licensePlateNumber ) {
        this.$toast('行驶证主页识别失败')
        return
      }
      if(this.vehicleLicenseBackOcrFlag && !this.vehicleLicenseInfo.backPlateNo ) {
        this.$toast('行驶证副页识别失败')
        return
      }
        await saveVehicle({
          vehicleId:this.id ? this.id : '',
          plateNumber:this.carNum ? this.carNum :'',
          vehicleType:this.selectedOption ? this.selectedOption : '',
          hasPolymerization:this.isJoin,
          serviceIds:this.serviceIds ? this.serviceIds : [],
          vehicleLicenseFront: this.vehicleLicenseFront,
          vehicleLicenseBack: this.vehicleLicenseBack,
          vehicleFrontPhoto: this.vehicleFrontPhoto,
          vehicleLicenseInfo: this.vehicleLicenseInfo,
        })
        if(this.id){
          this.$toast('修改成功')
        }else{
          this.$toast('添加成功')
        }
        setTimeout(()=>{
          this.$router.back();
        },2000)
      }
  },
  components:{
    CellGroup,
    TwoCommonBtn
  }
}
</script>

<style>
  .vehicleAdd .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";
.mySelect{
  @include fontWeightSize(bold,13px);
  color: #323643;
  appearance: none;
  padding-right: 16px;
  background: url('@/assets/arrow_bot.png') no-repeat right center / 15px 14px;
}
.checkbox-group {
  display: none;
}
.navBar{
  margin-bottom: 46px;
}
.wrap{
@include wh(100%,100%);
  overflow-y: auto;
}
.addContentWrap{
  margin-left: 16px;
  .itemContent{
    @include flexColBet;
    line-height: 56px;
    box-sizing: border-box;
    padding-right: 25px;
    .titleType{
      @include fontWeightSize(bold,14px);
      color: #323643;
    }
    .isJoin{
      display: flex;
      .joinWrap{
        display: flex;
      }
      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;
  }
  .serviceType{
    @include fontWeightSize(bold,13px);
    margin-left: 15px;
    .trailerService{
      margin-bottom: 10px;
    }
    .serviceline{
      @include flexCenter;
      margin-bottom: 10px;
    }
    .item{
     margin: 20px 0;
      @include flexCenter;
    }
    .radioWrap{
      margin-left: 10px;
    }
    .service{
      @include colorOpa(#323643,0.7);
      line-height: 18px;
      white-space: nowrap;
    }
    .line{
      display: inline-block;
      @include wh(240px,2px);
      opacity: 0.16;
      border-bottom: 1px solid;
      border-image: linear-gradient(270deg, rgba(217, 217, 217, 0.6), rgba(178, 178, 178, 1), rgba(178, 178, 178, 1), rgba(217, 217, 217, 0.6)) 1 1;
    }
    img{
      @include widHeiMar(16px,16px,12px)
    }
  }
  .btn{
    width: 90%;
    margin: 40px 0 30px 8px;
  }
}
</style>
