<template>
  <div class="member-main-content">
    <div class="search">
      <div />
      <div class="right">
        <div>
          <el-input
            v-model="search.fastSearch"
            placeholder="请输入客户号/长银账号/长银账户名称/客户名称"
            style="width: 320px;"
          />
        </div>
        <div>
          <el-select v-model="search.accountStatus" placeholder="请选择账户状态" clearable>
            <el-option
              v-for="item in constant.memberAccountStatus"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </div>
        <!-- <div>
          <el-input v-model="search.channel" placeholder="请输入渠道类型" clearable></el-input>
        </div> -->
        <div>
          <el-button type="primary" @click="fetchData('all')">查询</el-button>
          <!-- <el-button v-power="'addBocomVip'" type="primary" @click="handleAddAccount">新建会员账户</el-button> -->
        </div>
      </div>
    </div>
    <cy-comm-table
      ref="commTable"
      v-loading="loading"
      :columns="columns"
      :data="tableData"
      :count="total"
      :table-options="getTableOptions"
    />
    <cy-dialog ref="timeAxisDialog" title="进度时间轴" top="15vh">
      <cy-time-axis ref="timeAxis" :time-axis-params="timeAxisParams"></cy-time-axis>
    </cy-dialog>
    <cy-dialog ref="activationDialog" title="重设入金激活金额" top="25vh" width="700px">
      <activation-content :active-number="curActiveNumber" @close="transactionDialogClick" />
    </cy-dialog>
    <authorization ref="authorizationRef" :active-info="authActiveInfo" />
  </div>
</template>

<script>
import { formatMoney } from '@/utils'
import { mapGetters } from 'vuex'
import {
  queryMemberList,
  updateMemberRegister,
  refreshMemberStatus,
  resetActivateAmount
} from '@/api/cyAccountManage/memberAccountManage/index'

