<template>
<div class="wrap vehicleAdd">
  <div class="navBar">
    <van-nav-bar
        title="续保更新"
        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>
    <div class="isJoin">
      <van-radio-group v-model="hasLiabilityInsurance" @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>
  <span style="color: red">如有投保，选“有”，未投保选“无”，不必上传交强险或者商业险等其他保单</span>
  <div class="lineBot"></div>
  <template v-if="hasLiabilityInsurance == 1">
    <div class="itemContent">
      <div class="titleType">
        <img class="startImg" src="@/assets/start.png" />
        <span style="line-height: 20px">请上传救援职业责任险或货运险保单PDF或者关键信息页截图</span>
      </div>
      <van-uploader
        v-model="insurancePictureFiles"
        :after-read="insurancePictureFilesHandler"
        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>
      <el-select
        v-model="insuranceCorp"
        value-key="name"
        class="elSelect"
        collapse-tags="collapse-tags"
        placeholder="请选择"  style="width: 55%"
      >
        <el-option
          v-for="item in insuranceOptions"
          :key="item.name"
          :label="item.name"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </div>
    <div class="lineBot"></div>
    <div class="itemContent">
      <div class="titleType">
        <img class="startImg" src="@/assets/start.png" />
        <span>保险有效期</span>
      </div>
      <el-input style="width: 55%" readonly @focus="showDatePicker = true"  v-model="dateVal"  placeholder="请选择发布日期" :class="{'customSel':true,'customInput':true , 'has-value': dateVal }" >
        <template #suffix>
          <i
            v-if="dateVal"
            class="el-icon-circle-close el-input__icon"
            @click="dateVal = ''"
          ></i>
        </template>
      </el-input>
    </div>
  </template>
  <common-btn title="保存" @submitClick="submitBtn"/>
  <van-calendar v-model="showDatePicker"  :min-date="minDate"
                :max-date="maxDate" type="range" @confirm="onConfirm" />
</div>
</div>
</template>

<script>
  import {Dialog} from "vant";
import {myMixins} from "@/utils/myMixins"
  import {formatDate1} from "@/utils/common"
import { uploadImage, updateInsurance, getInfoById} from "@/api/mine"
  import CommonBtn from "@/components/commonBtn.vue"
