<!-- 签约账号管理 -->
<template>
    <app-table :data="dataList" v-model:columns="tableColumns" :loading="loading" :row-key="rowKey"
        :expand-row-keys="expandKeys" @row-click="rowClick">
        <template #headerLeft>
            <template v-if="((hasAQAuth && hasSignContract) || !hasAQAuth) && [AuthStatus.Certified, AuthStatus.Submitted].includes(authStatus) && ![SignStatus.Audit, SignStatus.Signing, SignStatus.Signed].includes(signStatus)">
                <el-button type="primary" size="small"
                    @click="showComponent('sign')">{{ t('banksign.addbanksign') }}</el-button>
            </template>
            <template v-if="[AuthStatus.Certified, AuthStatus.Submitted].includes(authStatus) && (hasAQAuth && !hasSignContract) ">
                <el-button type="primary" size="small" @click="showComponent('protocol')">{{ t('banksign.signagreement') }}</el-button>
            </template>
            <el-button type="warning" size="small" v-if="authStatus === AuthStatus.Uncertified"
                @click="openComponent('certification-aq')">{{ t('user.authentication.title') }}</el-button>
        </template>
        <!-- 证件类型 -->
        <template #cardtype="{ value }">
            {{ getCertificateTypeCodeName(Number(value)) }}
        </template>
        <!-- 状态 -->
        <template #signstatus="{ value }">
            {{ getSignStatusName(value) }}
        </template>
        <!-- 状态 -->
        <template #updatetime="{ value }">
            {{ formatDate(value) }}
        </template>
        <!-- 展开行 -->
        <template #expand="{ row }">
            <div class="buttonbar">
                <el-button v-if="row.signstatus === SignStatus.Signed && cusBank?.canrelease === 1" type="danger"
                    size="small" @click="openComponent('cancel')">{{ t('banksign.cancel') }}</el-button>
                <el-button
                    v-if="[SignStatus.Unsigned, SignStatus.Refuse, SignStatus.Rescinded].includes(row.signstatus) || (row.signstatus === SignStatus.Signed && cusBank?.canmodifysigninfo === 1)"
                    type="primary" size="small" @click="showComponent('sign')">{{ t('operation.modify') }}</el-button>
            </div>
        </template>
    </app-table>
    <component ref="componentRef" v-bind="{ selectedRow }" :is="componentMap.get(componentId)" @closed="closeComponent"
        v-if="componentId" />
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent, onMounted, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useComponent } from '@/hooks/component'
import { useComposeTable } from '@pc/components/base/table'
import { useRequest } from '@/hooks/request'
import { queryBankAccountSign, queryCusBankSignBank } from '@/services/api/bank'
import { getSignStatusName, SignStatus } from '@/constants/bank'
import { getCertificateTypeCodeName } from '@/constants/account'
import { queryUserAccount, queryUsereSignRecords } from '@/services/api/account'
import { AuthStatus } from '@/constants/account'
import { useUserStore, i18n } from '@/stores'
import { ElMessage } from 'element-plus'
import { queryMdUserSwapProtocol } from '@/services/api/swap'
import { getUserId, getMemberUserId } from '@/services/methods/user'
import AppTable from '@pc/components/base/table/index.vue'
import service from '@/services'
import { formatDate } from '@/filters'

const componentMap = new Map<string, unknown>([
    ['cancel', defineAsyncComponent(() => import('./components/cancel/index.vue'))],
    ['sign', defineAsyncComponent(() => import('./components/sign/index.vue'))],
    ['certification', defineAsyncComponent(() => import('./components/certification/index.vue'))], // 实名认证,
    ['certification-aq', defineAsyncComponent(() => import('./components/certification-aq/index.vue'))], // 实名认证
    ['protocol', defineAsyncComponent(() => import('./components/protocol/index.vue'))], // 合同签署
])

const useStore = useUserStore()
const authStatus = shallowRef(AuthStatus.Certified) // 实名认证状态
const signStatus = shallowRef(SignStatus.Unsigned)
const cusBank = shallowRef<Model.CusBankSignBankRsp>()
const oem = service.getConfig('oem')
const { t } = i18n.global
const dataList = shallowRef<Model.BankAccountSignRsp[]>()

const { rowKey, expandKeys, rowClick, selectedRow } = useComposeTable<Model.BankAccountSignRsp>({ rowKey: 'applyexchticket' })
// 需求 #5692: 交易系统通用问题2024
const { loading, run } = useRequest(queryBankAccountSign, {
    onSuccess: (res) => {
        /// 签约状态
        if (res.data.length != 0) {
            dataList.value = res.data.sort((a, b) => {
                return b.updatetime.localeCompare(a.updatetime)
            }).slice(0, 1)
            signStatus.value = dataList.value[0].signstatus
        }
    }
})

/// 查询用户掉期协议签署表
const { dataList: protocolList } = useRequest(queryMdUserSwapProtocol, {
    defaultParams: {
        userId: getUserId()
    }
})

/// 查询爱签签约协议信息
const { dataList: records} = useRequest(queryUsereSignRecords, {
    defaultParams: {
        userId: getUserId(),
        memberUserId: getMemberUserId(),
    }
})

/// 判断是否能签约
const hasSignContract = computed(() => {
    if ( oem.toLowerCase() === 'tjmd' ) {
        return protocolList.value.some(e => { return e.protocolstatus === 4 })
    } else if ( oem.toLowerCase() === 'zrwyt' ) {
        return records.value.some(e => { return e.recordstatus === 3 && e.templatetype === 2 })
    } else if (oem.toLowerCase() === 'gcszt' ) {
        return !records.value.some(e => { return e.recordstatus != 3 })
    }
    return true
})

/// 是否爱签实名认证
const hasAQAuth = computed(() => {
    if ( oem.toLowerCase() === 'tjmd' ) {
        return true
    } else if ( oem.toLowerCase() === 'zrwyt' ) {
        return records.value.some(e => { return e.recordstatus === 3 && e.templatetype === 1 })
    } else if ( oem.toLowerCase() === 'gcszt' ) {
        return true
    }
    return true
})

/// 查询托管银行信息
useRequest(queryCusBankSignBank, {
    onSuccess: (res) => {
        /// 签约状态
        if (res.data.length != 0) {
            cusBank.value = res.data[0]
        }
    }
})

const { componentRef, componentId, openComponent, closeComponent } = useComponent(() => {
    run()
})

const showComponent = ((componentName: string) => {
    /// 认证请求中 不能操作
    if (authStatus.value === AuthStatus.Submitted) {
        ElMessage.error(t('banksign.tips8'))
        return
    }
    openComponent(componentName)
})

const tableColumns = shallowRef<Model.TableColumn[]>([
    { field: 'accountcode', label: 'banksign.wallet.inoutapply.accountcode' },
    { field: 'accountname', label: 'banksign.accountname' },
    { field: 'cardtype', label: 'banksign.cardtype' },
    { field: 'cardno', label: 'banksign.cardno' },
    { field: 'cusbankname', label: 'banksign.cusbankname' },
    { field: 'bankname', label: 'banksign.bankname' },
    { field: 'bankaccountno', label: 'banksign.bankaccountno1' },
    { field: 'currency', label: 'banksign.currency' },
    { field: 'signstatus', label: 'banksign.signstatus' },
    { field: 'remark', label: 'banksign.remark' },
    { field: 'updatetime', label: 'banksign.remark' },
])

onMounted(() => {
    useStore.getUserData()
    // 获取用户账号信息----------------待处理，直接用useStore
    queryUserAccount().then((res) => {
        authStatus.value = res.data.hasauth
    })
})

</script>