<template>
  <div class="detail-container">
    <div class="pdf">
      <!-- <iframe :src="src + pdfUrl" class="iframe"></iframe> -->
    </div>
    <!-- 补充材料问题件 -->
    <div class="update" v-if="issueType === '828601'">
      <div class="updateInfo">
        <div class="title">被保险人身份证明</div>
        <div class="content">
          <div class="query">
            <div>问题说明</div>
            <p>
              {{ supplement.descriptionInsurant }}
            </p>
          </div>
          <van-uploader :after-read="insurantUpload" name="id" v-model="supplement.idImgList" />
        </div>
      </div>
      <div class="updateInfo">
        <div class="title">申请人身份证明、银行账户复印件</div>
        <div class="content">
          <div class="query">
            <div>问题说明</div>
            <p>
              {{ supplement.descriptionPolicyholder }}
            </p>
          </div>
          <van-uploader :after-read="policyHolderUpload" name="copy" v-model="supplement.copyImgList" />
        </div>
      </div>
    </div>
    <!-- 新契约基本问题件 -->
    <div class="feedback" v-if="issueType === 'TB89'">
      <div class="title">问题件回复：</div>
      <textarea placeholder="请输入" v-model="newContract.feedback"></textarea>
    </div>
    <div class="checkedBox" v-if="issueType !== '818901'">
      <van-checkbox v-model="checked" class="checked" icon-size="16px" shape="square"
        >本人认真阅读本新契约基本问题件，对其有关内容已全部了解，确认所上传资料均为真实资料，如有虚假资料或不如实告知，一切法律后果本人承担，同意将其作为投保要约的有效组成部分并承诺遵守。</van-checkbox
      >
    </div>
    <!-- 转账不成功基本问题件 -->
    <div class="selectList" v-if="issueType === '818901'">
      <div class="item">
        <van-field label-class="labels" label="处理方式">
          <template #input>
            <van-radio-group v-model="transfer.mode" direction="horizontal" class="radioGroup" @change="modeChange">
              <van-radio :name="1" icon-size="16px">继续转账</van-radio>
              <van-radio :name="2" icon-size="16px">终止转账</van-radio>
              <van-radio :name="3" icon-size="16px">更换卡号</van-radio>
            </van-radio-group>
          </template>
        </van-field>
      </div>
      <div class="item">
        <van-field v-model="transfer.bank" @click="getBankListItem" label-class="labels" readonly label="开户银行" placeholder="请选择"> </van-field>
      </div>
      <div class="item">
        <van-field v-model="transfer.card" :maxlength="19" label-class="labels" label="银行卡号" placeholder="请输入银行卡号"
          ><template #button>
            <van-button size="small" class="button" round color="#e4393c" type="primary" @click.stop="toggleCardScan(true)">银行卡扫描</van-button>
          </template>
        </van-field>
      </div>
      <div class="item">
        <van-field label-class="labels" readonly label="银行卡照片"></van-field>
        <div class="cardList">
          <van-uploader :max-count="2" :after-read="cardUpload" name="card" v-model="transfer.cardPhoto" />
        </div>
      </div>
      <div class="checkedBox" v-if="issueType === '818901'">
        <van-checkbox v-model="checked" class="checked" icon-size="16px" shape="square"
          >本人已认真阅读和理解上述通知书内容，同意将其作为投保要约的有效组成部分并承诺遵守。</van-checkbox
        >
      </div>
    </div>
    <!-- end -->
    <div class="autograph" v-if="issueType !== '818901'">
      <div class="list">
        <span>投保人/监护人亲笔签名：</span>
        <van-button type="danger" size="small" @click="autograph(0)">{{ policyholderSigned ? '已签名' : '签名' }}</van-button>
      </div>
      <div class="list" v-if="$route.query.receiveType === '1'">
        <span>被投保人亲笔签名：</span>
        <van-button type="danger" size="small" @click="autograph(1)">{{ insurantSigned ? '已签名' : '签名' }}</van-button>
      </div>
    </div>
    <div class="bg-white bottom-btn">
      <van-button type="danger" size="large" block @click="submit">下一步</van-button>
    </div>
    <short-message :show.sync="dialog.show" :type="dialog.type" :text="dialog.text" @getMessage="getMessage"></short-message>
    <van-popup v-model="transfer.show" position="bottom">
      <ul class="bankList">
        <li v-for="item in transfer.bankList" :key="item.code" @click="getBankListItem(item)">{{ item.bankName }}</li>
      </ul>
    </van-popup>
    <div :class="{ showDiscern: 1, show: transfer.showDiscern }">
      <van-icon name="cross" class="icon" @click.stop="toggleCardScan(false)" size="20" />
      <bank-card-scan class="backContent" :scanShow="true" :clear="transfer.clear" @getScanInfo="getBankNo"></bank-card-scan>
    </div>
    <!-- 转账不成功问题件提示框 -->
    <van-dialog v-model="showConfirm" title="标题" :show-confirm-button="false">
      <p style="margin: 1em;" v-if="transfer.mode === 2">
        如您选择终止转账，我公司将按照承保前撤单处 理，请您谨慎选择
      </p>
      <p style="margin: 1em;" v-if="transfer.mode === 3">
        变更银行账号后，续期保险费（如有）默认使用新账 号信息进行转账支付
      </p>
      <van-button type="danger" block @click="showConfirm = false">确定</van-button>
    </van-dialog>
  </div>