export default {
  name: "vehicleAdd",
  mixins:[myMixins],
  data(){
    return{
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      minDate: new Date(1970, 0, 1),  // 设置最小可选日期（1970年1月1日）
      maxDate: new Date(2099, 11, 31), // 设置最大可选日期（2099年12月31日）
      showDatePicker: false,
      dateVal: '',
      hasLiabilityInsurance: 1,   // 有无责任险
      activeIcon: require('@/assets/check.png'),
      inactiveIcon: require('@/assets/uncheck.png'),
      // result: [],
      checked: true,
      show:false,
      imageUrl: require('@/assets/arr_right.png'),
      insurancePictureFiles: [],
      insurancePicturePhoto: '',    // 保单照片
      isMultiple: false,     // 是否支持多选
      insuranceCorp: '',
      insuranceOptions: [{
        name: '太平洋',
        value: 1
      }, {
        name: '人保',
        value: 2
      }, {
        name: '平安',
        value: 3
      }, {
        name: '中华联合',
        value: 4
      }, {
        name: '大地',
        value: 5
      }, {
        name: '阳光',
        value: 6
      }, {
        name: '太平',
        value: 7
      }, {
        name: '人寿',
        value: 8
      }, {
        name: '永安',
        value: 9
      }, {
        name: '华安',
        value: 10
      }, {
        name: '申能',
        value: 11
      }, {
        name: '大家',
        value: 12
      }, {
        name: '富德',
        value: 13
      }, {
        name: '其他',
        value: 14
      }]
    }
  },
  computed: {
  },
  watch:{

  },

  async mounted() {
    this.id=this.$route.params?.id
    if( this.id){
      // await this.vehicleInfo()
    }
  },
  methods:{
    async vehicleInfo(){
      let res= await  getInfoById({
        vehicleId:this.id
      })
      let result=res.data;
      this.id=result.vehicleId
      this.insurancePicturePhoto = result.insurancePicturePhoto;
      this.hasLiabilityInsurance = result.hasLiabilityInsurance
      this.insuranceCorp = result.insuranceCorp;
      if(this.insurancePicturePhoto) {
        this.insurancePictureFiles = [{url: this.insurancePicturePhoto}]
      }
      if( result.liabilityInsuranceEndTime && result.liabilityInsuranceStartTime ) {
        this.dateVal =  formatDate1(result.liabilityInsuranceStartTime) + ' - ' + formatDate1(result.liabilityInsuranceEndTime)
      }
    },
    formatDate(date) {
      return `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
    },
    onConfirm(date) {
      const [start, end] = date;
      this.showDatePicker = false;
      this.dateVal = `${this.formatDate(start)} - ${this.formatDate(end)}`;
    },
    formatDateTimeRange(str) {
      const [startStr, endStr] = str.split(' - ').map(s => s.trim());
      const startDate = new Date(startStr);
      const startTime = `${startDate.getFullYear()}-${(startDate.getMonth() + 1).toString().padStart(2, '0')}-${startDate.getDate().toString().padStart(2, '0')} 00:00:00`;
      const endDate = new Date(endStr);
      const endTime = `${endDate.getFullYear()}-${(endDate.getMonth() + 1).toString().padStart(2, '0')}-${endDate.getDate().toString().padStart(2, '0')} 23:59:59`;
      return {
        startTime,
        endTime
      };
    },
    async insurancePictureFilesHandler(file) {
      const formData = new FormData();
      formData.append("file" , file.file);
      let res = await uploadImage(formData);
      this.insurancePicturePhoto = res.data;
    },
    isChange(e){
      this.hasLiabilityInsurance=e
      if (e === 0) {
        Dialog.confirm({
          title: '提醒',
          message: '有救援职业责任险车辆会提升案件聚合能力和接单能力。',
          confirmButtonText: '我已知晓', // 确认按钮文字，默认为“确认”
          showCancelButton: false // 是否显示取消按钮，默认为 true。如果不需要取消按钮，可以设置为 false。
        })
        .then(() => { /* 确认后的操作 */ })
        .catch(() => { /* 取消后的操作 */ });
      }
    },
    async submitBtn(){
      if(this.hasLiabilityInsurance === null || this.hasLiabilityInsurance === undefined || this.hasLiabilityInsurance === '') {  // 有职业责任险，就需要有保单照片
        this.$toast('救援职业责任险不能为空')
        return
      }
      if(!this.insurancePicturePhoto && this.hasLiabilityInsurance == 1) {  // 有职业责任险，就需要有保单照片
        this.$toast('保单照片不能为空')
        return
      }
      if(!this.insuranceCorp && this.hasLiabilityInsurance == 1) {  // 有职业责任险，就需要有保单照片
        this.$toast('承保保司不能为空')
        return
      }
      if(!this.dateVal && this.hasLiabilityInsurance == 1) {  // 有职业责任险，就需要有保单照片
        this.$toast('保单有效期不能为空')
        return
      }
      let timeObj;
      if(this.dateVal) {
        timeObj = this.formatDateTimeRange(this.dateVal)
      }
      let params = {
        id: this.id ? this.id : '',
        renewInsureInfo: JSON.stringify({
          hasLiabilityInsurance: this.hasLiabilityInsurance,
          insurancePictureUrls: this.hasLiabilityInsurance == 1 ? this.insurancePicturePhoto : '',
          insuranceCorp: this.hasLiabilityInsurance == 1 ? this.insuranceCorp : '',
          liabilityInsuranceStartTime: this.hasLiabilityInsurance == 1 ? (timeObj?.startTime || '' ) : '',
          liabilityInsuranceEndTime: this.hasLiabilityInsurance == 1 ? (timeObj?.endTime || '') : '',
        })
      }
      await updateInsurance(params)
        if(this.id){
          this.$toast('修改成功')
        }else{
          this.$toast('添加成功')
        }
        setTimeout(()=>{
          this.$router.back();
        },2000)
      }
  },
  components:{
    CommonBtn
  }
}
</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;
  .item_content_btn {
    padding-right: 25px;
    text-align: right;
    span {
      display: inline-block;
      background: #354D93;
      padding: 5px 10px;
      font-size: 12px;
      font-weight: bold;
      color: #fff;
      border-radius: 4px;
      margin-bottom: 5px;
    }
  }
  .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;
  }
}
.elSelect ::v-deep .el-input__inner{
  border: none !important;
  text-align: right !important;
}
.disabled-tree {
  pointer-events: none;
  opacity: 0.6;
}
</style>
