<template>
  <div class="bind-card">
    <cy-info-title>
      绑定实体卡信息
      <div v-if="$route.query.type !=='see'" slot="right">
        <el-button type="text" @click="addCard">添加</el-button>
      </div>
    </cy-info-title>
    <cy-comm-table
      style="margin-top: 10px; width: 100%"
      :columns="tableColumns"
      :data="tableData"
      :count="tableDataCount"
    />
    <activation
      ref="activationRef"
      :active-info="curActiveRow"
      :account-name="accountName"
      :account-number="accountNumber"
    />
    <cy-dialog ref="dialog" title="绑定实体卡" width="700px" top="10vh">
      <el-form
        ref="cardFormRef"
        :model="cardForm"
        :rules="cardRules"
        label-position="left"
        label-width="150px"
      >
        <el-form-item label="是否为交通银行：" style="width: 100%;" prop="hasBankOfCommunications">
          <el-radio-group v-model="cardForm.hasBankOfCommunications">
            <el-radio :label="0">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="cardForm.hasBankOfCommunications === 0">
          <el-form-item label="账户类型：" style="width: 100%;" prop="bindAcctTp">
            <el-select
              v-model="cardForm.bindAcctTp"
              placeholder="请选择账户类型"
              style="width: 100%"
              disabled
            >
              <el-option
                v-for="item in constant.memberAccountType"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="银行卡号：" style="width: 100%;" prop="bindAcctNo">
            <el-input
              v-model="cardForm.bindAcctNo"
              placeholder="请输入银行卡号"
            />
          </el-form-item>
          <el-form-item label="账户名称：" style="width: 100%;" prop="bindAcctNoAcctNme">
            <el-input
              v-model="cardForm.bindAcctNoAcctNme"
              placeholder="请输入账户名称"
            />
          </el-form-item>
        </template>
        <template v-if="cardForm.hasBankOfCommunications === 1">
          <el-form-item label="开户银行：" class="form-required" style="width: 100%;" prop="bankName">
            <el-input
              v-model="cardForm.bankName"
              placeholder="请输入开户银行"
            />
          </el-form-item>
          <el-form-item label="账户类型：" style="width: 100%;" prop="bindAcctTp">
            <el-select
              v-model="cardForm.bindAcctTp"
              placeholder="请选择账户类型"
              style="width: 100%"
              disabled
            >
              <el-option
                v-for="item in constant.memberAccountType"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="银行卡号：" style="width: 100%;" prop="bindAcctNo">
            <el-input
              v-model="cardForm.bindAcctNo"
              placeholder="请输入银行卡号"
            />
          </el-form-item>
          <el-form-item label="账户名称：" style="width: 100%;" prop="bindAcctNoAcctNme">
            <el-input
              v-model="cardForm.bindAcctNoAcctNme"
              placeholder="请输入账户名称"
            />
          </el-form-item>
          <el-form-item label="银行开户行行号：" style="width: 100%;" prop="bindAcctBankNo">
            <el-input
              v-model="cardForm.bindAcctBankNo"
              placeholder="请输入银行开户行行号"
            >
              <template #append>
                <el-popover
                  placement="top"
                  width="400"
                  trigger="click"
                >
                  <div>
                    <div>【银行开户行号】：</div>
                    <div>是指为银行分支机构分配的唯一识别号码，由12位数字组成。</div>
                    <div>【查询方法】：</div>
                    <div>使用银行卡的卡号段查询开户行信息。您可以访问银行的官方网站或使用银行的手机应用程序进行查询。例如，您可以访问中国工商银行的官网，在首页点击“查询服务” - “银行卡信息查询”，输入卡号段（622280）后点击查询。</div>
                  </div>
                  <i slot="reference" class="el-icon-warning" style="color: #FE7D0B; font-size: 24px; cursor: pointer; " />
                </el-popover>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="开户支行名称：" style="width: 100%;" prop="branchBankName">
            <el-input
              v-model="cardForm.branchBankName"
              placeholder="请输入开户支行名称"
            >
              <template #append>
                <el-popover
                  placement="top"
                  width="400"
                  trigger="click"
                >
                  <div>
                    <div>【银行开户支行名称】：</div>
                    <div>指开户行的全称，包括银行名称和分支机构名称。例如，中国工商银行北京分行、中国建设银行上海分行、中国农业银行广州分行。</div>
                    <div>【查询方法】：</div>
                    <div>您可以使用银行的查询工具或致电银行客服进行查询。例如，您可以访问中国人民银行的官网，在首页点击“金融服务” - “银行查询” - “联行号查询”，输入开户行号（10210000）后点击查询</div>
                  </div>
                  <i slot="reference" class="el-icon-warning" style="color: #FE7D0B; font-size: 24px; cursor: pointer; " />
                </el-popover>
              </template>
            </el-input>
          </el-form-item>
        </template>
      </el-form>
      <div v-if="cardForm.hasBankOfCommunications === 1" class="tips-cont">
        <span>温馨提示：</span>当实体卡非交通银行时，资金从您的账户提款至您的实体卡时，会产生手续费。具体手续费以银行实际收取为准。
      </div>
      <div class="submit-btn">
        <el-button @click="() => { $refs.dialog.show = false }">取消</el-button>
        <el-button v-if="$route.query.type !== 'see'" type="primary" @click="confirm">提交</el-button>
      </div>
    </cy-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { updateBindCardInfo } from '@/api/accountCenter/cyAccountManage'

