<template>
  <div class="wrap">
    <div class="navBar">
      <van-nav-bar
          title="人员信息"
          :left-arrow="Boolean(!isWebFunc())"
          left-arrow-color="#FFFFFF"
          :border="false"
          :fixed="true"
          :safe-area-inset-top="true"
          @click-left="goBack"
      />
    </div>
    <div :class="{'tipWrap':true,'yelBg':type==3,'greBg':type==4}">
      <img v-show="[1,2].includes(type)" src="@/assets/unpass.png" />
      <img v-show="[3].includes(type)" src="@/assets/yelTip.png" />
      <img v-show="[4].includes(type)" src="@/assets/greTip.png" />
      <span v-if="type==1">请立即核对或修改以下信息：姓名/身份/电话/微信号/邮箱</span>
      <span v-else-if="type==2">“角色”无法修改，如需修改“角色”请联系区域经理。提交审批后请到【管理人员】模块进行查看。</span>
      <span v-else-if="type==3">当前信息正在确认中，如需调整请联系区域经理。</span>
      <span v-else-if="type==4">当前信息已确认，如需调整请联系区域经理。</span>
    </div>
    <van-loading v-show="personList.length<=0"  class="loadingWrap"  type="spinner" color="#1989fa" />
    <div class="contentWrap" v-show="personList.length>0"
         :style="{'height':([1,2].includes(type) && isMaster) ? 'calc(100% - 160px)' : 'calc(100% - 90px)'}">
        <div class="itemWrap" v-for="(item,index) in personList" :key="index">
          <div class="opaCol">人员{{(index+1)}}:</div>
          <div class="line"></div>
          <div class="item">
            <div class="left" :class="{'opaCol':type!=2}"><span class="star">*</span><span>姓名：</span></div>
            <div class="right">
              <van-field  :input-align="type==2 ? 'right' : 'left'" :readonly="type!=2" v-model="item.name" placeholder="请输入" />
            </div>
          </div>
          <div class="item">
            <div class="left opaCol"><span class="star" style="opacity: 0">*</span><span>角色：</span></div>
            <div class="right" :class="{'opaCol':type==2}">
              <van-field  :input-align="type==2 ? 'right' : 'left'" readonly v-model="item.roleName" placeholder="请输入" />
            </div>
          </div>
          <div class="item">
            <div class="left" :class="{'opaCol':type!=2}"><span class="star">*</span><span>电话1：</span></div>
            <div class="right">
              <van-field  :input-align="type==2 ? 'right' : 'left'" :readonly="type!=2" v-model.number="item.phone1" placeholder="请输入" @blur="blurHandle" />
            </div>
          </div>
          <div class="item">
            <div class="left" :class="{'opaCol':type!=2}"><span class="star"  style="opacity: 0">*</span><span>电话2：</span></div>
            <div class="right">
              <van-field  :input-align="type==2 ? 'right' : 'left'" :readonly="type!=2" v-model.number="item.phone2"  @blur="blurHandle" placeholder="请输入" />
            </div>
          </div>
          <div class="item">
            <div class="left" :class="{'opaCol':type!=2}"><span class="star">*</span><span>微信号：</span></div>
            <div class="right wechatRight">
              <span class="reviseBtn" v-show="type==2" @click="wechatRevise(item,index)">修改</span>
              <van-field  :input-align="type==2 ? 'right' : 'left'" readonly v-model="item.wechatName"  />
            </div>
          </div>
          <div class="item">
            <div class="left" :class="{'opaCol':type!=2}"><span class="star"  style="opacity: 0">*</span><span>邮箱：</span></div>
            <div class="right">
              <van-field  :input-align="type==2 ? 'right' : 'left'" :readonly="type!=2" v-model="item.email" placeholder="请输入" />
            </div>
          </div>
        </div>
    </div>
    <div class="btnWrap" v-if="isMaster && [1,2].includes(type)">
      <div v-show="type==2" class="audit common" @click="auditHandle">提交审批</div>
      <div v-show="type==1" class="revise common" @click="reviseHandle">立即修改</div>
      <div v-show="type==1" class="confirm common" @click="confirmHandle">确认信息无误</div>
    </div>
    <van-dialog v-model="dialogShow" title="请将此二维码发送至相应人员进行添加，成功添加后将更新微信号。" show-cancel-button
                confirmButtonText="确认已添加" confirmButtonColor="#354E93" className="customDialog"
                @confirm="wechatConfirm" @cancel="cancelHandle">
      <img v-if="wechatInfo?.qrCode" :src="wechatInfo.qrCode"  style="width: 83%"/>
    </van-dialog>
 </div>
</template>

<script>

