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

// 银行签约相关
export function useBankSign() {
    const { getUserDataInfo } = useUserStore()
    const { accountId } = useAccountStore()
    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: accountId.value.toString(), // 账户
        AccountName: userInfo.customername, // 客户名称
        BankAccountName: userInfo.customername,
        ExtOperatorID: 0, // 外部操作流水号
        CertType: userInfo.cardtypeid.toString(), // 证件类型
        CertID: decryptAES(userInfo.cardnum)!, // 证件号码
    })

    const formSubmit = () => {
        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 t2bBankSign({
            data: {
                ...formData,
                ExtOperatorID: new Date().getTime(),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

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

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

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

    const formSubmit = () => {
        loading.value = true
        return t2bBankCancelSign({
            data: {
                ExtOperatorID: new Date().getTime(), // 外部操作流水号
                AccountCode: getFirstAccountId().toString(), // 账户
                CusBankID: bankInfo.cusbankid, // 托管银行编号
                IsForce: 0, // 是否强制
                Currency: bankInfo.currency, // 币种
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formSubmit,
    }
}

/**
 * 账户出入金
 * @returns 
 */
export function useAccountInOut() {
    const { getUserId } = useLoginStore()
    const { dataList, selectList, buttonList, filterMethod, getQueryParam } = useDataTable<Ermcp.AccountOutInApplyRsp>()
    const columns = shallowRef(getTableColumns('mine_capital'))
    const loading = shallowRef(false)

    selectList.value = [
        {
            key: 'applystatus',
            label: '状态',
            options: [
                { label: '待审核', value: 1 },
                { label: '待复审', value: 2 }
            ],
        },
        {
            key: 'executetype',
            label: '申请类型',
            options: [
                { label: '出金', value: 1 },
                { label: '入金', value: 2 }
            ],
        },
    ]

    filterMethod.onReset = () => {
        getAccountInOutApply()
    }

    filterMethod.onSearch = () => {
        getAccountInOutApply()
    }

    const getAccountInOutApply = () => {
        const param = getQueryParam()
        loading.value = true
        return queryAccountInOutApply({
            data: {
                userid: getUserId(),
                applystatus: param.applystatus,
                querytype: param.executetype,
            },
            success: (res) => {
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        dataList,
        selectList,
        buttonList,
        columns,
        getAccountInOutApply,
    }
}

// 入金
export function useDeposit() {
    const { getUserDataInfo } = useUserStore()
    const { accountInfo } = useAccountStore()
    const userInfo = getUserDataInfo('userInfo')
    const loading = shallowRef(false)

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

    const formSubmit = async () => {
        loading.value = true
        return new Promise<void>((resolve, reject) => {
            queryBankAccountSign({
                data: {
                    userid: userInfo.userid
                },
                success: (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({
                            data: {
                                ...formData,
                                ExtOperatorID: new Date().getTime()
                            },
                            success: () => {
                                resolve()
                            },
                            fail: (err) => {
                                reject(err)
                            },
                            complete: () => {
                                loading.value = false
                            }
                        })
                    } else {
                        loading.value = false
                        reject('请先签约银行！')
                    }
                },
                fail: (err) => {
                    loading.value = false
                    reject(err)
                }
            })
        })
    }

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

// 出金
export function useWithdraw() {
    const { getUserDataInfo } = useUserStore()
    const { accountInfo } = useAccountStore()
    const userInfo = getUserDataInfo('userInfo')
    const loading = shallowRef(false)

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

    const formSubmit = async () => {
        loading.value = true
        return new Promise<void>((resolve, reject) => {
            queryBankAccountSign({
                data: {
                    userid: userInfo.userid
                },
                success: (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({
                            data: {
                                ...formData,
                                ExtOperatorID: new Date().getTime()
                            },
                            success: () => {
                                resolve()
                            },
                            fail: (err) => {
                                reject(err)
                            },
                            complete: () => {
                                loading.value = false
                            }
                        })
                    } else {
                        loading.value = false
                        reject('请先签约银行！')
                    }
                },
                fail: (err) => {
                    loading.value = false
                    reject(err)
                }
            })
        })
    }

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