<template>
  <div class="wrap" >
    <div class="headerWrap">
      <img class="bg" src="@/assets/secondHandCar/bg.png" />
      <div class="navWrap">
        <div v-if="isWebFunc()" style="opacity: 0;" class="back"></div>
        <img v-else class="back" @click="backHandle" src="@/assets/secondHandCar/back.png" />
        <img class="navIcon" src="@/assets/secondHandCar/cheyuan_big.png" />
        <div style="opacity: 0;" class="back"></div>
      </div>
      <div class="audit" v-if="status==3 && auditRemark">
        <span><img class="noAudit" src="@/assets/secondHandCar/noAudit.png" />审核不通过：</span>
        <span>{{auditRemark}}</span>
      </div>
      <div class="audit supplierInfo" v-if="type==2">
        <div><span>供应商名称：</span><span>{{supplierName}}</span></div>
        <div><span>供应商编号：</span><span>{{supplierCode}}</span></div>
      </div>
    </div>
    <div class="contentWrap" :style="id ? 'height: calc(100% - 100px);' : 'height: calc(100% - 42px);'" :class="[type==1 ? 'noContentAudit': 'hasContentAudit']">
      <div class="oneContent content">
        <img class="sort" src="@/assets/secondHandCar/one_cheyuan.png"  />
        <div class="uploadWrap">
          <upload-common  @success1="getDrivingLicense"  @delete1="deleteImg1"
                         :text="'行驶证照片'" :multiple="false" :files.sync="vehicleLicensePhotoList"/>
          <upload-common  @success2="getPlateColor"  @delete2="deleteImg2"
                         :text="'车辆45度照'" :multiple="false" :files.sync="vehicleAnglePhotoList" />
          <upload-common @success3="getOtherImg"   @delete3="handleDeleteOtherImg"
                         :text="'其他照片0/6'" :multiple="true"  :files.sync="otherImgSrcList"/>
        </div>
      </div>
      <div class="line"></div>
      <div  class="twoContent content">
        <img class="sort" src="@/assets/secondHandCar/two_desc.png"  />
        <div class="ocrInfo">
          <div class="item"><span>牌照类型</span><span class="orc">{{ form.licenseType==1 ? '蓝牌' : (form.licenseType==2 ? '黄牌' : (form.licenseType==3 ? '绿牌' : '')) }}</span></div>
          <div class="item"><span>上装品牌</span><span class="orc">{{form.brandModel}}</span></div>
          <div class="item"><span>注册日期</span><span class="orc">{{form.registerDate?.substring(0,10)}}</span></div>
        </div>
        <div class="item vehicleTypeItem">
          <span> <span class="star">*</span>车辆类型 </span>
          <van-radio-group v-model="form.vehicleType" direction="horizontal" class="radioWrap">
            <van-radio name="拖车" :class="{'checked':form.vehicleType=='拖车','vehicleRadio':true}">拖车</van-radio>
            <van-radio name="地库车" :class="{'checked':form.vehicleType=='地库车','vehicleRadio':true}">地库车</van-radio>
            <van-radio name="牵引车" :class="{'checked':form.vehicleType=='牵引车','vehicleRadio':true}">牵引车</van-radio>
            <van-radio name="随车吊" :class="{'checked':form.vehicleType=='随车吊','vehicleRadio':true}">随车吊</van-radio>
          </van-radio-group>
        </div>
        <div class="item" v-if="form.vehicleType=='拖车'">
          <span> <span class="star">*</span>落板方式 </span>
          <van-radio-group v-model="form.boardType" direction="horizontal" class="radioWrap">
            <van-radio name="1" :class="{'checked':form.boardType==1}">全落地</van-radio>
            <van-radio name="2" :class="{'checked':form.boardType==2}">斜落地</van-radio>
            <van-radio name="3" :class="{'checked':form.boardType==3}">一般平板</van-radio>
          </van-radio-group>
        </div>
        <div class="item">
          <span> <span class="star">*</span>排放标准 </span>
          <van-radio-group v-model="form.emissionStandard" direction="horizontal" class="radioWrap">
            <van-radio name="4" :class="{'checked':form.emissionStandard==4}">国4</van-radio>
            <van-radio name="5" :class="{'checked':form.emissionStandard==5}">国5</van-radio>
            <van-radio name="6" :class="{'checked':form.emissionStandard==6}">国6</van-radio>
          </van-radio-group>
        </div>
        <div class="item">
          <span> <span class="star">*</span>所在城市 </span>
          <van-field
              @focus="areaShow = true"
              class="radioWrap"
              readonly
              v-model="areaName"
              input-align="right"


          > </van-field>
        </div>
        <div class="item">
          <span> <span class="star">*</span>行驶里程 </span>
          <van-field
              type="number"
              class="radioWrap"
              v-model="form.mileage"
              input-align="right"
          >
            <template slot="right-icon" >
             <span style="white-space: nowrap;  margin-left: 8px;"> 公里 </span>
            </template>
          </van-field>
        </div>
        <div class="item">
          <span> <span class="star">*</span>联系号码 </span>
          <van-field
              type="number"
              class="radioWrap"
              v-model="form.contactNumber"
              input-align="right"

          > </van-field>
        </div>
        <div class="item">
          <span> <span class="star">*</span>售价</span>
          <van-field
              type="number"
              style="border: none"
              class="radioWrap"
              v-model="form.minPrice"
              input-align="right"
          >
            <template slot="right-icon" >
              <span style="white-space: nowrap;  margin-left: 8px;"> 元 </span>
            </template>
          </van-field>
        </div>
      </div>
      <div class="line lastLine"></div>
      <div  class="threeContent content">
        <img class="sort" src="@/assets/secondHandCar/three.png"  />
        <el-input class="ipt" v-model.trim="form.desc" type="textarea"  :autosize="{ minRows: 6, maxRows: 6 }"
                  maxlength="500" show-word-limit placeholder="描述车辆信息：如事故、额外加装、无线遥控"></el-input>
        <div v-if="type==2" style="margin: 10px 3px">不通过原因</div>
        <el-input v-if="type==2"  class="ipt" v-model.trim="auditReason" type="textarea"  :autosize="{ minRows: 2, maxRows: 6 }"
                  maxlength="200" show-word-limit placeholder="请填写不通过原因"></el-input>
        <div class="checkedWrap" v-if="type==1">
          <img v-show="radio==1" @click="radio=0" class="radioIcon" src="@/assets/secondHandCar/checked.png" />
          <img v-show="radio==0" @click="radio=1" class="radioIcon" src="@/assets/secondHandCar/uncheck.png" />
          <span>我已阅读并同意</span>
          <span @click="viewPrivacy">《二手车交易条款》</span>
        </div>
        <div class="btnWrap" >
          <div v-if="type==1" class="btn commonBtn"  @click="noMultipleClicks(submitHandle)">发布</div>
          <div v-if="type==2" class="auditBtn">
            <div  class="commonBtn" @click="noMultipleClicks(auditHandle,0)">审核不通过</div>
            <div  class="commonBtn" @click="noMultipleClicks(auditHandle,1)"><span style="margin-right: 6px">✔</span>审核通过</div>
          </div>
        </div>
      </div>
    </div>
    <van-popup
        v-model="areaShow"
        closeable
        position="bottom"
    >
      <van-area title="标题" :area-list="areaList" :columns-num="2"  closeable="true" :value="form.areaCode ? String(form.areaCode) : ''"
                @cancel="areaShow = false" @confirm="confirmHandle"/>
    </van-popup>
 </div>