</template>
<script>
import { Uploader, Checkbox, Field, Radio, RadioGroup, Popup, Overlay, Dialog } from 'vant'
import { getBankList, uploadImg, saveInformation } from '@/api/ebiz/sale/sale'
import { getQuestionDetail, updateQuestionDetail } from '@/api/ebiz/questions'
import BankCardScan from '@/components/ebiz/sale/BankCardScan'
import ShortMessage from '@/components/ebiz/question/ShortMessage.vue'
export default {
  name: 'QuestionsDetail',
  components: {
    [Uploader.name]: Uploader,
    [Checkbox.name]: Checkbox,
    ShortMessage,
    BankCardScan,
    [Field.name]: Field,
    [Radio.name]: Radio,
    [RadioGroup.name]: RadioGroup,
    [Popup.name]: Popup,
    [Overlay.name]: Overlay,
    [Dialog.name]: Dialog
  },
  data() {
    let isWeixin = this.$utils.device().isWeixin
    return {
      isWeixin,
      problemDetail: null,
      supplement: {
        // 被保人问题描述
        descriptionInsurant: '',
        // 投保人问题描述
        descriptionPolicyholder: '',
        // 被保人身份证明
        idImgList: [],
        insurantUploadResult: [],
        // 投保人身份证明等资料
        copyImgList: [],
        policyholderUploadResult: []
      },
      newContract: {
        // 新契约
        feedback: ''
      },
      transfer: {
        // 转账失败
        mode: '',
        bank: '',
        bankCode: '',
        card: '',
        cardPhoto: [],
        bankList: [],
        show: false, //显示银行列表
        showDiscern: false, //是否开启银行卡识别
        clear: false, //是否清空银行卡识别数据
        cardUploadResult: []
      },
      // 勾选协议
      checked: false,
      dialog: {
        // 弹窗
        show: false,
        type: 'confirm',
        text: ''
      },
      issueType: 0,
      // 投保人是否已签名
      policyholderSigned: false,
      policyholderBase64: '',
      // 被保人是否已签名
      insurantSigned: false,
      insurantBase64: '',
      // 接收验证码手机号码
      phoneNum: '',
      showConfirm: false,
      src: '',
      pdfUrl: ''
    }
  },
  methods: {
    async policyHolderUpload(file, detail) {
      console.log(file, detail)
      let res = await this.afterRead(file)
      console.log(res)
      this.supplement.policyholderUploadResult.push({
        rgssUrl: res.path
      })
    },
    async insurantUpload(file) {
      let res = await this.afterRead(file)
      this.supplement.insurantUploadResult.push({
        rgssUrl: res.path
      })
    },
    async cardUpload(file) {
      let res = await this.afterRead(file)
      this.transfer.cardUploadResult.push({
        rgssUrl: res.path
      })
    },
    //签名
    async autograph(personType) {
      let problemInfo = JSON.parse(localStorage.getItem('currentProblemItem'))
      if (!this.isWeixin) {
        let signParam = {
          name: personType === 0 ? problemInfo.prtName : problemInfo.insuredName,
          type: '1',
          number: '142727199301063550',
          keyword: '签字',
          pageNo: '1',
          index: 1,
          offset: 20,
          pos: 3,
          signatureWidth: this.$utils.signParams().signatureWidth,
          signatureHeight: this.$utils.signParams().signatureHeight
        }
        console.log(signParam)
        // eslint-disable-next-line
        const res = await EWebBridge.webCallAppInJs('ca_sign', signParam)
        let signRes = JSON.parse(res)
        // 投保人签名
        if (personType === 0 && signRes.state === '1') {
          this.policyholderBase64 = decodeURI(signRes.sign)
          this.policyholderSigned = true
        }
        // 被保人签名
        else if (personType === 1 && signRes.state === '1') {
          this.insurantBase64 = decodeURI(signRes.sign)
          this.insurantSigned = true
        }
        console.log('签名结果: ', res)
      } else {
        this.toAirSign('0', '签字日期', '-150', '2', personType)
      }
    },
    getBankNo(data) {
      console.log(data)
    },
    toggleCardScan(data) {
      this.transfer.showDiscern = data
      if (data) {
        localStorage.setItem('cardScanningType', 0)
      } else {
        localStorage.removeItem('cardScanningType')
      }
    },
    getBankListItem(item) {
      this.transfer.show = !this.transfer.show
      this.transfer.bank = item.bankName
      this.transfer.bankCode = item.code
    },
    async getBankList() {
      this.transfer.bankList = (
        await getBankList({
          operateType: 'bank_type'
        })
      ).content
    },
    appCallBack(data) {
      let title = ''
      if (this.issueType === 'TB89') {
        title = '国富人寿基本问题件处理'
      } else if (this.issueType === '828601') {
        title = '国富人寿补充资料问题件处理'
      } else {
        title = '国富人寿转账不成功问题件处理'
      }
      if (data.trigger == 'right_button_click') {
        // eslint-disable-next-line no-undef
        EWebBridge.webCallAppInJs('bridge', {
          flag: 'share',
          extra: {
            title: title,
            content: this.shareContent,
            url: `${location.origin}/#/questions/detail/${this.problemDetail.id}/${this.problemDetail.issueType}?&token=${localStorage.token}&receiveType=${this.problemDetail.receiveType}&prtNo=${this.$route.query.prtNo}`,
            img: this.$assetsUrl + 'images/logo.png'
          }
        })
      }
    },
    modeChange(mode) {
      if (mode !== 1) {
        this.showConfirm = true
      }
    },
    async afterRead(file) {
      let data = new FormData()
      data.append('imgPath', file.file)
      return await uploadImg(data)
    },
    submit() {
      // 校验回复内容
      if (this.issueType === 'TB89' && this.newContract.feedback.trim() === '') return this.$toast('请填写回复内容')
      // 校验补充资料
      if (this.issueType === '828601') {
        if (this.supplement.idImgList.length === 0 || this.supplement.copyImgList.length === 0) {
          return this.$toast('请上传补充资料')
        }
      }
      if (this.issueType === '818901') {
        // 校验处理方式
        if (this.transfer.mode === '') {
          return this.$toast('请选择处理方式')
        }
        // 校验开户行
        if (!this.transfer.bank) {
          return this.$toast('请选择开户行')
        }
        // 银行卡号校验
        let regx = /^(\d{16}|\d{18}|\d{19})$/
        if (!regx.test(this.transfer.card)) {
          return this.$toast('银行卡号不符合规则')
        }
        if (this.transfer.cardPhoto.length === 0) {
          return this.$toast('请上传银行卡图片')
        }
      }
      if (!this.checked) return this.$toast('请先同意协议')
      // 转账失败问题件不用签名
      if (this.issueType !== '818901') {
        // 校验签名
        if (this.$route.query.receiveType === '0') {
          if (!this.policyholderSigned) return this.$toast('请完成签名后继续操作')
        } else if (this.$route.query.receiveType === '1') {
          if (!this.policyholderSigned || !this.insurantSigned) return this.$toast('请完成签名后继续操作')
        }
      }
      // 短信校验
      this.dialog = {
        type: 'confirm',
        show: true,
        text: '为确定用户身份，我们将向186xxxx8972此手机号发送验证码'
      }
    },
    async getMessage({ data }) {
      // 获取dialog信息，type为confirm时为短信框，alert时是确定框
      let currentProblem = JSON.parse(localStorage.getItem('currentProblemItem'))
      let problemData = {
        id: currentProblem.id,
        businessType: currentProblem.businessType,
        content: '',
        disposeStatus: '',
        bankType: '',
        bankName: '',
        bankNo: '',
        list: []
      }
      // 验证码验证成功
      if (data) {
        // 关闭短信弹窗
        this.dialog.show = false
        // 契约问题件
        if (this.issueType === 'TB89') {
          problemData.content = this.newContract.feedback
        }
        // 补充资料类问题件
        else if (this.issueType === '828601') {
          // 被保人资料
          for (let item of this.supplement.insurantUploadResult) {
            item.imageInfoType = '1'
            item.subBusinessType = '1'
          }
          problemData.list.push(...this.supplement.insurantUploadResult)
          // 投保人资料
          for (let item of this.supplement.policyholderUploadResult) {
            item.imageInfoType = '1'
            item.subBusinessType = '0'
          }
          problemData.list.push(...this.supplement.policyholderUploadResult)
        }
        // 转账不成功问题件
        else {
          problemData.disposeStatus = this.transfer.mode
          problemData.bankType = this.transfer.mode
          problemData.bankName = this.transfer.bank
          problemData.bankNo = this.transfer.card
          for (let item of this.transfer.cardUploadResult) {
            item.imageInfoType = '3'
            item.subBusinessType = '0'
          }
          problemData.list = this.transfer.cardUploadResult
        }
        // 更新问题件数据
        let res = await updateQuestionDetail(problemData)
        // 签名pdf
        let data = {
          orderType: 'SIGN_ORDER',
          orderDTO: {
            orderInfoDTO: {
              orderNo: ''
            },
            ebizSignDTOS: []
          }
        }
        saveInformation(data).then(res => {
          this.$toast.clear()
          if (res.result == '1') {
            localStorage.setItem('failedReason', res.resultMessage)
          }
          this.$jump({
            flag: 'h5',
            extra: {
              forbidSwipeBack: '1',
              url: location.origin + `/#/questions/result/${res.result}`
            },
            routerInfo: { path: `/questions/result/${res.result}` }
          })
        })
        console.dir(res)
      }
    },
    async getQuestionDetail() {
      const rs = await getQuestionDetail({
        id: this.$route.params.id,
        prtNo: this.$route.query.prtNo,
        userType: Number(this.$route.query.receiveType)
      })
      this.problemDetail = rs.content.list[0]
      this.problemDetail.receiveType = JSON.parse(localStorage.getItem('currentProblemItem')).receiveType
      this.supplement.descriptionInsurant = this.problemDetail.content
      this.supplement.descriptionPolicyholder = this.problemDetail.issueContent
    },
    //微信空签
    toAirSign(status, keyword, offset, originStatus, personType) {
      localStorage.setItem(
        'signInfo',
        JSON.stringify({
          originStatus: originStatus,
          idNo: localStorage.idNoD,
          name: localStorage.idNameD,
          type: '1',
          keyword: keyword,
          status: status,
          offset: offset,
          originUrl: location.href
        })
      )
      window.location.href = this.$mainUrl + '/sign/index.html'
    }
  },
  async created() {
    this.issueType = this.$route.params.type
    if (this.isWeixin) {
      localStorage.setItem('token', this.$route.query.token)
      let imgBase64Data = sessionStorage.getItem('oneimgBase64Data')
      let wxSigned = sessionStorage.getItem('onewxSigned')
      let signInfo = JSON.parse(localStorage.getItem('signInfo'))
      if (wxSigned) {
        console.log('第二次进问题件详情页面')
        this.base64D = imgBase64Data
      }
    }
    this.getBankList()
    this.getQuestionDetail()
    console.log(this.$route.params)
  },
  mounted() {
    setTimeout(() => {
      // 右上角的显示
      window.EWebBridge.webCallAppInJs('webview_right_button', {
        btns: [
          {
            img: this.$assetsUrl + 'images/share@3x.png'
          }
        ]
      })
    }, 1000)
    window['appCallBack'] = this.appCallBack
  }
}
</script>
<style lang="scss" scoped>
/deep/ .van-dialog__header {
  padding-top: 1em;
}
#app .van-cell:not(:last-child):after {
  border: 0;
}
.detail-container {
  background: #fff;
  padding-bottom: 40px;
  box-sizing: border-box;
  .showDiscern {
    position: fixed;
    z-index: -1;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    background: rgba(0, 0, 0, 0.5);
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease 0.3s;
    display: flex;
    align-items: flex-end;
    justify-content: center;
    background: #fff;
    &.show {
      z-index: 999;
      opacity: 1;
      visibility: visible;
      transition: all 0.3s;
      .backContent {
        transform: translateY(0);
        transition: all 0.3s ease 0.3s;
      }
    }
    .icon {
      position: absolute;
      right: 10px;
      top: 10px;
      z-index: 1;
    }
    .backContent {
      transition: all 0.3s;
      width: 100%;
      transform: translateY(10px);
      height: 95%;
      background: #fff;
      border-radius: 5px;
      overflow: hidden;
    }
  }
  .bankList {
    height: 300px;
    li {
      text-align: center;
      padding: 10px 0;
      font-size: 14px;
      border-bottom: 1px solid #eee;
    }
  }
  .pdf {
    width: 100%;
    height: 200px;
    border-bottom: 1px solid #eee;
  }
  .checkedBox {
    padding: 10px;
    .checked {
      font-size: 10px;
      color: #666;
      line-height: 1.5;
    }
  }
  .update {
    margin-bottom: 10px;
    .updateInfo {
      border-bottom: 1px solid #eee;
      .title {
        border-bottom: 1px solid #eee;
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        padding: 0 10px;
      }
      .content {
        padding: 10px 20px;
        .query {
          color: #e4393c;
          font-size: 13px;
          div {
            padding-bottom: 2px;
          }
          p {
            line-height: 22px;
            padding-bottom: 7px;
          }
        }
      }
    }
  }
  .feedback {
    border-bottom: 1px solid #eee;
    margin-bottom: 10px;
    padding: 0 10px;
    .title {
      font-size: 14px;
      padding: 10px 0;
    }
    textarea {
      font-size: 13px;
      border: 0;
      width: 100%;
      height: 60px;
    }
  }
  .selectList {
    .item {
      border-bottom: 1px solid #eee;
      /deep/.labels {
        font-size: 13px;
      }
      .radioGroup {
        display: flex;
        justify-content: space-between;
        font-size: 13px;
      }
      .button {
        height: 18px;
        line-height: 18px;
      }
      .cardList {
        padding: 10px 10px 0;
        border-top: 1px solid #eee;
      }
    }
  }
  .autograph {
    padding: 10px 10px 20px 10px;
    font-size: 12px;
    .list {
      &:first-child {
        margin-bottom: 5px;
      }
      .button {
        border-radius: 5px;
        height: 18px;
        line-height: 18px;
      }
    }
  }
  .next {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 40px;
  }
}
</style>
