<template>
  <h-view id="np-bank-card">
    <h-header :proportion="[5,1,1]" class="bar-custom">
      <div slot="left" class="h-header-btn" @click="$routeGo()">
        <img src="@/assets/userBind/arrow.png" >
        <span>银行信息</span>
      </div>
    </h-header>
    <h-content>
      <div id="bank-card">
        <div class="info">
          <div class="info-icon">
            <img src="@/assets/userBind/info.png" >
            <span>温馨提示</span>
          </div>
          <p>推荐使用农行卡,农行卡支付免收手续费!</p>
        </div>
        <div class="my-card">
          <div class="top">
            <div class="left">
              <img src="@/assets/userBind/bankIcon.png" class="icon" >
              <span class="top-word">
                我的卡
                <span class="sum">(共{{ getBankList.length }}张)</span>
              </span>
            </div>
            <img src="@/assets/userBind/add.png" class="icon-right" @click="showModal" >
          </div>
          <div class="clear" />
          <div class="card-content">
            <ul>
              <li v-for="(item,index) in getBankList" :key="index" >
                <item-option class="slider">
                  <div
                    :style="'background-image: url('+ changeBgImg (item) +')'"
                    class="my-bank-card"
                    @click="showModalInfo(item)"
                  >
                    <div class="card-info">
                      <span class="name">{{ item.bank_full_name }}</span>
                      <span class="card-type">{{ selectType(item.bank_card_type) }}</span>
                      <span class="number">卡号</span>
                      <span class="card-number">**** **** **** {{ selectLast (item) }}</span>
                    </div>
                  </div>
                  <div slot="buttons" class="button">
                    <option-button text @click.native="deleteFun(item.bank_account_num)" />
                  </div>
                </item-option>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </h-content>
    <bottom-tab class="footer-button">
      <tab-button class="save" @click.native="putData">提交</tab-button>
    </bottom-tab>
    <h-modal ref="modal" v-model="showModalValue" position="bottom">
      <h-view>
        <div class="modal-content">
          <div class="modal-content-add-top">
            <span>添加银行卡</span>
            <img src="@/assets/userBind/close.png" @click="hideModal" >
          </div>
          <img
            v-if="!bankImg && !isApproved"
            src="@/assets/userBind/addBack.png"
            class="addBack"
            @click="ocrShow('bankCard', '')"
          >
          <img
            v-if="bankImg"
            :src="bankImg"
            class="addBack"
            style="height: 38%;"
            @click="ocrShow('bankCard', '')"
          >
          <img
            v-if="isClear && isApproved && !bankImg"
            src="@/assets/userBind/addBack.png"
            class="addBack"
            @click="ocrShow('bankCard', '')"
          >
          <img
            v-if="!bankImg && isApproved && !isClear"
            src="@/assets/userBind/addBack.png"
            class="addBack"
            @click="ocrShow('bankCard', '')"
          >
          <list-item :item-height="44" class="card-Info">
            <item>
              <div slot="name">银行卡卡号</div>
              <input
                slot="content"
                v-model="bank.bank_account_num"
                readonly
                placeholder="识别银行卡自动填充"
              >
            </item>
            <item>
              <div slot="name">账户姓名</div>
              <input slot="content" v-model="bank.bank_account_name" readonly placeholder="请输入账户名称" >
            </item>
            <item>
              <div slot="name">银行名称</div>
              <input slot="content" v-model="bank.bank_full_name" readonly placeholder="识别银行卡自动填充" >
            </item>
            <item>
              <div slot="name">支行名称</div>
              <input slot="content" v-model="bank.bank_branch_name" placeholder="请输入支行名称" >
            </item>
          </list-item>
        </div>
      </h-view>
      <bottom-tab class="add-box">
        <!-- v-if="!isApproved || (isClear && isApproved)"-->
        <tab-button class="add-card" @click.native="addBankInfo">添加</tab-button>
      </bottom-tab>
    </h-modal>
  </h-view>