</template>
<script>
import {publishCarInfo,carInfoDetail,auditCarInfo} from "@/api/secondHandCar"
import {myMixins} from "@/utils/myMixins"
import uploadCommon from "@/views/secondHandCar/components/upload-common.vue";
import {areaList} from "@vant/area-data";
export default {
  name: "carSource",
  mixins:[myMixins],
  components:{uploadCommon},
  data(){
    return{
      form:{
        id:'',
        type:1,
        vehicleLicensePhoto:'',
        vehicleAnglePhoto:'',
        otherPhoto:'',
        licenseType:'',
        brandModel:'',
        vinCode:'',
        plateNumber:'',
        vehicleFrontLicensePlate:'',
        registerDate:'',
        vehicleType:'',
        boardType:'',
        emissionStandard:'',
        areaCode:'',
        mileage:'',
        contactNumber:'',
        minPrice:'',
        desc:'',
      },
      radio: 0,
      type:'',//1为发布&修改 2为审核
      id:'',
      queryType:'',
      areaList: areaList,
      areaShow:false,
      noClick:true,
      auditRemark:'',
      auditReason:'',
      areaName:'',
      vehicleLicensePhotoList:[],
      vehicleAnglePhotoList:[],
      otherImgSrcList:[],
      otherImgSrc:[],
      status:'',
      supplierName:'',
      supplierCode:'',
    }
  },
  async mounted() {
    const urlParams = new URLSearchParams(window.location.search);
    this.type=this.$route.query.type || urlParams.get('type');
    this.id=this.$route.query.id ||  urlParams.get('id');
    this.queryType=this.$route.query.queryType || urlParams.get('queryType');
    if( this.id){
      let res = await carInfoDetail({
        id:this.id,
        queryType:this.queryType ,
      })
      this.form={...res.data}
      this.form.licenseType=res.data.licenseType?.code
      this.form.boardType=res.data.boardType?.code
      this.form.emissionStandard=res.data.emissionStandard?.code
      this.auditRemark=res.data?.auditRemark
      this.status=res.data?.status?.code
      const municipalities = ['北京市', '天津市', '上海市', '重庆市'];
      const isMunicipality = municipalities.some(city => res.data.areaName.includes(city));
      this.areaName= isMunicipality ? res.data.areaName?.substring(0, 3) : res.data.areaName;
      this.supplierName=res.data?.supplierName
      this.supplierCode=res.data?.supplierCode
      if(res.data?.otherPhoto){
        this.otherImgSrc=res.data.otherPhoto?.split(',')
        this.otherImgSrc?.map(item=>this.otherImgSrcList.push({url:item}))
      }
      this.vehicleLicensePhotoList=[{url:res.data?.vehicleLicensePhoto}]
      this.vehicleAnglePhotoList=[{url:res.data?.vehicleAnglePhoto}]
    }
    let carSourceFormInfo=localStorage.getItem("carSourceFormInfo") ? JSON.parse(localStorage.getItem("carSourceFormInfo")) : ''
    // console.log("carSourceFormInfo",carSourceFormInfo)
    if(!carSourceFormInfo){
      return
    }
    this.form={...carSourceFormInfo.form}
    this.radio=carSourceFormInfo.radio
    this.areaName=carSourceFormInfo.areaName
    this.vehicleLicensePhotoList=carSourceFormInfo.vehicleLicensePhotoList
    this.vehicleAnglePhotoList=carSourceFormInfo.vehicleAnglePhotoList
    this.otherImgSrcList=carSourceFormInfo.otherImgSrcList
    this.otherImgSrc=carSourceFormInfo.otherImgSrc
  },
  methods:{
    clearStorageFormInfo(){
      localStorage.setItem("carSourceFormInfo",'')
    },
    backHandle(){
      if(this.$route.query.homePage){//返回列表
        this.$router.push({ name: "indexList"})
      }else{//返回我的发布
        this.$router.push({ name: "mineRelease"})
      }
      this.clearStorageFormInfo()
    },
    viewPrivacy(){
      let data={
        form:this.form,radio:this.radio,areaName:this.areaName,
       /* vehicleLicensePhotoList:this.vehicleLicensePhotoList,
        vehicleAnglePhotoList:this.vehicleAnglePhotoList,
        otherImgSrcList:this.otherImgSrcList,
        otherImgSrc:this.otherImgSrc,*/
      }
      localStorage.setItem("carSourceFormInfo",JSON.stringify(data))
      this.$router.push({ name: "privacyComponent"})
    },
    confirmHandle(val){
      // let data=val.length
      // this.form.areaCode=val[data - 1]?.code
      if(val[0].name.includes('市')){
        this.areaName=val[0].name
        this.form.areaCode=val[0].code
      }else{
        this.areaName=val[0].name +val[1].name
        this.form.areaCode=val[1].code
      }
      this.areaShow=false
    },
    getDrivingLicense(data){
      console.log("getDrivingLicense",data)
      this.form.vehicleLicensePhoto=data.url
      this.form.brandModel=data.info.model
      this.form.vinCode=data.info.vin
      this.form.plateNumber=data.info.plateNo
      this.form.registerDate=data.info.registerDate +' 00:00:00'
      this.form.vehicleType=data.info.vehicleType
    },
    deleteImg1(){
      this.form.vehicleLicensePhoto=''
    },
    getPlateColor(data){
      console.log("getPlateColor",data)
      this.form.vehicleAnglePhoto=data.url
      this.form.licenseType=data.colorStatus
      this.form.vehicleFrontLicensePlate=data.plateType
    },
    deleteImg2(){
      this.form.vehicleAnglePhoto=''
    },
    getOtherImg(data){
      this.otherImgSrc.push(data.url)
    },
    handleDeleteOtherImg(file,index) {
      this.otherImgSrc = this.otherImgSrc.filter((item,i) => index !== i);
      this.otherImgSrcList = this.otherImgSrcList.filter((item,i) => index !== i);
    },
    // 审核操作
    async auditHandle(type){
      if (!type && !this.auditReason){
        this.$toast('请填写不通过原因')
        return
      }
      await this.commonMethods();
      try {
        await auditCarInfo({
          id: this.id,
          auditResult: type  ? 1 : 0 ,
          auditReason: this.auditReason,
          ...this.form,
          otherPhoto:this.otherImgSrc?.join(',')
        })
        this.clearStorageFormInfo()
        setTimeout(()=>{
          this.closeParentDialog()
        },1000)
      } finally {
        console.log(type)
      }
    },
    commonMethods(){
      if (!this.form.vehicleLicensePhoto) {
        this.$toast('行驶证不能为空')
        return
      }
      if (!this.form.vehicleAnglePhoto) {
        this.$toast('车辆45度不能为空')
        return
      }
      let flag=this.validateHandle()
      if(flag){
        this.$toast(flag)
        return
      }
      if (this.form.vehicleType=='拖车' && !this.form.boardType) {
        this.$toast('落板方式不能为空')
        return
      }else if(this.form.vehicleType !=='拖车'){
        this.form.boardType=''
      }
      let rule=this.validationRules.find(item=>!item.value)
      if(rule){
        this.$toast(rule.name)
        return
      }
    },
    // 发布车源
    async submitHandle(){
      if (!this.radio) {
        this.$toast('请勾选我已阅读并同意')
        return
      }
      await this.commonMethods();
      try {
        let res = await publishCarInfo({
          ...this.form,
          otherPhoto:this.otherImgSrc?.join(',')
        })
        this.clearStorageFormInfo()
        if(res.code == 200 && !res.msg){
          this.$toast('发布成功')
          if(this.isWebFunc()){
            setTimeout(()=>{
              this.closeParentDialog()
            },1000)
          }else{
            setTimeout(()=>{
              this.$router.push({ name: "mineRelease"})
              sessionStorage.setItem('mineActiveTab',String(1) )
            },1000)
          }
        }else{
          this.$toast(res.msg)
        }
        console.log("车源发布publishCarInfo",res)
      } catch (e){
        console.log('e',e)
      } finally {
        console.log(111)
      }
    },
    // 手机号验证方法
    validateHandle() {
      const contactNumberPattern = /^1[3-9]\d{9}$/; // 手机号正则表达式
      let str=''
      if (!this.form.contactNumber) {
        str='联系方式不能为空'
        // return
      } else if (!contactNumberPattern.test(this.form.contactNumber)) {
        str='联系方式格式错误'
      } else {
        str=''
      }
      return str
    },
  },
  computed: {
    validationRules() {
      return [
        { value: this.form.vehicleType, name: '车辆类型不能为空' },
        { value: this.form.emissionStandard, name: '排放标准不能为空' },
        { value: this.form.areaCode, name: '所在城市不能为空' },
        { value: this.form.mileage, name: '行驶里程不能为空' },
        { value: this.form.contactNumber, name: '联系方式不能为空' },
        { value: this.form.minPrice, name: '售价不能为空' },
      ];
    },
  },
}
</script>

