<template>
  <div class="main-content">
    <div v-for="(item, index) in companyList" :key="index">
      <div v-if="item.vipAccountBasicInfoList && item.vipAccountBasicInfoList.length === 0 && item.customerStatus === '生效'" class="company-box-cont">
        <div class="company-box">
          <div class="company-title">
            <div>
              <div class="supplier">供应商企业名称</div>
              <div class="supplier-name">{{ item.customerName }}</div>
            </div>
            <div class="supplier-operation">
              <div>客户状态： {{ item.customerStatus }}</div>
            </div>
          </div>
          <div
            class="normal"
            style="display: flex; justify-content: space-between"
          >
            <div>客户号{{ item.customerNumber }}</div>
            <!-- v-tooltip="addAccountTip" -->
            <!-- <div>
              <el-button
                v-if="item.addVipAccount === 1"
                :id="`new-account-${index}`"
                type="primary"
                @click="openActivation(item.bocomBasicInfoId)"
              >新建账户</el-button>
            </div> -->
          </div>
        </div>
        <empty
          v-if="item.customerStatus === '生效'"
          type="cyAccountManage"
          :margin-top="'5vh'"
          :add-id="item.bocomBasicInfoId"
          :customer-name="item.customerName"
          :customer-status="item.customerStatus"
          :customer-number="item.customerNumber"
        />
      </div>
      <div v-if="item.vipAccountBasicInfoList && item.vipAccountBasicInfoList.length > 0" class="company-box-cont">
        <div class="company-box">
          <div class="company-title">
            <div>
              <div class="supplier">供应商企业名称</div>
              <div class="supplier-name">{{ item.customerName }}</div>
            </div>
            <div class="supplier-operation">
              <div>客户状态： {{ item.customerStatus }}</div>
            </div>
          </div>
          <div
            class="normal"
            style="display: flex; justify-content: space-between"
          >
            <div>客户号{{ item.customerNumber }}</div>
            <!-- v-tooltip="addAccountTip" -->
            <div>
              <el-button
                v-if="item.addVipAccount === 1"
                :id="`new-account-${index}`"
                type="primary"
                @click="openActivation(item.bocomBasicInfoId)"
              >新建账户</el-button>
            </div>
          </div>
        </div>
        <cy-comm-table
          style="margin-top: 10px; width: 100%"
          :columns="columns"
          :data="item.vipAccountBasicInfoList"
          :count="0"
        />
      </div>
    </div>
    <activation
      ref="activationRef"
      :active-info="curActiveRow"
      :account-name="activeAccountName"
      :account-number="activeAccountNumber"
    />
    <authorization ref="authorizationRef" :active-info="authActiveInfo" :fresh-page="true" />
  </div>
</template>

<script>
import driverMix from '../mixins/driver.js'
import {
  addMemberRegister,
  refreshMemberRegister,
  resetAuthCode
} from '@/api/accountCenter/cyAccountManage'

