import { shallowRef, reactive } from 'vue'
import { decryptAES } from '@/utils/websocket/crypto'
import { useDataTable } from '@/hooks/datatable'
import { useAccountStore, useLoginStore, useUserStore } from '@/stores'
import { queryCusBankSignBank, queryAccountInOutApply, t2bBankSign, t2bBankCancelSign, queryBankAccountSign, t2bBankDeposit, t2bBankWithdraw } from '@/services/api/bank'
import { SignStatus } from '@/constants/bank'

const accountStore = useAccountStore()
const loginStore = useLoginStore()
const { getUserDataInfo } = useUserStore()

// 银行签约相关
export function useBankSign() {
    const userInfo = getUserDataInfo('userInfo')
    const loading = shallowRef(false)
    const custodianBanks = shallowRef<Ermcp.CusBankSignBankRsp[]>([]) // 托管银行列表
    const selectedCustodianBank = shallowRef<Ermcp.CusBankSignBankRsp>() // 已选中的托管银行
    const selectedDepositBank = shallowRef<Ermcp.BankInfoRsp>() // 已选中的开户银行

    const extendInfo = {
        sex: userInfo.sex,
    }

    const formData = reactive<Partial<Proto.t2bBankSignReq>>({
        OperateType: 1, // 变更类型[1-增加; 2-修改; 4-绑卡;
        IsForce: 0, // 是否强制[0-否; 1-是]强制
        AgentCertType: 0, // 授权代理人证件类型
        BankCardType: 0, // 银行卡类型
        BankAccountType: 1, // 银行账户类型
        AccountType: 1, // // 账户类型[1-对私; 2-对公]
        extend_info: JSON.stringify(extendInfo), //  扩展信息（JSON串，参考配置要求进行填充）
        AccountCode: accountStore.accountId.toString(), // 账户
        AccountName: userInfo.customername, // 客户名称
        BankAccountName: userInfo.customername,
        ExtOperatorID: 0, // 外部操作流水号
        CertType: userInfo.cardtypeid.toString(), // 证件类型
        CertID: decryptAES(userInfo.cardnum)!, // 证件号码
    })

    const formSubmit = async () => {
        try {
            loading.value = true
            // 已选的托管银行
            if (selectedCustodianBank.value) {
                ({
                    cusbankid: formData.CusBankID,
                    currency: formData.Currency,
                    tradedate: formData.TradeDate,
                } = selectedCustodianBank.value)
            }
            // 已选中的开户银行
            if (selectedDepositBank.value) {
                ({
                    bankid: formData.OpenBankAccId,
                    bankname: formData.ExBankName,
                } = selectedDepositBank.value)
            }

            return await t2bBankSign({
                ...formData,
                ExtOperatorID: new Date().getTime(),
            })
        } finally {
            loading.value = false
        }
    }

    // 获取托管银行
    queryCusBankSignBank().then((res) => {
        custodianBanks.value = res.data
    })

    return {
        loading,
        custodianBanks,
        selectedCustodianBank,
        selectedDepositBank,
        formData,
        formSubmit,
    }
}

// 银行解约相关
export function useBankCancelSign(bankInfo: Ermcp.BankAccountSignRsp) {
    const loading = shallowRef(false)

    const formSubmit = async () => {
        try {
            loading.value = true
            return await t2bBankCancelSign({
                ExtOperatorID: new Date().getTime(),
                AccountCode: loginStore.firstAccountId.toString(),
                CusBankID: bankInfo.cusbankid,
                IsForce: 0,
                Currency: bankInfo.currency, // 币种
            })
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formSubmit,
    }
}

/**
 * 账户出入金
 * @returns 
 */
export function useAccountInOut() {
    const { dataList } = useDataTable<Ermcp.AccountOutInApplyRsp>()
    const loading = shallowRef(false)

    const getAccountInOutApply = async (params: Partial<Ermcp.AccountInOutApplyReq> = {}) => {
        try {
            loading.value = true
            const res = await queryAccountInOutApply({
                userid: loginStore.userId,
                applystatus: params.applystatus,
                querytype: params.querytype,
            })
            dataList.value = res.data
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        dataList,
        getAccountInOutApply,
    }
}

// 入金
export function useDeposit() {
    const { accountInfo } = accountStore.$toRefs()
    const userInfo = getUserDataInfo('userInfo')
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.t2bBankDepositReq>>({
        CusBankID: '', // 托管银行编号
        AccountCode: '', // 资金账户
        Currency: '', // 币种
        BankAccoutName: '',
        BankAccoutNum: '',
    })

    const formSubmit = () => {
        loading.value = true
        return new Promise<void>((resolve, reject) => {
            queryBankAccountSign({
                userid: userInfo.userid
            }).then((res) => {
                const bankInfo = res.data[0]
                if (bankInfo?.signstatus === SignStatus.Signed) {
                    ({
                        cusbankid: formData.CusBankID,
                        accountcode: formData.AccountCode,
                        currency: formData.Currency,
                        bankaccountname2: formData.BankAccoutName,
                        bankaccountno2: formData.BankAccoutNum,
                    } = bankInfo)

                    t2bBankDeposit({
                        ...formData,
                        ExtOperatorID: new Date().getTime()
                    }).then(() => {
                        resolve()
                    }).catch((err) => {
                        reject(err)
                    }).finally(() => {
                        loading.value = false
                    })
                } else {
                    loading.value = false
                    reject('请先签约银行！')
                }
            }).catch((err) => {
                loading.value = false
                reject(err)
            })
        })
    }

    return {
        loading,
        userInfo,
        accountInfo,
        formData,
        formSubmit,
    }
}

// 出金
export function useWithdraw() {
    const { accountInfo } = accountStore.$toRefs()
    const userInfo = getUserDataInfo('userInfo')
    const loading = shallowRef(false)

    const formData = reactive<Partial<Proto.t2bBankDepositReq>>({
        CusBankID: '', // 托管银行编号
        AccountCode: '', // 资金账户
        Currency: '', // 币种
        BankAccoutName: '',
        BankAccoutNum: '',
    })

    const formSubmit = () => {
        loading.value = true
        return new Promise<void>((resolve, reject) => {
            queryBankAccountSign({
                userid: userInfo.userid
            }).then((res) => {
                const bankInfo = res.data[0]
                if (bankInfo?.signstatus === SignStatus.Signed) {
                    ({
                        cusbankid: formData.CusBankID,
                        accountcode: formData.AccountCode,
                        currency: formData.Currency,
                        bankaccountname2: formData.BankAccoutName,
                        bankaccountno2: formData.BankAccoutNum,
                    } = bankInfo)

                    t2bBankWithdraw({
                        ...formData,
                        ExtOperatorID: new Date().getTime()
                    }).then(() => {
                        resolve()
                    }).catch((err) => {
                        reject(err)
                    }).finally(() => {
                        loading.value = false
                    })
                } else {
                    loading.value = false
                    reject('请先签约银行！')
                }
            }).catch((err) => {
                loading.value = false
                reject(err)
            })
        })
    }

    return {
        loading,
        userInfo,
        accountInfo,
        formData,
        formSubmit,
    }
}