import { reactive, shallowRef, computed } from 'vue'
import { loginStore, userStore } from '@/stores'
import { t2bBankWithdraw, queryBankAccountSign, t2bBankDeposit, queryCusBankSignBank, t2bBankSign, t2bBankCancelSign, accountFundInfoReq } from '@/services/api/bank'
import { SignStatus } from '@/constants/bank'
import { decryptAES } from '@/utils/websocket/crypto'
import moment from "moment"

const { userId, firstAccountId } = loginStore.$mapGetters()

// 提现请求
export function useDoWithdraw() {
    const loading = shallowRef(false)
    /// 获取当前是否已签约
    const bankAccountSign = shallowRef<Model.BankAccountSignRsp[]>([])

    const sign = computed<Partial<Model.BankAccountSignRsp>>(() => {
        if (bankAccountSign.value.length) {
            return bankAccountSign.value[0]
        }
        return {}
    })

    /// 查询签约信息
    const request = queryBankAccountSign({
        userid: userId.value
    }).then((res) => {
        if (res.data.length) {
            bankAccountSign.value = res.data
            const data = res.data[0]
            formData.Currency = data.currency
            formData.CusBankID = data.cusbankid
            formData.BankAccoutName = data.bankaccountname
            formData.OpenCardBankId = data.bankid
            formData.AccountCode = data.accountcode
            formData.BranchBankName = data.branchbankname
            formData.BankAccoutName = data.bankaccountname2
            formData.BankAccoutNum = data.bankaccountno2
        }
    })

    const formData = reactive<Partial<Proto.t2bBankWithdrawReq>>({
        AccountType: 0,
        AppDateTime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        Extend_Info: JSON.stringify({ "sex": 1 })
    })

    const onSubmit = async () => {
        await request
        loading.value = true

        return t2bBankWithdraw({
            data: {
                ...formData,
                ExtOperatorID: new Date().getTime()
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        onSubmit,
        formData,
        sign
    }
}

// 充值请求
export function useDoDeposit() {
    const loading = shallowRef(false)
    /// 获取当前是否已签约
    const sign = shallowRef<Model.BankAccountSignRsp[]>([])
    /// 常量信息
    const extendInfo = { certificate_photo_url: '' }
    /// formData
    const formData = reactive<Partial<Proto.t2bBankDepositReq>>({})

    const request = queryBankAccountSign({
        userid: userId.value
    }).then((res) => {
        if (res.data.length) {
            sign.value = res.data
            const data = res.data[0]
            formData.Currency = data.currency
            formData.CusBankID = data.cusbankid
            formData.BankAccoutName = data.bankaccountname2
            formData.OpenCardBankId = data.bankid
            formData.AccountCode = data.accountcode
            formData.BankAccoutNum = data.bankaccountno2
        }
    })

    const onSubmit = async () => {
        await request
        loading.value = true
        return t2bBankDeposit({
            data: {
                ...formData,
                ExtOperatorID: new Date().getTime(),
                Extend_Info: JSON.stringify(extendInfo)
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        onSubmit,
        extendInfo,
        formData,
        sign
    }
}

/// 银行签约请求
export function useDoBankSign() {
    const { userInfo } = userStore.$mapGetters()
    const loading = shallowRef(false)
    const bankInfo = shallowRef<Model.BankAccountSignRsp>()

    /// 托管银行信息
    const cusSignBank = shallowRef<Model.CusBankSignBankRsp>()
    /// 查询签约银行信息
    const request = queryCusBankSignBank().then((res) => {
        if (res.data.length) {
            const data = res.data[0]
            cusSignBank.value = data
            formData.Currency = data.currency
            formData.CusBankID = data.cusbankid
            formData.TradeDate = data.tradedate
        }
    })

    /// 银行列表
    const banklist = computed(() => {
        return (cusSignBank.value?.Banklst ?? []).filter(e => e.status == 0)
    })

    /// 判断是否有签约信息 有就做修改
    queryBankAccountSign().then((res) => {
        bankInfo.value = res.data[0]
        if (bankInfo.value) {
            ({
                currency: formData.Currency,
                cusbankid: formData.CusBankID,
                accountcode: formData.AccountCode,
                accountname: formData.BankAccountName,
                branchbankname: formData.OpenBankName,
                bankaccountno: formData.BankAccountNo,
                bankid: formData.OpenBankAccId,
            } = bankInfo.value)
        }
    })

    /// 数据
    const formData = reactive<Partial<Proto.t2bBankSignReq>>({
        AccountType: 1,
        IsForce: 0,
        AgentCertType: 0,
        BankCardType: 0,
        BankAccountType: 1,
        Extend_Info: JSON.stringify({ "sex": 1 }),
        AccountCode: firstAccountId.value.toString(),
        CertID: decryptAES(userInfo.value?.cardnum ?? ''),
        CertType: userInfo.value?.cardtypeid.toString(),
        BankAccountName: userInfo.value?.customername,
    })

    const onSubmit = async () => {
        await request
        loading.value = true
        // 默认未签约状态
        const { signstatus = SignStatus.Unsigned } = bankInfo.value ?? {}

        return t2bBankSign({
            data: {
                ...formData,
                OperateType: signstatus === SignStatus.Unsigned ? 1 : 2,
                ExtOperatorID: new Date().getTime(),
                AccountName: formData.BankAccountName,
                ExBankName: banklist.value.find(obj => obj.bankid === formData.OpenBankAccId)?.bankname
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formData,
        banklist,
        onSubmit,
        bankInfo
    }
}

/// 银行解约请求
export function useDoCancelBankSign() {
    /// 获取UserId
    const loading = shallowRef(false)
    const bankInfo = shallowRef<Model.BankAccountSignRsp>()

    /// 表单信息
    const formData = reactive<Partial<Proto.t2bBankCancelSignReq>>({
        IsForce: 0,
    })
    /// 获取当前是否已签约
    const sign = shallowRef<Model.BankAccountSignRsp[]>([])

    const formRefresh = () => {
        queryBankAccountSign().then((res) => {
            bankInfo.value = res.data[0];
            ({
                currency: formData.Currency,
                cusbankid: formData.CusBankID,
                accountcode: formData.AccountCode,
            } = bankInfo.value ?? {})
        })
    }

    const cancelSubmit = async () => {
        // await request
        loading.value = true
        /// 发起请求
        return t2bBankCancelSign({
            data: {
                ...formData,
                ExtOperatorID: new Date().getTime(),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        cancelSubmit,
        formData,
        sign,
        bankInfo,
        formRefresh
    }
}

/// 账户资金信息请求
export function useAccountFundInfo() {
    /// 数据
    const fund = shallowRef<Partial<Proto.AccountFundInfoRsp>>({})

    /// 账户资金信息
    accountFundInfoReq({
        data: {
            QueryBitMask: 2,
            OrderId: new Date().getTime(),
            AccountId: firstAccountId.value,
        },
        success: (res) => {
            fund.value = res
        },
    })

    return {
        fund
    }
}