export default {
  components: {
    Authorization: () => import('./components/Authorization.vue'),
    ActivationContent: () => import ('./components/ActivationContent.vue')
  },
  data() {
    return {
      activeName: 'pending',
      loading: false,
      total: 0,
      page: 1,
      size: 10,
      search: {
        fastSearch: '',
        accountStatus: ''
        // channel: ''
      },
      tableData: [],
      timeAxisParams: {
        businessKey: '',
        businessType: 'SupplierInfo'
      },
      columns: [
        {
          label: '序号',
          index: true
        },
        {
          label: '客户号',
          prop: 'customerNumber',
          showTooltip: true,
          width: 120
        },
        {
          label: '账号',
          prop: 'accountNumber',
          showTooltip: true,
          width: 120
        },
        {
          label: '账户名称',
          prop: 'accountName',
          showTooltip: true,
          width: 120
        },
        {
          label: '客户名称',
          prop: 'customerName',
          showTooltip: true,
          width: 120
        },
        {
          label: '账户状态',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ row.accountStatus === 1 ? '生效' : '失效' }</div>
            )
          }
        },
        {
          label: '授权状态',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getAuthorizationDesc(row.authorizationStatus) }</div>
            )
          }
        },
        {
          label: '绑定银行账号',
          showTooltip: true,
          width: 150,
          render: (h, row) => {
            return (
              <div>{ (row.bindAccountInfoList && row.bindAccountInfoList.length > 0) ? row.bindAccountInfoList[0].bindAcctNo : '' }</div>
            )
          }
        },
        {
          label: '绑定状态',
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ (row.bindAccountInfoList && row.bindAccountInfoList.length > 0) ? this.getBindStatus(row.bindAccountInfoList[0].bindAccSts) : '' }</div>
            )
          }
        },
        {
          label: '绑定审批状态',
          showTooltip: true,
          width: 120,
          render: (h, row) => {
            return (
              <div>{ (row.bindAccountInfoList && row.bindAccountInfoList.length > 0) ? this.getBindApprovalStatus(row.bindAccountInfoList[0].managerApproverSts) : '' }</div>
            )
          }
        },
        {
          label: '核验状态',
          showTooltip: true,
          width: 120,
          render: (h, row) => {
            return (
              <div>{ (row.bindAccountInfoList && row.bindAccountInfoList.length > 0) ? this.getVerifyStatus(row.bindAccountInfoList[0].bindSts) : '' }</div>
            )
          }
        },
        {
          label: '账户余额',
          showTooltip: true,
          width: 120,
          render: (h, row) => {
            return (
              <div>{ formatMoney(row.accountBalance) }</div>
            )
          }
        },
        {
          label: '可用余额',
          showTooltip: true,
          width: 120,
          render: (h, row) => {
            return (
              <div>{ formatMoney(row.availableBalance) }</div>
            )
          }
        },
        {
          label: '币种',
          prop: 'currency',
          showTooltip: true
        },
        {
          label: '通知推送对象',
          width: 120,
          showTooltip: true,
          render: (h, row) => {
            return (
              <div>{ this.getNoticeObjName(row.noticeObject) }</div>
            )
          }
        },
        {
          label: '创建日期',
          prop: 'gmtCreate',
          showTooltip: true
        },
        {
          label: '开通日期',
          prop: 'openTime',
          showTooltip: true
        },
        {
          label: '操作',
          render: (h, row) => {
            const btnList = [
              // {
              //   msg: '时间进度轴',
              //   icon: 'iconfont icon-timeAxis',
              //   power: '',
              //   tabPower: ['all', 'pending'],
              //   category: 'timeAxis'
              // },
              {
                msg: '查看',
                icon: 'iconfont icon-Magnifier',
                power: 'viewBocomVip',
                tabPower: ['all', 'pending'],
                // rowPower: [],
                category: 'see'
              },
              // {
              //   msg: '修改',
              //   icon: 'iconfont icon-xiugai',
              //   power: 'updateBocomVip',
              //   tabPower: ['pending'],
              //   category: 'edit'
              // },
              {
                msg: '删除',
                icon: 'iconfont icon-shanchu',
                power: 'deleteBocomVip',
                tabPower: ['pending'],
                category: 'delete'
              },
              {
                msg: '绑定实体卡信息',
                icon: 'iconfont icon-a-Union4',
                power: 'bindAccount',
                tabPower: ['pending'],
                category: 'bindCard'
              },
              {
                msg: '静默户信息',
                icon: 'iconfont icon-a-Union3',
                power: 'silentAccount',
                tabPower: ['pending'],
                category: 'defaultAccount'
              },
              {
                msg: '查看授权码',
                icon: 'iconfont icon-Magnifier',
                power: 'viewAuthCode',
                tabPower: ['all', 'pending'],
                rowPower: [0, 1, 2, 3],
                category: 'seeAuth'
              },
              // {
              //   msg: '交易记录',
              //   icon: 'iconfont icon-jiaoyijilu',
              //   power: 'transactionRecords',
              //   tabPower: ['pending'],
              //   category: 'transaction',
              //   style: 'font-size: 20px'
              // },
              {
                msg: '重设入金激活金额',
                icon: 'iconfont icon-jihuo',
                power: 'resetActvtAmt',
                tabPower: ['pending'],
                category: 'activation',
                style: 'font-size: 20px'
              },
              {
                msg: '重新查询会员信息',
                icon: 'iconfont icon-shuaxin',
                power: 'refreshBocomVipAccount',
                tabPower: ['pending'],
                category: 'refresh',
                style: 'font-size: 20px'
              }
              // {
              //   msg: '刷新登记薄',
              //   icon: 'iconfont icon-shuaxin',
              //   power: '',
              //   tabPower: ['pending'],
              //   category: 'refresh',
              //   style: 'font-size: 20px'
              // }
            ]
            const options = btnList.map(item => {
              return (
                this.tablePower({ item, tab: this.activeName, row }) && <el-tooltip class='item' effect='dark' content={item.msg} placement='top'>
                  <span class='table-icon-box' style='margin-right: 8px;' v-power={item.power}>
                    <i class={item.icon} style={item.style} onClick={() => { this.handlerOperate(item.category, row) }}></i>
                  </span>
                </el-tooltip>
              )
            })
            return <div>{ options }</div>
          },
          width: 260
        }
      ],
      curActiveNumber: '', // 入金激活弹窗查询的登记薄账号
      authActiveInfo: {} // 查看授权码组件入参集合
    }
  },
  computed: {
    ...mapGetters(['constant']),
    tablePower() {
      return ({ item, tab, row }) => {
        const { tabPower, rowPower } = item
        if (rowPower) {
          if (tabPower.includes(tab) && rowPower.includes(row.statusName)) {
            return true
          }

          if (row.authorizationStatus !== null &&
            rowPower.includes(row.authorizationStatus)) {
            return true
          } else {
            return false
          }
        } else {
          if (tabPower.includes(tab)) {
            return true
          }
        }
      }
    },
    getTableOptions() {
      if (this.activeName === 'all') {
        return {
          sortTable: true,
          maxHeight: 'calc(100vh - 406px)',
          height: 'calc(100vh - 406px)'
        }
      }
      if (this.total > 0) {
        return {
          sortTable: true,
          maxHeight: 'calc(100vh - 360px)',
          height: 'calc(100vh - 360px)'
        }
      }
      return {
        sortTable: true,
        maxHeight: 'calc(100vh - 306px)',
        height: 'calc(100vh - 306px)'
      }
    }
  },
  mounted() {
    this.fetchData('all')
  },
  methods: {
    async fetchData(tab) {
      this.loading = true
      if (tab === 'all') {
        this.page = 1
        this.size = 10
      }

      const res = await queryMemberList({
        ...this.search,
        page: this.page,
        rows: this.size,
        listType: 0
      })

      console.log('fetchData ---', res)
      this.loading = false

      this.tableData = res.rows
      this.total = res.records
    },
    handleTabClick(tab) {
      this.activeName = tab.name
      this.page = 1
      this.size = 10
      this.fetchData(tab.name)
    },
    handlerOperate(type, row) {
      if (type === 'timeAxis') {
        this.timeAxisClick(row)
        return
      } else if (type === 'bindCard') {
        this.$router.push({
          name: 'MemberUpdateBindAccount',
          query: {
            id: row.id,
            type: 'bindCard'
          }
        })
      } else if (type === 'defaultAccount') {
        this.$router.push({
          name: 'MemberUpdateDefaultAccount',
          query: {
            id: row.id,
            type: 'defaultAccount'
          }
        })
      } else if (type === 'delete') {
        this.deleteClick(row)
      } else if (type === 'requery') {
        this.requeryClick(row)
      } else if (type === 'transaction') {
        this.$router.push({
          name: 'MemberAccountTransaction',
          params: {
            id: row.id || new Date().getTime()
          }
        })
      } else if (type === 'see') {
        this.$router.push({
          name: 'MemberAccountDetail',
          query: {
            id: row.id,
            type: 'see'
          }
        })
      } else if (type === 'activation') {
        // this.curActiveNumber = row.accountNumber
        // this.transactionDialogClick(true)
        this.resetAmount(row.bindAccountInfoList[0].id)
      } else if (type === 'edit') {
        this.$router.push({
          name: 'MemberAccountEdit',
          query: {
            id: row.id,
            type: 'edit'
          }
        })
      } else if (type === 'refresh') {
        this.refreshAccountRow(row.id)
      } else if (type === 'seeAuth') {
        // 去授权
        this.$refs.authorizationRef.openDialog(true)
        console.log(row)
        this.authActiveInfo = {
          name: row.authenticator,
          qrcodeUrl: row.qrCode,
          effectTime: row.qrCodeEffectTime
        }
      }
    },
    // 重新查询
    requeryClick(row) {
      this.$confirm('确认重新查询会员信息么？', '重新查询会员信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

      }).catch(() => {})
    },
    // 删除
    deleteClick(row) {
      this.$confirm('确认删除该条数据么？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteAccount(row.id)
      }).catch(() => {})
    },
    // 时间轴
    timeAxisClick(row) {
      this.timeAxisParams.businessKey = row.id
      this.$refs.timeAxisDialog.show = true
      this.$nextTick(() => {
        this.$refs.timeAxis.fetchData()
      })
    },
    // 新建会员账户
    handleAddAccount() {
      this.$router.push({
        name: 'MemberAccountAdd',
        query: {
          type: 'add'
        }
      })
    },
    // 删除登记薄
    async deleteAccount(delId) {
      const res = await updateMemberRegister({ id: delId, deleteFlag: 1, Loading: true })

      if (res.success) {
        this.$message.success('登记薄删除成功')
        this.$router.go(0)
      }
    },
    // 刷新登记薄
    async refreshAccountRow(refreshId) {
      this.$confirm('确认重新查询会员信息么？', '重新查询会员信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await refreshMemberStatus({ id: refreshId })
        if (res.success) {
          this.$message.success('登记薄刷新成功')
          this.$router.go(0)
        }
      }).catch(() => {})
    },
    // 激活金额
    transactionDialogClick(status) {
      this.$refs.activationDialog.show = status
    },
    async resetAmount(resetId) {
      const res = await resetActivateAmount({ id: resetId })

      if (res.success) {
        this.$message.success('重设入金激活成功')
        this.$router.go(0)
      }
    },
    // 获取授权状态描述
    getAuthorizationDesc(status) {
      const descMap = {
        0: '待用户授权',
        1: '银行审核中',
        2: '授权失败（用户拒绝）',
        3: '授权失败（银行拒绝）',
        4: '授权成功'
      }
      if (status !== null) {
        return descMap[status] || ''
      }
      return ''
    },
    // 获取绑定状态
    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 ''
    },
    // 获取通知推送对象
    getNoticeObjName(status) {
      const noticeMap = {
        1: '法人',
        2: '授权代理人',
        3: '个人'
      }
      if (status !== null) {
        return noticeMap[status] || ''
      }
      return ''
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