</template>
<script>
import backImg1 from '@/assets/userBind/nong.png'
import backImg2 from '@/assets/userBind/unNong.png'
export default {
  data () {
    return {
      backImg: null,
      showModalValue: false,
      bankList: [],
      isClear: false,
      certification_status: '',
      authUrl: '',
      bank: {
        bank_account_num: '',
        bank_account_name: '',
        bank_card_type: '',
        bank_full_name: '',
        bank_branch_name: '',
      },
      bankImg: '', // 银行卡图片
      getBankList: [],
    }
  },
  computed: {
    isApproved () {
      return window.localStorage.user_bp_status === 'APPROVED'
    },
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getBankInfo()
      // vm.getNpCertificationUrl()
    })
  },
  methods: {
    successCall () {
      this.hideModal()
      this.getBankInfo()
      this.bank.bank_account_num = ''
      this.bank.bank_account_name = ''
      this.bank.bank_full_name = ''
      this.bank.bank_branch_name = ''
    },
    hideModal () {
      this.showModalValue = false
      this.isClear = true
      this.bank.bank_account_num = ''
      this.bank.bank_account_name = window.localStorage.bp_name
      this.bank.bank_card_type = ''
      this.bank.bank_full_name = ''
      this.bank.bank_branch_name = ''
    },
    showModal () {
      this.showModalValue = true
      this.bankImg = ''
    },
    async checkElectonic () {
      let vm = this
      let id = window.localStorage.getItem('bp_id')
      let url = process.env.basePath + 'bp_elec_check'
      let param = {
        bp_id: id,
      }
      vm.hlsPopup.showLoading('请稍候')
      let res = await vm.$post(url, param)
      if (res.result === 'S') {
        vm.hlsPopup.hideLoading()
        vm.certification_status = res.info.certification_status
        return true
      } else {
        vm.hlsPopup.hideLoading()
        this.hlsPopup.showLongCenter(res.message)
      }
    },
    async putData () {
      let vm = this
      let bp_id = window.localStorage.getItem('bp_id')
      let isCheck = await vm.checkElectonic()
      let urlTemp = await vm.getNpCertificationUrl()
      if (urlTemp) {
        this.hlsPopup.showConfirm({
          title: '提示',
          content: '您确认提交吗?',
          onConfirm: data => {
            if (data) {
              let url = process.env.basePath + 'bp_bind_submit'
              let param = {
                master: {
                  bp_id: bp_id,
                  company_id: '2145',
                  bp_class: 'NP',
                  bp_type: window.localStorage.getItem('bp_type'),
                  business_num: window.localStorage.getItem('business_num'),
                },
              }
              vm.hlsPopup.showLoading('请稍候')
              if (isCheck) {
                vm.hlsHttp.post(url, param).then(function (res) {
                  vm.hlsPopup.hideLoading()
                  if (res.result === 'S') {
                    vm.hlsPopup.showSuccess('提交成功')
                    if (vm.certification_status === 'Y') {
                      vm.$router.push({
                        name: 'MyInfo',
                      })
                    } else if (vm.certification_status === 'N') {
                      // vm.$router.push({
                      //   name: 'Certification',
                      //   params: {
                      //     authUrl: vm.authUrl,
                      //   },
                      // })
                      const u = navigator.userAgent
                      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
                      if (isiOS) {
                        cordova.InAppBrowser.open(vm.authUrl, '_blank', 'location=yes')
                        console.log('ios')
                      } else {
                        vm.$router.push({
                          name: 'Certification',
                          params: {
                            authUrl: vm.authUrl,
                          },
                        })
                        console.log('android')
                      }
                    } else {
                      vm.$router.push({
                        name: 'MyInfo',
                      })
                    }
                  } else if (res.result === 'P') {
                    vm.hlsPopup.showLongCenter(res.message)
                    vm.$router.push({
                      name: 'MyInfo',
                    })
                  } else {
                    vm.hlsPopup.showLongCenter(res.message)
                  }
                })
              }
            }
          },
        })
      } else {
        this.hlsPopup.showLongCenter('电子签认证出错')
      }
    },
    async getNpCertificationUrl () {
      let vm = this
      let url = $config.basePath + 'auth_user_sign'
      let param = {
        phone: window.localStorage.user_phone,
      }
      hlsPopup.showLoading('请稍候')
      let res = await vm.$post(url, param)
      hlsPopup.hideLoading()
      if ((res.info.code === 0) && (res.info.data.authUrl)) {
        vm.authUrl = res.info.data.authUrl
        return vm.authUrl
      } else if ((res.info.code === 0) && (res.info.data.openId)) {
        vm.authUrl = res.info.data.openId
        return vm.authUrl
      } else {
        hlsPopup.showError(res.info.msg)
        return ''
      }
    },
    addBankInfo () {
      this.hlsPopup.showConfirm({
        title: '提示',
        content: '您确认添加吗?',
        onConfirm: data => {
          if (data === 1) {
            let bpName = window.localStorage.getItem('bp_name')
            if (
              this.bank.bank_account_num === '' ||
              this.bank.bank_account_name === '' ||
              this.bank.bank_full_name === ''
            ) {
              this.hlsPopup.showLongCenter('请输入完整字段')
            } else if (this.hlsUtil.isBankAccount(this.bank.bank_account_num)) {
              this.hlsPopup.showLongCenter('银行卡号有误')
            } else if (this.bank.bank_account_name !== bpName) {
              this.hlsPopup.showLongCenter('请输入本人银行卡')
            } else {
              let list = JSON.parse(JSON.stringify(this.bank))
              this.bankList.push(list)
              let vm = this
              let url = process.env.basePath + 'bp_bank_save'
              let param = {
                master: {
                  bp_id: window.localStorage.getItem('bp_id'),
                  bank_lists: this.bankList,
                },
              }
              vm.hlsPopup.showLoading('请稍候')
              vm.hlsHttp.post(url, param).then(function (res) {
                vm.hlsPopup.hideLoading()
                if (res.result === 'S') {
                  vm.successCall()
                  vm.hlsPopup.showLongCenter('保存成功')
                  setTimeout(vm.successCall, 2000)
                }
              })
            }
          }
        },
      })
    },
    selectType (e) {
      if (e === '0') {
        return '未知类型'
      } else if (e === '1') {
        return '借记卡'
      } else if (e === '2') {
        return '信用卡'
      }
    },
    showModalInfo (item) {
      Object.assign(this.bank, item)
      this.showModalValue = true
    },
    getBankInfo () {
      let vm = this
      let id = window.localStorage.getItem('bp_id')
      let url = process.env.basePath + 'bp_bank_query'
      let param = {
        bp_id: id,
      }
      vm.hlsPopup.showLoading('请稍候')
      vm.hlsHttp
        .post(url, param)
        .then(function (res) {
          vm.hlsPopup.hideLoading()
          if (res.result === 'S') {
            vm.getBankList = res.lists
          }
        })
        .catch(() => {
          this.hlsPopup.showLongCenter('传入参数异常')
        })
    },
    changeBgImg (item) {
      if (item.bank_full_name.indexOf('农业银行') !== -1) {
        return backImg1
      } else {
        return backImg2
      }
    },
    selectLast (item) {
      let num = item.bank_account_num
      return num.substring(num.length - 4)
    },
    deleteFun (e) {
      this.hlsPopup.showConfirm({
        title: '提示',
        content: '您确认删除吗?',
        onConfirm: data => {
          if (data === 1) {
            let index = this.getBankList.findIndex(item => {
              if (item.bank_account_num === e) {
                return true
              }
            })
            this.getBankList.splice(index, 1)
            let vm = this
            let url = process.env.basePath + 'bp_bank_delete'
            let param = {
              'master': {
                'bp_id': window.localStorage.getItem('user_id'),
                'bank_account_num': e,
              },
            }
            vm.hlsPopup.showLoading('请稍候')
            vm.hlsHttp.post(url, param).then(function (res) {
              vm.hlsPopup.hideLoading()
              if (res.result === 'S') {
                vm.hlsPopup.showSuccess('删除成功')
              } else {
                vm.hlsPopup.showLongCenter(res.message)
              }
            })
          }
        },
      })
    },
    ocrShow (ocrType, type) {
      let vm = this
      hlsPopup.showActionSheet({
        titleText: '请选择照片',
        buttonArray: ['拍照', '从相册取'],
        callback: index => {
          if (index === 0) {
            vm.openCamera(ocrType, type)
          } else {
            vm.takePicture(ocrType, type)
          }
        },
      })
    },
    openCamera (ocrType, type) {
      let vm = this
      let cameraoptions = {
        quality: 60,
        width: 1843,
        height: 1382,
      }
      let success = function (imgdata) {
        if (!imgdata) {
          hlsPopup.showLongCenter('请拍照')
        } else {
          if (ocrType === 'idCard') {
            type === 'front'
              ? ((vm.idCardFront = imgdata),
              vm.idCardIdentify(imgdata, 'idCard'),
              (vm.idCardFrontEditFlag = true))
              : ((vm.idCardBack = imgdata),
              vm.idCardBackIdentify(imgdata, 'idCard'),
              (vm.idCardBackEditFlag = true))
          } else if (ocrType === 'idCardSp') {
            // 配偶身份证识别
            type === 'front'
              ? ((vm.idCardFrontSp = imgdata),
              vm.idCardIdentify(imgdata, 'idCardSp'),
              (vm.idCardFrontSpEditFlag = true))
              : ((vm.idCardBackSp = imgdata),
              vm.idCardBackIdentify(imgdata, 'idCardSp'),
              (vm.idCardBackSpEditFlag = true))
          } else if (ocrType === 'bankCard') {
            vm.bankImg = imgdata
            vm.bankCardIdentify(imgdata)
          }
        }
      }
      let error = function () {
        hlsPopup.showLongCenter('请拍照')
      }
      hlsUtil.openCamera(cameraoptions, success, error)
    },
    takePicture (ocrType, type) {
      let vm = this
      var cameraoptions = {
        quality: 70,
        width: 1843,
        height: 1382,
        maxCount: 1,
      }
      let success = function (imgUrl) {
        if (imgUrl.length === 0) {
          hlsPopup.showLongCenter('请选择一张图片')
        } else {
          if (ocrType === 'idCard') {
            type === 'front'
              ? ((vm.idCardFront = imgUrl[0]),
              vm.idCardIdentify(imgUrl[0], 'idCard'),
              (vm.idCardFrontEditFlag = true))
              : ((vm.idCardBack = imgUrl[0]),
              vm.idCardBackIdentify(imgUrl[0], 'idCard'),
              (vm.idCardBackEditFlag = true))
          } else if (ocrType === 'idCardSp') {
            // 配偶身份证识别
            type === 'front'
              ? ((vm.idCardFrontSp = imgUrl[0]),
              vm.idCardIdentify(imgUrl[0], 'idCardSp'),
              (vm.idCardFrontSpEditFlag = true))
              : ((vm.idCardBackSp = imgUrl[0]),
              vm.idCardBackIdentify(imgUrl[0], 'idCardSp'),
              (vm.idCardBackSpEditFlag = true))
          } else if (ocrType === 'bankCard') {
            vm.bankImg = imgUrl[0]
            vm.bankCardIdentify(imgUrl[0])
          }
        }
      }
      let error = function () {
        hlsPopup.showLongCenter(error)
      }
      vm.hlsUtil.takePicture(cameraoptions, success, error)
    },
    // 银行卡识别
    bankCardIdentify (fileUrl) {
      let vm = this
      hlsPopup.showLoading('正在识别')
      let url = process.env.ocrPath + '/baidu/ocr/bankCard'
      hlsUtil.baiduOcr(fileUrl, url, function (res) {
        hlsPopup.hideLoading()
        let result = res.result.result
        vm.bank.bank_account_num = result.bank_card_number.replace(/\s*/g, '')
        vm.bank.bank_full_name = result.bank_name
        vm.bank.bank_card_type = result.bank_card_type
      })
    },
  },
}
</script>
<style lang="less">
  #np-bank-card {
      .info {
        height: 70px;
        background-color: rgba(142, 195, 30, 0.1);
        .info-icon {
          height: 20px;
          padding-top: 20px;
          display: flex;
          align-items: center;
          img {
            width: 15.8px;
            height: 15.8px;
            margin-left: 17.1px;
          }
          span {
            font-family: PingFangSC-Semibold;
            font-size: 14px;
            color: #8ec31e;
            margin-left: 9px;
            letter-spacing: 0.5px;
            line-height: 20px;
          }
        }
        p {
          font-family: PingFangSC-Regular;
          font-size: 13px;
          color: #656464;
          width: 310px;
          margin-left: 42px;
          letter-spacing: 0.4px;
          line-height: 18px;
          margin-top: 8px;
        }
      }
      .my-card {
        .top {
          width: 320px;
          margin: 0 auto;
          margin-top: 13px;
          .left {
            height: 32px;
            display: flex;
            align-items: center;
            float: left;
            .icon {
              width: 18px;
              height: 20px;
              margin-right: 4px;
            }
            .top-word {
              font-family: PingFangSC-Semibold;
              font-size: 15px;
              color: @headerColor;
              letter-spacing: 0.46px;
              .sum {
                font-family: PingFangSC-Semibold;
                font-size: 15px;
                color: #4d5d6c;
                letter-spacing: 0.46px;
              }
            }
          }
          .icon-right {
            width: 34px;
            height: 34px;
            float: right;
          }
        }
        .clear {
          clear: both;
        }
        .card-content {
          width: 350px;
          padding-left: 28px;
          overflow: hidden;
          margin-top: 16px;
          li {
            margin-bottom: 10px;
            .slider {
              height: 100%;
              margin-left: -14px;
            }
          }
          .my-bank-card {
            width: 320px;
            height: 190px;
            box-shadow: 0 5px 20px 0 rgba(101, 101, 101, 0.25);
            border-radius: 6px;
            background-size: 370px 240px;
            background-position: -20px;
            .card-info {
              font-family: PingFangSC-Medium;
              color: #ffffff;
              margin-left: 18px;
              padding-top: 15px;
              .name,
              .card-type {
                font-size: 16px;
                letter-spacing: 5.5px;
                line-height: 24px;
              }
              .card-type {
                display: block;
                margin-top: 9px;
              }
              .number {
                font-size: 12px;
                letter-spacing: 0;
                line-height: 16px;
                margin-top: 33px;
                display: block;
                margin-top: 33px;
              }
              .card-number {
                display: block;
                font-family: Avenir-Heavy;
                font-size: 16px;
                color: #ffffff;
                letter-spacing: 6px;
                line-height: 24px;
              }
            }
          }
        }
      }
      .swipeout-list .item .function {
        left: 330px;
        border-radius: 6px;
        width: 54px;
        height: 190px;
        background: url("../../../assets/userBind/delete.png") 16px 84.9px #fde5e8
        no-repeat;
        background-size: 20px 20px;
      }
    .save {
    color: #fdb62f;
    border-radius: 4px;
    border: 1px solid #fdb62f;
    background-color: #fafafa;
  }
       .modal-content {
    width: 100%;
    height: 75%;
    position: absolute;
    top: 25%;
    background-color: #fff;
    overflow-y: scroll;
    .modal-content-add-top {
      width: 320px;
      height: 34px;
      line-height: 34px;
      padding-top: 10px;
      background-color: #fff;
      padding-bottom: 40px;
      position: fixed;
      left: 28px;
      span {
        font-family: PingFangSC-Semibold;
        font-size: 15px;
        color: @headerColor;
        letter-spacing: 0.47px;
      }
      img {
        width: 34px;
        height: 34px;
        float: right;
      }
    }
    .addBack {
      display: block;
      width: 320px;
      margin: 0 auto;
      margin-top: 50px;
      border-radius: 6px;
      margin-bottom: 17px;
    }

    .card-Info {
      margin-bottom: 220px;
    }

  }
     .add-card {
    width: 358px;
    height: 40px;
    background: @headerColor;
    border-radius: 4px;
    color: #fff;
  }
    }
    .modal {
  background-color: rgba(0, 0, 0, 0) !important;
}
</style>