<template>
  <div class="comp-client-confirm">
    <el-form ref="form" :model="form" label-width="80px" label-position="top" size="small">
      <page-module name="确认步骤" icon="step">
        <el-row :gutter="40">
          <el-col :span="24">
            <div class="SMS-confirm-course">
              <img :src="courseImg">
            </div>
          </el-col>
        </el-row>
      </page-module>
      <page-module name="信息内容" icon="content">
        <div class="SMS-confirm-content">
          <el-row :gutter="40">
            <el-col :span="12">
              <div class="SMS-confirm-content-row marginTop0">
                <div class="SMS-confirm-content-title">车主手机号</div>
                <div class="SMS-confirm-content-content">{{ turnHidePwd(form.mobile) }}</div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="SMS-confirm-content-row">
                <div class="SMS-confirm-content-title">短信内容</div>
                <div class="SMS-confirm-content-content">{{ form.vin }}</div>
              </div>
            </el-col>
          </el-row>
        </div>
      </page-module>
    </el-form>
    <!-- 操作等待 -->
    <operation-wait-dialog
      :wait-visible="msgVisible"
      :break-timer="breakTimer"
      :prompt-info="promptInfo"
      @updateWaitVisible="updateWaitVisible"/>
    <!-- 成功 -->
    <comp-confirm
      :show.sync="tipVisible"
      :desc="desc"
      :show-cancel-btn="false"
      :type="msgType"
      @on-sure="closeVisible"
    />
  </div>
</template>