export default {
  components: {
    Activation: () => import('./Activation.vue')
  },
  props: {
    customerType: {
      type: [String, Number],
      default: ''
    },
    detailsInfo: {
      type: Array,
      default: () => []
    },
    accountName: {
      type: String,
      default: ''
    },
    accountNumber: {
      type: String,
      default: ''
    },
    operateId: {
      type: [String, Number],
      default: ''
    },
    basicInfoId: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    responsible: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableData: [],
      tableDataCount: 0,
      columns: [
        {
          label: '开户银行',
          prop: 'bankName',
          showTooltip: true
        },
        {
          label: '账户类型',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ row.bindAcctTp !== null && row.bindAcctTp === 0 ? '对公' : '个人' }</div>
            )
          }
        },
        {
          label: '银行卡号',
          showTooltip: true,
          prop: 'bindAcctNo'
        },
        {
          label: '账户名称',
          showTooltip: true,
          prop: 'bindAcctNoAcctNme'
        },
        {
          label: '银行开户行行号',
          prop: 'bindAcctBankNo',
          showTooltip: true
        },
        {
          label: '开户支行名称',
          prop: 'branchBankName',
          showTooltip: true
        },
        {
          label: '核验状态',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getVerifyDesc(row.bindSts) }</div>
            )
          }
        },
        {
          label: '绑定状态',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getBindDesc(row.bindAccSts) }</div>
            )
          }
        },
        {
          label: '绑定审批状态',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getApprovalDesc(row.managerApproverSts) }</div>
            )
          }
        },
        {
          label: '入金金额',
          showTooltip: true,
          render: (h, row) => {
            return (
              <cy-amount-input v-model={ row.actvtAmt } disabled={true} ></cy-amount-input>
            )
          }
        },
        {
          label: '操作',
          render: (h, row) => {
            const btnList = [
              {
                msg: '去激活',
                icon: 'iconfont icon-orange icon-a-Group957',
                power: '',
                activePower: [2],
                category: 'activation'
              },
              {
                msg: '删除',
                icon: 'iconfont icon-orange icon-a-Group991',
                power: '',
                category: 'delete'
              }
              // {
              //   msg: '刷新',
              //   icon: 'iconfont icon-orange icon-shuaxin',
              //   power: '',
              //   category: 'refresh'
              // }
            ]
            const options = btnList.map((item) => {
              return (
                this.tablePower({ item, row }) &&
                <span class='table-icon-box' style='font-size: 14px' onClick={() => {
                  this.optionsClick(item.category, row)
                }}>
                  { item.msg }
                </span>
              )
            })
            return <div>{options}</div>
          },
          width: 190
        }
      ],
      cardForm: {
        hasBankOfCommunications: 0,
        bindAcctTp: 0,
        bindAcctNo: '',
        bindAcctNoAcctNme: '',
        branchBankName: '',
        bindAcctBankNo: ''
      },
      cardRules: {
        hasBankOfCommunications: [
          { required: true, message: '请选择是否为交通银行', trigger: 'blur' }
        ],
        bindAcctTp: [
          { required: true, message: '请选择账户类型', trigger: 'blur' }
        ],
        bindAcctNo: [
          { required: true, message: '请输入银行卡号', trigger: 'blur' }
        ],
        bindAcctNoAcctNme: [
          { required: true, message: '请输入账户名称', trigger: 'blur' }
        ],
        branchBankName: [
          { required: true, message: '请输入开户银行名称', trigger: 'blur' }
        ],
        bindAcctBankNo: [
          { required: true, message: '请输入银行开户行行号', trigger: 'blur' }
        ]
      },
      curActiveRow: {}
    }
  },
  computed: {
    ...mapGetters(['constant']),
    tableColumns() {
      if (this.$route.query.type !== 'see') {
        return this.columns
      }
      return this.columns.filter(item => item.label !== '操作')
    },
    tablePower() {
      return ({ item, row }) => {
        const { power, activePower } = item
        if (power) {
          return false
        }
        if (activePower && activePower.length) {
          if (row && row.bindSts && activePower.includes(row.bindSts)) {
            return true
          }
          return false
        }
        return true
      }
    }
  },
  watch: {
    detailsInfo: {
      handler(val) {
        if (val && val.length) {
          this.tableData = val
          this.tableDataCount = val.length
        }
      },
      immediate: true
    },
    customerType: {
      handler(val) {
        if (val !== null || val !== '') {
          // if (val === 2) {
          //   this.cardForm.bindAcctTp = 1
          // } else {
          //   this.cardForm.bindAcctTp = 0
          // }
          this.cardForm.bindAcctTp = 0
        }
      },
      immediate: true
    }
  },
  methods: {
    confirm() {
      if (this.cardForm.hasBankOfCommunications === 1 && !this.cardForm.bankName) {
        this.$message.warning('请输入开户银行名称')
        return
      }

      this.$refs.cardFormRef.validate(async(valid) => {
        if (valid) {
          const params = {
            ...this.cardForm,
            bocomVipAccountBasicInfoId: this.operateId,
            bocomBasicInfoId: this.basicInfoId
          }
          const res = await updateBindCardInfo(params)

          if (res) {
            this.$message.success('绑定实体卡信息修改成功')
            this.$router.go(0)
          }
        }
      })
    },
    // 是否位交行change
    isBankChange(val) {
      if (val === 0) {
        this.cardForm.bindAcctTp = 0
      }
      // 不是交行且账户类型是个体工商户的且账户类型是个人的时候账户名称禁用且默认填充负责人字段
      if (val === 1 && this.customerType === 1 && this.cardForm.bindAcctTp === 1) {
        this.cardForm.bindAcctNoAcctNme = this.responsible
      }
    },
    // 不是交行的账户类型change
    bindAcctTpChange(val) {
      if (val === 1 && this.customerType === 1) {
        this.cardForm.bindAcctNoAcctNme = this.responsible
      } else {
        this.cardForm.bindAcctNoAcctNme = ''
      }
    },
    optionsClick(type, row) {
      if (type === 'activation') {
        this.curActiveRow = row
        this.$refs.activationRef.openDialog(true)
      } else if (type === 'delete') {
        this.deleteCard(row)
      } else if (type === 'refresh') {
        this.refreshCardStatus(row.id)
      }
    },
    deleteCard(row) {
      if (row.moneyConfirmTime && !this.isDelInToday(row.moneyConfirmTime)) {
        this.$message.warning('入金激活后24小时内不能删除绑定的实体卡')
        return
      }
      this.$confirm('您将删除该绑定实体卡，删除后无法恢复。请确认是否继续？', '删除绑定实体卡', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await updateBindCardInfo({ ...row })

        if (res) {
          this.$message.success('绑定实体卡信息修改成功')
          this.$router.go(0)
        }
      })
    },
    // 刷新银行卡状态
    async refreshCardStatus(refreshId) {
      // const res = await refreshBoundCardStatus({ id: refreshId })
      // if (res.success) {
      //   this.$message.success('银行卡信息刷新成功')
      //   this.$router.go(0)
      // }
    },
    addCard() {
      if (this.tableData.length > 0) {
        this.$message.warning('一个账户只允许绑定一个实体账户，如需更改，请先删除已绑定实体账户')
        return
      }
      this.$refs.dialog.show = true
    },
    getVerifyDesc(status) {
      const verifyMap = {
        0: '初态',
        1: '正常',
        2: '入金激活待确认',
        3: '待出金验证',
        4: '出金待确认',
        5: '出金失败',
        6: '未出金',
        7: '验证失败',
        8: '入金激活次数超限或超时'
      }
      if (status !== null) {
        return verifyMap[status] || ''
      }
      return ''
    },
    getBindDesc(status) {
      const bindMap = {
        0: '流程中',
        1: '可用',
        2: '不可用'
      }
      if (status !== null) {
        return bindMap[status] || ''
      }
      return ''
    },
    getApprovalDesc(status) {
      const approvalMap = {
        0: '无需审批',
        1: '客户经理审批流程中',
        2: '客户经理审批通过',
        3: '客户经理审批拒绝',
        4: '网银审批流程中',
        5: '网银审批通过',
        6: '网银审批拒绝'
      }
      if (status !== null) {
        return approvalMap[status] || ''
      }
      return ''
    },
    isDelInToday(date) {
      const timeDelay = 24 * 60 * 60 * 1000
      const now = new Date().getTime()
      const dateTime = new Date(date).getTime()

      return dateTime - now > timeDelay
    }
  }
}
</script>

<style lang="scss" scoped>
.tips-cont {
  width: 100%;
  font-size: 14px;
  margin: 40px auto 30px;
  span {
    color: #FE7D0B;
  }
}
</style>