export default {
  components: {
    Activation: () => import('./components/Activation.vue'),
    Authorization: () => import('./components/Authorization.vue'),
    Empty: () => import('../components/Empty.vue')
  },
  mixins: [driverMix],
  props: {
    infoData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      companyList: [],
      columns: [
        // {
        //   label: '序号',
        //   index: true
        // },
        {
          label: '账号',
          prop: 'accountNumber',
          showTooltip: true,
          width: 140
        },
        {
          label: '账户名称',
          showTooltip: true,
          prop: 'accountName',
          width: 180
        },
        {
          label: '账户状态',
          prop: 'accountStatusReal',
          showTooltip: true
        },
        {
          label: '授权代理人授权状态',
          width: 150,
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getAuthorizationDesc(row.authorizationStatus) }</div>
            )
          }
        },
        {
          label: '法人授权状态',
          width: 120,
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getlegalDesc(row.legalAuthorizationStatus) }</div>
            )
          }
        },
        {
          label: '付款方数量',
          width: 100,
          render: (h, row) => {
            return (
              <span
                onClick={() => {
                  this.detailClick('number', row)
                }}
                style='color: #FE7D0B; cursor: pointer'
              >
                {row.silentAccountNum}
              </span>
            )
          }
        },
        {
          label: '实体账号',
          width: 160,
          render: (h, row, $index) => {
            return (row && row.bindAccountInfoList && row.bindAccountInfoList.length &&
            row.bindAccountInfoList[0].bindAcctNo
            ) ? (
                <span
                  onClick={() => {
                    this.detailClick('physicalAccount', row)
                  }}
                  style='color: #FE7D0B; cursor: pointer'
                >
                  {row.bindAccountInfoList[0].bindAcctNo}
                </span>
              ) : (
                <span
                  class={`binding-account-${row.parentIdx}-${$index}`}
                  style='color: #FE7D0B; cursor: pointer'
                  onClick= { () => {
                    this.goBindCardPage(row)
                  } }
                >
                  去绑定
                </span>
              )
          }
        },
        {
          label: '绑定账户',
          width: 170,
          render: (h, row) => {
            return (
              <div>{ (row.bindAccountInfoList && row.bindAccountInfoList[0]) ? row.bindAccountInfoList[0].bindAcctNoAcctNme : '' }</div>
            )
          }
        },
        {
          label: '账户核验状态',
          width: 140,
          render: (h, row) => {
            return (
              <div>{ (row.bindAccountInfoList && row.bindAccountInfoList[0]) ? this.getVerifyStatus(row.bindAccountInfoList[0].bindSts) : '' }</div>
            )
          }
        },
        {
          label: '余额',
          width: 120,
          render: (h, row) => {
            return (
              <div>{ (row.accountBalance && row.currency) ? `${row.accountBalance}-${row.currency}` : '' }</div>
            )
          }
        },
        {
          label: '可用余额',
          width: 120,
          render: (h, row) => {
            return (
              <div>{ (row.availableBalance && row.currency) ? `${row.availableBalance}-${row.currency}` : '' }</div>
            )
          }
        },
        {
          label: '冻结金额',
          render: (h, row) => {
            return (
              <div>{ (row.freezeAmount && row.currency) ? `${row.freezeAmount}-${row.currency}` : '' }</div>
            )
          }
        },
        {
          label: '提示',
          render: (h, row) => {
            if (row.accountStatus === 1) {
              if (row.authorizationStatus === 1 && row.legalAuthorizationStatus === 1) {
                return <div>请联系客服</div>
              }
              if (row.authorizationStatus === 2 && row.legalAuthorizationStatus === 2) {
                return <div>请联系客服</div>
              }
              if (row.authorizationStatus === 3 && row.legalAuthorizationStatus === 3) {
                return <div>请联系客服</div>
              }
            }
            return <div></div>
          }
        },
        {
          label: '开通日期',
          prop: 'openTime',
          showTooltip: true,
          width: 140
        },
        {
          label: '操作',
          render: (h, row, $index) => {
            const curIndex = $index

            const btnList = [
              {
                msg: '查看账户信息',
                icon: 'iconfont icon-orange icon-a-Group957',
                power: '',
                category: 'see'
              },
              {
                msg: '去授权',
                icon: `iconfont icon-orange icon-a-Group1022
                authorization-${row.parentIdx}-${curIndex}`,
                power: '',
                authPower: [0, 1, 2, 3],
                category: 'authorization'
              },
              {
                msg: '入金激活',
                icon: `iconfont icon-orange icon-icon-active activation-${row.parentIdx}-${curIndex}`,
                power: '',
                activePower: [2],
                category: 'activation'
              },
              {
                msg: '刷新登记薄',
                icon: 'iconfont icon-orange icon-a-Group8131',
                power: '',
                category: 'refreshRegister'
              },
              {
                msg: '修改绑卡信息',
                icon: 'iconfont icon-orange icon-a-Group8151',
                power: '',
                category: 'seeBindCard'
              },
              {
                msg: '修改付款方信息',
                icon: 'iconfont icon-orange icon-a-Group8151',
                power: '',
                category: 'number'
              }
              // {
              //   msg: '账单流水',
              //   icon: 'iconfont icon-orange icon-a-Group957',
              //   power: '',
              //   category: 'flowingWater'
              // }
            ]
            const options = btnList.map((item) => {
              return (
                this.tablePower({ item, row }) &&
                <el-tooltip
                  class='item'
                  effect='dark'
                  content={item.msg}
                  placement='top'
                >
                  <span class='table-icon-box'>
                    <i
                      class={item.icon}
                      onClick={() => {
                        this.detailClick(item.category, row)
                      }}
                    ></i>
                  </span>
                </el-tooltip>
              )
            })
            return <div>{options}</div>
          },
          width: 240
        }
      ],
      authActiveInfo: [], // 待授权弹窗组件入参
      curActiveRow: {}, // 入金激活组件入参
      activeAccountName: '',
      activeAccountNumber: '',
      timeReduce: 48 * 60 * 60 * 1000
    }
  },
  computed: {
    tablePower() {
      return ({ item, row }) => {
        const { power, activePower, category } = item
        // && !this.btnPermission.includes(power)
        // row.bindAccountInfoList[0].bindSts
        if (power) {
          return false
        }
        if (activePower && activePower.length) {
          if (row.bindAccountInfoList &&
            row.bindAccountInfoList.length &&
            activePower.includes(row.bindAccountInfoList[0].bindSts)) {
            return true
          }
          return false
        }
        if (category === 'authorization') {
          if (row.accountStatus === 1) {
            if (row.authorizationStatus === 0 && row.legalAuthorizationStatus === 0) {
              return true
            }
            if (row.authorizationStatus === 0 && row.legalAuthorizationStatus === 4) {
              return true
            }
            if (row.authorizationStatus === 4 && row.legalAuthorizationStatus === 0) {
              return true
            }
          }
          return false
        }
        if (category === 'seeBindCard' || category === 'number') {
          if (row.silentAccountNum > 0) {
            return true
          }
          return false
        }
        return true
      }
    }
  },
  watch: {
    infoData: {
      handler(val) {
        if (val && Object.keys(val).length) {
          this.companyList = val
          if (this.companyList.length) {
            let i = 0
            while (i < this.companyList.length) {
              if (this.companyList[i].customerStatus === '生效') {
                if (this.companyList[i].vipAccountBasicInfoList && this.companyList[i].vipAccountBasicInfoList.length) {
                  this.companyList[i].vipAccountBasicInfoList.forEach((el, innerIdx) => {
                    el.parentIdx = i // 外层的客户编号索引
                    // 登记薄失效引导
                    if (el.accountStatus === 2) {
                      this.createAuthorizationTimeoutGuide(i)
                    }

                    // 入金激活失效引导
                    // if (el.bindAccountInfoList && el.bindAccountInfoList.length && el.bindAccountInfoList[0].bindSts === 8) {
                    //   this.createDepositInvalidGuide(i)
                    // }

                    // 表格去授权引导
                    // if (el.accountStatus === 1 && el.authorizationStatus !== 4) {
                    //   this.$nextTick(() => {
                    //     this.createTableAuthorizationGuide(el.parentIdx, innerIdx)
                    //   })
                    // }
                  })
                }
              }
              i++
            }
            setTimeout(() => {
              // 默认只显示第一个账户的授权状态 状态包含入金激活引导 授权引导 绑卡引导
              this.initDriver(0, 0)
            }, 300)
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    // setTimeout(() => {
    //   this.initDriver()
    // })
  },
  methods: {
    detailClick(type, row) {
      // query type: 'edit' 编辑 | 'see' 查看 | 'add' 新增
      if (type === 'activation') {
        this.curActiveRow = row.bindAccountInfoList[0]
        this.activeAccountName = row.accountName
        this.activeAccountNumber = row.accountNumber
        this.$refs.activationRef.openDialog(true)
      } else if (type === 'see') {
        // 查看账户信息
        this.$router.push({
          name: 'CyAccountaccountDetails',
          query: { type: 'see', id: row.id }
        })
      } else if (type === 'physicalAccount') {
        // 查看实体账户
        this.$router.push({
          name: 'CyAccountaccountSee',
          query: { type: 'bindCard', id: row.id }
        })
      } else if (type === 'flowingWater') {
        // 账单流水
        this.$router.push({
          name: 'CyAccountBillFlowingWater',
          params: { id: '3123123' }
        })
      } else if (type === 'number') {
        if (row.accountStatusReal !== '生效') {
          this.$message.warning('该登记薄不是可收可付状态，暂时无法查看')
          return
        }
        // 付款方数量
        this.$router.push({
          name: 'CyAccountaccountEdit',
          query: {
            type: 'edit',
            id: row.id,
            editId: row.bocomBasicInfoId
          }
        })
      } else if (type === 'authorization') {
        if (row.noticeInfoList.length === 0) {
          this.$message.warning('授权信息有误，请重试')
          return
        }
        // 去授权 -- 这里做一个判断，如果二维码认证时间过期 需要重新调用生成二维码接口
        const nowTimeTemp = new Date().getTime()
        const qrCodeValidTime = new Date(row.noticeInfoList[0].qrCodeEffectTime).getTime() + this.timeReduce

        if (qrCodeValidTime - nowTimeTemp <= 0) {
          this.resetQrCodeUri(row)
        } else {
          this.$refs.authorizationRef.openDialog(true)

          this.authActiveInfo = row.noticeInfoList
        }
      } else if (type === 'refreshRegister') {
        this.refreshRegister(row)
      } else if (type === 'seeBindCard') {
        this.$router.push({
          name: 'CyAccountaccountBind',
          query: {
            type: 'edit',
            id: row.id
          }
        })
      }
    },
    // 开通长银账户
    async openActivation(addId) {
      // this.$router.push({
      //   name: 'CyAccountaccountAdd',
      //   query: { type: 'add', addId: addId }
      // })
      const res = await addMemberRegister({ bocomBasicInfoId: addId, Loading: true })

      console.log('addMemberRegister----', res)

      if (res.success && res.data && res.data.authorizationStatus !== 4) {
        this.authActiveInfo = res.data.noticeInfoList
        // 回调触发微信授权
        this.$refs.authorizationRef.openDialog(true)
      }
    },
    // 重置授权二维码
    async resetQrCodeUri(curRow) {
      this.authActiveInfo = []
      const res = await resetAuthCode({ id: curRow.id })

      if (res.success) {
        if ('noticeInfoList' in res.data) {
          this.authActiveInfo = res.data.noticeInfoList
        } else if (Array.isArray(res.data)) {
          this.authActiveInfo = res.data
        } else {
          this.authActiveInfo.push({
            qrCodeEffectTime: res.data.qrCodeEffectTime,
            qrCode: res.data.qrCode,
            authenticator: res.data.authenticator
          })
        }
        this.$refs.authorizationRef.openDialog(true)
      }
    },
    // 刷新登记薄
    async refreshRegister(row) {
      const res = await refreshMemberRegister({ id: row.id, Loading: true })

      if (res.success) {
        this.$message.success('刷新成功')
        this.$router.go(0)
      }
    },
    // 去绑卡页面
    goBindCardPage(row) {
      if (row.accountStatusReal !== '生效') {
        this.$message.warning('该登记薄不是可收可付状态，暂时无法绑卡')
        return
      }
      this.$router.push({
        name: 'CyAccountaccountBind',
        query: {
          type: 'bindCard',
          id: row.id
        }
      })
    },
    // 获取授权状态描述
    getAuthorizationDesc(status) {
      const descMap = {
        0: '待用户授权',
        1: '银行审核中',
        2: '授权失败（用户拒绝）',
        3: '授权失败（银行拒绝）',
        4: '授权成功'
      }
      if (status !== null) {
        return descMap[status] || ''
      }
      return ''
    },
    // 法人授权状态
    getlegalDesc(status) {
      const map = {
        0: '待用户授权',
        1: '银行审核中',
        2: '授权失败（用户拒绝）',
        3: '授权失败（银行拒绝）',
        4: '授权成功'
      }
      return map[status] || ''
    },
    // 获取绑定状态
    getBindStatus(status) {
      const bindMap = {
        0: '流程中',
        1: '可用',
        2: '不可用'
      }

      if (status !== null) {
        return bindMap[status] || ''
      }
      return ''
    },
    // 获取绑定审核状态
    getBindApprovalStatus(status) {
      const approvalMap = {
        0: '无需审批',
        1: '客户经理审批流程中',
        2: '客户经理审批通过',
        3: '客户经理审批拒绝',
        4: '网银审批流程中',
        5: '网银审批通过',
        6: '网银审批拒绝'
      }
      if (status !== null) {
        return approvalMap[status] || ''
      }
      return ''
    },
    // 获取核验状态
    getVerifyStatus(status) {
      const verifyMap = {
        0: '初态',
        1: '正常',
        2: '入金激活待确认',
        3: '待出金验证',
        4: '出金待确认',
        5: '出金失败',
        6: '未出金',
        7: '验证失败',
        8: '入金激活次数超限或超时'
      }
      if (status !== null) {
        return verifyMap[status] || ''
      }
      return ''
    }
  }
}
</script>

<style>
.custom-tooltip {
  width: 300px;
  position: absolute;
  top: -10px !important;
  left: -100px;
  background-color: #f56c6c;
  color: #fff;
  padding: 10px;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  z-index: 1000; /* 确保 tooltip 在其他元素之上 */
}

.custom-tooltip .close-btn {
  background: none;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 16px;
}

.custom-tooltip .timer {
  margin-left: 10px;
  color: #fff;
}
</style>

<style lang="scss" scoped>
.main-content {
  .company-box-cont {
    padding: 20px;
    border: 2px dashed #ebebeb;
    margin: 15px 0;
    .company-box {
      width: 100%;
      padding: 20px;
      background: #f5f6f6;
      .company-title {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        margin-bottom: 10px;
        .supplier {
          color: #a3a8ac;
          font-size: 14px;
        }
        .supplier-name {
          color: #222931;
          font-size: 20px;
          font-weight: 700;
          margin-top: 10px;
        }
        .supplier-operation {
          display: flex;
          & > .svg-button {
            margin-left: 40px;
          }
        }
      }
      .normal {
        color: #222931;
        font-size: 16px;
        margin-top: 20px;
      }
    }
  }
}
</style>