import {myMixins} from "@/utils/myMixins"
import {getConfirmPerson,getConfirmStatus,getQrCode,confirmAddWechat,confirm,submitConfirm} from "@/api/authentication";
import { Dialog } from 'vant';
export default {
  name: "personList",
  mixins:[myMixins],
  data(){
    return{
      noClick:true,
      id:'',
      type:'',//1确认信息 2修改 3审批中 4已确认
      personList:[],
      dialogShow:false,
      reviseIndex:-1,
      supplierId:'',
      wechatInfo:'',
      personInfoId:'',
      personInfo:'',
      isMaster:false,
    }
  },
  async mounted() {
    window.addEventListener('message', (event) => {
      if (event.data === 'dialogClosed') {
        // console.log('Dialog 已关闭 // 执行关闭后的逻辑');
      }
    });
    // console.log('isWebFunc()',this.isWebFunc())
    const urlParams = new URLSearchParams(window.location.search);
    this.id=this.$route.query.id ||  urlParams.get('id');
    this.supplierId=this.$route.query.supplierId ||  urlParams.get('supplierId');
    // this.supplierId=1128
    console.log('1111',this.supplierId)
    await this.getPersonList()
  },
  methods:{
    blurHandle(e){
      let val= e.target.value || ''
      let flag=this.validatePhone(val)
      // console.log('flag',flag)
      if(!flag){
        this.$toast('手机号格式不正确')
      }
    },
    validatePhone(val) {
      console.log('val',val)
      if(!val){
        return true
      }
      const purePhone = val
      // 情况1：11位且1开头 → 合法
      if (/^1[0-9]{10}$/.test(purePhone)) {
        return true
      }
      // 情况2：12位且首位是0、第二位是1 → 去0后合法
      if (/^01[0-9]{10}$/.test(purePhone)) {
        return true
      }
      // 其他情况 → 不合法
      return false
    },
    async getPersonList(){
      let result=await getConfirmStatus({supplierId:this.supplierId})
      if(result.data?.wechatConfirmStatus==2){
        this.type=3
      }else if(result.data?.wechatConfirmStatus==3){
        this.type=4
      }else if(!result.data?.wechatConfirmStatus || result.data?.wechatConfirmStatus==1){
        this.type=1
      }
      this.isMaster=result.data.isMaster
      // this.type=2
      let res=await getConfirmPerson({supplierId:this.supplierId})
      if(res.data && res.data.length>0){
        this.personList=res.data
      }else{
        this.personList=[]
      }
    },
    async wechatConfirm(){//确认已添加微信按钮
      Dialog.confirm({
        message:'请确认相关人员是否已添加该二维码。',
        confirmButtonText:'确认',
        cancelButtonText:'取消',
        confirmButtonColor:'#354E93',
      }).then(async() => {
        let res=await confirmAddWechat({supplierId:this.supplierId,supplierPersonInfoId:this.personInfoId})
        console.log('res',this.personInfo,res.data?.name,this.personInfo.wechatName)
        if((res.data?.name == this.personInfo.wechatName) || (!res.data && this.personInfo.wechatName)){
          console.log('11111111')
          this.$set(this.personList[this.reviseIndex],'isChange',false)
        }else {
          console.log('2222222')
          this.$set(this.personList[this.reviseIndex],'isChange',true)
        }
        console.log('this.personList',this.personList)
        let flagRevise=this.personList.some(item => 'isChange' in item && !item.isChange)
        console.log('存在未修改',flagRevise)
        if(res.data){
          this.personList[this.reviseIndex].wechatId=res.data?.externalUserId
          this.personList[this.reviseIndex].wechatName=res.data?.name
        }
        await this.cancelHandle()
      }).catch(async () => {
        await this.cancelHandle()

      });
    },
    cancelHandle(){
      this.dialogShow=false
      this.wechatInfo=''
      this.reviseIndex=-1
      this.personInfoId=''
    },
    async wechatRevise(item,index){
      console.log('item,index',item,index)
      // console.log('item',item)
      this.personInfoId=item.id
      this.reviseIndex=index
      this.personInfo=item
      await this.getCode()
      this.dialogShow=true
    },
    async getCode(){//获取二维码
      let res = await getQrCode({supplierId:this.supplierId,supplierPersonInfoId:this.personInfoId})
      // console.log('res--getCode',res)
      this.wechatInfo=res.data || ''
    },
    async auditHandle(){//提交审批
      let flag=this.personList.every(item => item.name && item.phone1 && item.wechatId && item.wechatName)
      if(!flag){
        this.$toast('必填项不可为空')
        return
      }
      console.log('----',this.personList)
      let flagRevise=this.personList.some(item => 'isChange' in item && !item.isChange)
      console.log('存在未修改',flagRevise)
      if(flagRevise){
        this.$toast('您仍未修改微信号，请先修改再提交审批。')
        return
      }
      let phone1Flag= this.personList.every(item => this.validatePhone(item.phone1))
      let phone2Flag= this.personList.every(item => (item.phone2 && this.validatePhone(item.phone2) || !item.phone2))
      console.log('phone1Flag',phone1Flag)
      console.log('phone2Flag',phone2Flag)
      if(!phone1Flag || !phone2Flag){
        return
      }
      await submitConfirm({supplierId:this.supplierId,infos:this.personList})
      this.$toast('操作成功')
      if(this.isWebFunc()){
        setTimeout(()=>{
          this.closeParentDialog()
        },1500)
      }else{
        setTimeout(()=>{
          this.goBack()
        },1500)
      }
    },
    async reviseHandle(){//修改
      this.type=2
    },
    async confirmHandle(){//确认信息无误
      let flag=this.personList.every(item => item.name && item.phone1 && item.wechatId && item.wechatName)
      if(!flag){
        this.$toast('必填项不可为空，请点击“立即修改”将信息补充完整')
        return
      }
      Dialog.confirm({
        message:'请务必仔细确认信息是否无误。',
        confirmButtonText:'确认无误',
        cancelButtonText:'返回',
        confirmButtonColor:'#354E93',
      }).then(async() => {
        // console.log('确认无误')
        await confirm({supplierId:this.supplierId})
        this.$toast('操作成功')
        if(this.isWebFunc()){
          setTimeout(()=>{
            this.closeParentDialog()
          },1500)
        }else{
          setTimeout(()=>{
            this.goBack()
          },1500)
        }
      }).catch(() => {
      });
    },
  }
}
</script>
<style lang="scss">
.customDialog {
 .van-dialog__content{
    text-align: center !important;
  }
  .van-dialog__header {
    box-sizing: border-box;
    padding: 12px;
  }
}
</style>
<style scoped lang="scss">
@import "@/styles/common.scss";
@import '@/styles/mixin.scss';
.wrap {
  @include wh(100%, 100%);
  position: relative;
  background-color: #F6F6F6;
}
.navBar{
  margin-bottom: 46px;
}
.tipWrap{
  width: 100%;
  box-sizing: border-box;
  padding: 8px 8px 8px 18px;
  margin-bottom: 10px;
  display: flex;
  background-color: #FFF6F2;
  img{
    width: 14px;
    height: 14px;
    //vertical-align: middle;
    margin-right: 5px;
    margin-top: 2px;
  }
  span{
    color: #FC3C06;
  }
}
.yelBg{
  background-color: #FFFFED ;
  span{
    color: #F36708;
  }
}
.greBg{
  background-color: #E8FFF3;
  span{
    color: #19AC43;
  }
}
/*.headerWrap{
  width: 100%;
  box-sizing: border-box;
  padding: 15px 16px;
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .back{
    @include wh(15px,15px);
  }
  span{
    font-weight: bold;
    font-size: 16px;
    color: #203152;
  }
}*/
.loadingWrap{
  width: 100%;
  height: calc(100% - 90px);
  text-align: center;
  line-height: 200px;
}
.contentWrap{
  //height: calc(100% - 160px);
  //height: calc(100% - 90px);//没有按钮时
  overflow-y: auto;
  .itemWrap{
    font-size: 14px;
    width: 100%;
    margin-bottom: 10px;
    background-color: #FFFFFF;
    box-sizing: border-box;
    padding:10px 15px 10px 20px;
    .line{
      width: 100%;
      text-align: center;
      border-bottom: 2px solid;
      opacity: 0.16;
      margin-top: 10px;
      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;
    }
    .item{
      //line-height: 36px;
      display: flex;
      align-items: center;
      .left{
        width: 66px;
      }
      .right{
        flex: 1;
      }
      .wechatRight{
        display: flex;
        align-items: center;
        justify-content: space-between;
        .reviseBtn{
          display: inline-block;
          width: 60px;
          text-align: center;
          border-radius: 4px;
          background-color: #354D93;
          color: #FFFFFF;
          box-sizing: border-box;
          padding: 2px 0;
        }
      }
    }
    .opaCol{
      color: #323643;
      opacity: .65;
    }
    .star{
      font-weight: bold;
      font-size: 13px;
      color: #FF0808;
    }
  }
}
.btnWrap{
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  box-sizing: border-box;
  padding: 10px 19px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #F6F6F6;
  .common{
    background: #354D93;
    height: 48px;
    line-height: 48px;
    text-align: center;
    border-radius: 5px;
    font-weight: 500;
    font-size: 14px;
    color: #FFFFFF;
    cursor: pointer;
  }
  .audit{
    width: 100%;
  }
  .revise{
    width: 30%;
    background-color: #FFFFFF;
    color: #354D93;
    box-sizing: border-box;
    border: 1px solid #354D93;
  }
  .confirm{
    width: 67%;
  }
}
</style>