<style scoped lang="scss">
@import '@/styles/mixin.scss';
.wrap {
  @include wh(100%, 100%);
  position: relative;
}
.headerWrap{
  width: 100%;
  box-sizing: border-box;
  padding-top: 15px;
  padding-bottom: 15px;
  position: relative;
  .navWrap{
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-sizing: border-box;
    padding: 0 16px 10px;
  }
  .bg{
    position: absolute;
    width: 100%;
    height: 120px;
    line-height: 120px;
    top: 0;
    left: 0;
    opacity: 0.5;
    z-index: -1;
  }
  .back{
    @include wh(15px,15px);
  }
  .navIcon{
    @include wh(84px,21px);
  }
  .audit{
    @include wh(100%,43px);
    background: #FFF7F4;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    color: #FF6B3B;
    .noAudit{
      @include wh(13px,12px);
      margin-right: 5px;
      vertical-align: bottom;
    }
    span:first-child{
      font-weight: 600;
    }
  }
  .supplierInfo{
    justify-content: space-around;
    background-color: #F5F7F9;
    color: #606266;;
  }
}
.navBar{
  margin-bottom: 46px;

}
.noContentAudit{
  height: calc(100% - 42px);
}
//100px
.hasContentAudit{
  height: calc(100% - 85px);
}
.contentWrap{
  width: 100%;
  overflow-y: auto;
  .sort{
    @include wh(91px, 19px);
    margin-bottom: 15px;
  }
  .line{
    width: 100%;
    border-bottom: 1px solid #F2F2F2;
    margin-top: 26px;
    margin-bottom: 17px;
  }
  .lastLine{
    margin-top: 3px !important;
  }
  .content{
    width: 100%;
    box-sizing: border-box;
    padding: 0 14px 0 20px;
    //padding:0 20px;
  }
  .oneContent{
    .uploadWrap{
      display: flex;
      flex-wrap: wrap;
      //justify-content: space-between;
    }
  }
  .twoContent{
    .ocrInfo{
      background: #FAFBFC;
      border-radius: 4px;
    }
    .item{
      display: flex;
      //align-items: center;
      font-weight: 400;
      font-size: 13px;
      color: #2C3D54;
      line-height: 44px;
      width: 100%;
      box-sizing: border-box;
      padding-left: 21px;
      padding-right: 9px;
      span:first-child{
        display: inline-block;
        width:70px;
        font-size: 13px;
        color: rgba(44, 61, 84, 0.59);
      }
      span:last-child{
        display: inline-block;
        width:calc(100% - 70px);
        border-bottom: 1px solid #E9E9EA;
      }
      .orc{
        box-sizing: border-box;
        padding-left: 6px;
      }
    }
    .vehicleTypeItem{
      line-height: 13px !important;
      margin-top: 8px;
    }
    .star{
      color: #FF4B4B !important;
      opacity: 1 !important;
      font-weight: bold;
      font-size: 12px;
      margin-right: 6px;
      margin-left: -6px;
    }
    .radioWrap{
      width:calc(100% - 70px);
      border-bottom: 1px solid #E9E9EA;
    }
  }
  .threeContent{
    .checkedWrap{
      cursor: pointer;
      color:#808D99 ;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 20px;
      margin-bottom: 10px;
      font-size: 12px;
      .radioIcon{
        @include wh(16px, 16px);
        margin-right: 6px;
      }
      span:last-child{
        color: #0E76F4;
      }
    }
    .btnWrap{
      padding-bottom: 20px;
      padding-top: 15px;
    }
    .commonBtn{
      height: 46px;
      line-height: 46px;
      text-align: center;
      font-weight: bold;
      border-radius: 5px;
      color: #FFFFFF;
      cursor: pointer;
    }
    .btn{
      width: 296px;
      background: #4A7FEB;
      margin: 0 auto;
      font-size: 15px;
    }
    .auditBtn{
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      box-sizing: border-box;
      padding: 0 6px;
      div:first-child{
        width: 100px;
        opacity: 0.79;
        background: #1C2C49;
      }
      div:last-child{
        width: 200px;
        background: #4A7FEB;
      }
    }
  }
}
 ::v-deep .van-icon-success{
  display: none !important;
}
 ::v-deep .van-radio__label{
   margin-left: 0;
   width: 54px;
   height: 23px;
   border-radius: 13px;
   border: 1px solid #9F9F9F;
   opacity: 0.5;
   text-align: center;
   line-height: 23px;
   font-size: 12px;
   color: #323233;
   opacity: 1;
 }
 ::v-deep .van-radio--horizontal{
   margin-right: 4px;
 }
::v-deep .van-radio--horizontal:last-child{
  margin-right: 0;
}
::v-deep  .checked .van-radio__label{
   background: #FFF1EC !important;
   border: 1px solid #FF5C26 !important;
   color: #FE5006 !important;
   border-radius: 13px !important;
 }
::v-deep  .van-field__right-icon{
  margin-right: 0;
  padding: 0;
}
::v-deep .ipt .el-textarea__inner{
  background: #F5F7F9;
  border-radius: 4px;
  //opacity: 0.74;
  font-size: 12px;
  border: none;
}
::v-deep .van-popup__close-icon--top-right{
  display: none;
}
::v-deep .vehicleRadio .van-radio__label{
  margin-bottom: 8px !important;
}
</style>