<script>
import { postIccidsByVin, postPollCardUnbindStatus, surplusCardResult, getUnBindIccidList } from '@/api/special-business'
import CompConfirm from '@/components/CompConfirm'
import OperationWaitDialog from '@/components/OperationWaitDialog'
export default {
  name: 'CompClientConfirm',
  components: {
    CompConfirm,
    OperationWaitDialog
  },
  props: {
    formData: {
      type: Object,
      default: () => {}
    },
    waitVisible: {
      type: Boolean,
      default: () => false
    },
    type: {
      type: String,
      default: () => ''
    },
    promptInfo: {
      type: String,
      default: () => ''
    },
    opreatorUuid: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
      courseImg: require('@/assets/special-business/course.png'),
      tboxImg: require('@/assets/special-business/tbox.png'),
      bindImg: require('@/assets/special-business/bindImg.png'),
      unbindImg: require('@/assets/special-business/course.png'),
      form: {
        mobile: '',
        vin: ''
      },
      rnrInfo: {},
      rnrId: '',
      tipVisible: false,
      msgType: 'info',
      desc: '',
      carUnbindMsg: {
        3: '卡解绑成功',
        4: '客户已取消操作',
        9: '已超时, 如需操作请重试'
      },
      enterpriserUnbindMsg: {
        3: '企业解绑成功',
        4: '客户已取消操作',
        9: '已超时, 如需操作请重试'
      },
      tboxMsg: {
        3: '换件成功',
        4: '客户已取消操作',
        9: '已超时, 如需操作请重试'
      },
      bindMsg: {
        // 2等待中 3成功 4用户取消 9超时
        3: '卡绑定成功',
        4: '客户已取消操作',
        9: '已超时, 如需操作请重试'
      },
      intervals: null,
      breakTimer: false,
      msgVisible: false
    }
  },
  watch: {
    formData: {
      handler(val, oldVal) {
        if (val && val !== oldVal) {
          this.displaySmsTxt()
        }
      },
      deep: true,
      immediate: true
    },
    waitVisible: {
      handler(val, oldVal) {
        if (val && val !== oldVal) {
          this.msgVisible = val
          // 轮询是否发送了短信
          this.handleStatus()
        }
      }
    }
  },
  methods: {
    /**
    * 展示短信内容
    * @time 2022-04-24 06:49:47
    */
    displaySmsTxt() {
      let smsMsg = ''
      const curVin = this.formData.vin instanceof Array ? this.formData.vin.map(vin => this.turnHidePwd(vin, 'vin')) : this.turnHidePwd(this.formData.vin, 'vin')
      const iccidTxtArr = this.formData.iccidList ? this.formData.iccidList.map((item) => {
        return this.type === 'TBOX' ? `${this.turnHidePwd(item.iccid, 'iccid')}换为${this.turnHidePwd(item.newiccid, 'iccid')}` : this.turnHidePwd(item.iccid, 'iccid')
      }) : []
      if (this.type === 'TBOX') {
        // 换件
        smsMsg = `尊敬的*先生/女士: 您正在对VIN号为${curVin}的车进行换件操作, 如下卡号: ${iccidTxtArr.join(',')}。确定更换请回复“Y”, 放弃更换请回复“N”`
        this.courseImg = this.tboxImg
      }
      if (this.type === 'UNBIND') {
        // 卡解绑
        smsMsg = `尊敬的*先生/女士: 您正在对VIN号为${curVin}的车进行解绑操作,解绑如下卡号: ${iccidTxtArr.join(',')}。确定解绑请回复“Y”, 放弃解绑请回复“N”。解绑后该车将无法享受我们提供的联网服务, 请谨慎操作, 并确认您对该车的所属权。`
        this.courseImg = this.unbindImg
      }
      if (this.type === 'BIND' || this.type === '') {
        // 卡绑定
        smsMsg = `尊敬的*先生/女士: 您正在对VIN号为${curVin}的车进行一车多卡绑定操作, 绑定如下卡号: ${iccidTxtArr.join(',')}。确定绑定请回复“Y”, 放弃绑定请回复“N”`
        this.courseImg = this.bindImg
      }
      if (this.type === 'ENTERPRISE_UNBIND') {
        smsMsg = `尊敬的*先生/女士：您作为企业责任人，正在对本企业${curVin.length}台车辆进行解绑操作。确定解绑请回复“Y”，放弃解绑请回复“N”。解绑后这批车辆将无法享受我们提供的联网服务，请谨慎操作，并确认本企业对该批车辆的所属权。`
      }
      this.form.vin = smsMsg
      // 企业解绑不需要查询
      if (this.type !== 'ENTERPRISE_UNBIND') {
        this.getRnrInfoByVinFn()
      } else {
        this.form.mobile = this.formData.mobile
        console.clear()
        console.log('mobile: ', this.formData, this.form)
      }
    },

    /**
    * 加 * 号，置换首尾数字
    * @param  {String} val 手机号
    * @time 2022-04-23 13:39:47
    */
    turnHidePwd(val, type) {
      const curVal = '' + val
      if (type === 'vin') {
        return curVal.replace(/^(\w{6})\w{8}(\w{3})$/, '$1********$2')
      } else if (type === 'iccid') {
        return curVal.replace(/^(\w{6})\w{8}(\w{6})$/, '$1********$2')
      } else {
        return curVal.replace(/^(\w{3})\w{4}(\w{4})$/, '$1****$2')
      }
    },

    /**
    * 获取实名ID以及手机号
    * @time 2022-04-23 15:26:33
    */
    getRnrInfoByVinFn() {
      if (this.type === 'BIND') {
        getUnBindIccidList({
          data: {
            vin: this.formData.vin
          }
        })
          .then((res) => {
            this.rnrId = res.rnrId
            this.form.mobile = res.phone
          })
      } else {
        postIccidsByVin({
          data: {
            vin: this.formData.vin
          }
        }).then(res => {
          this.rnrInfo = res.mgRnrInfoDTO
          this.rnrId = res.vehicleCardRnrDTO.rnrId
          this.form.mobile = this.rnrInfo.phone
        })
      }
    },

    /**
    * 操作等待弹出关闭后事件
    * @time 2022-04-23 14:29:04
    */
    updateWaitVisible(val) {
      clearTimeout(this.intervals)
      // 在倒计时结束后, 延迟200毫秒发出最后一次请求
      setTimeout(() => {
        this.postStatusFuc(true)
      }, 200)
      this.$emit('update:waitVisible', false)
    },

    /**
    * 关闭解绑成功弹出
    * @time 2022-04-23 15:59:13
    */
    closeVisible() {
      if (this.msgType === 'success') {
        // 成功 - 前往首页
        this.$router.replace({
          name: 'Home'
        })
      } else {
        // 失败 - 关闭弹出
        this.tipVisible = false
      }
    },

    /**
    * 查询定时器
    * @time 2022-04-23 15:59:13
    */
    handleStatus() {
      this.intervals = setTimeout(() => {
        this.postStatusFuc()
      }, 6000)
    },

    /**
    * 查询是否发送短信
    * @time 2022-04-23 15:59:13
    */
    postStatusFuc(last) {
      let reqFuc = postPollCardUnbindStatus
      let reqData = { uuid: this.opreatorUuid }
      if (this.type === 'BIND') {
        reqFuc = surplusCardResult
        reqData = { orderId: this.opreatorUuid }
      }
      reqFuc(reqData)
        .then((res) => {
          if (this.type === 'UNBIND') {
            this.desc = this.carUnbindMsg[res.orderStatus] || '卡解绑失败'
          }
          if (this.type === 'ENTERPRISE_UNBIND') {
            this.desc = this.enterpriserUnbindMsg[res.orderStatus] || '企业解绑失败'
          }
          if (this.type === 'TBOX') {
            this.desc = this.tboxMsg[res.orderStatus] || '换件失败'
          }
          if (this.type === 'BIND') {
            this.desc = this.bindMsg[res.orderStatus] || '卡绑定失败'
          }
          if (res.orderStatus === 3) {
            this.msgType = 'success'
            if (last) {
              this.msgVisible = false
              this.tipVisible = true
            } else {
              this.breakTimer = true
            }
          } else {
            this.msgType = 'info'
            if (last) {
              this.msgVisible = false
              this.tipVisible = true
            } else {
              if (res.orderStatus === 2 || res.orderStatus === 1) {
                this.handleStatus()
              } else {
                this.breakTimer = true
              }
            }
          }
        })
        .catch((err) => {
          console.log(err)
          if (last) {
            this.msgVisible = false
            this.tipVisible = true
          } else {
            this.breakTimer = true
          }
          this.msgType = 'info'
          this.desc = err.message || '操作失败'
        })
    }
  }
}
</script>

<style scoped lang="scss">
.SMS-confirm-course{
  img{
    width: 100%;
  }
}
.marginTop0{
  margin-top: 0 !important;
}
.SMS-confirm-content-row{
  margin-top: 23px;
  .SMS-confirm-content-title{
    font-size: 14px;
    color: #212026;
    font-weight: 700;
  }
  .SMS-confirm-content-content{
    background: #F2F3F5;
    border-radius: 4px;
    font-size: 16px;
    color: #212026;
    line-height: 24px;
    font-weight: 400;
    padding: 12px;
    margin-top: 13px;
    text-align: left;
    word-break: break-all;
  }
}
</style>
