import { reactive, shallowRef, computed } from 'vue'
import { useDataTable } from '@/hooks/datatable'
import { useLoginStore, useUserStore } from '@/stores'
import { queryHisAmountLog, queryAmountLog, t2bBankWithdraw, queryBankAccountSign, t2bBankDeposit, queryAccountInOutApply, queryCusBankSignBank, t2bBankSign, t2bBankCancelSign, accountFundInfoReq } from '@/services/api/bank'
import { decryptAES } from '@/utils/websocket/crypto'
import moment from "moment";


// 历史资金流水列表
export function useAmountStatementList() {
    const { getFirstAccountId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize, pageCount } = useDataTable<Model.AmountLogRsp>()
    const loading = shallowRef(false)

    const getAmountStatementList = async () => {
        loading.value = true
        await queryAmountLog({
            data: {
                page: pageIndex.value,
                pagesize: pageSize.value,
                pageflag: 1,
                accountID: getFirstAccountId().toString(),
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
        return dataList.value
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        pageCount,
        getAmountStatementList,
    }
}

// 历史出入金流水列表
export function useHisAmountStatementList() {
    const { getFirstAccountId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize, pageCount } = useDataTable<Model.HisAmountLogRsp>()
    const loading = shallowRef(false)

    const getHisAmountStatementList = async () => {
        loading.value = true
        await queryHisAmountLog({
            data: {
                page: pageIndex.value,
                pagesize: pageSize.value,
                pageflag: 1,
                accountID: getFirstAccountId().toString(),
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
        return dataList.value
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        pageCount,
        getHisAmountStatementList,
    }
}

// 获取出入金流水列表
export function useAccouuntInOutApplyListList() {

    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize, pageCount } = useDataTable<Model.AccountOutInApplyRsp>()
    const loading = shallowRef(false)

    const getAccouuntInOutApplyList = () => {
        loading.value = true
        return queryAccountInOutApply({
            data: {
                userid: getUserId()
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        pageCount,
        getAccouuntInOutApplyList
    }
}

// 查询可签约的托管银行列表
export function getCusBankSignBankList() {
    const { dataList, total, pageIndex, pageSize, pageCount } = useDataTable<Model.CusBankSignBankRsp>()
    const loading = shallowRef(false)

    const getCusBankSignBankList = () => {
        loading.value = true
        return queryCusBankSignBank({
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        pageCount,
        getCusBankSignBankList
    }
}

// 查询当前已经签约信息列表
export function useBankAccountSign() {
    const { getUserId } = useLoginStore()
    const { dataList } = useDataTable<Model.BankAccountSignRsp>()
    const loading = shallowRef(false)

    const getBankAccountList = () => {
        loading.value = true
        return queryBankAccountSign({
            data: {
                userid: getUserId()
            },
            success: (res) => {
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    const bankInfo = computed(() => {
        return dataList.value[0]
    })

    return {
        loading,
        dataList,
        bankInfo,
        getBankAccountList
    }
}

// 提现请求
export function useDoWithdraw() {

    /// 获取UserId
    const { getUserId } = useLoginStore()
    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({
        data: {
            userid: getUserId()
        },
        success: (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() {
    /// 获取UserId
    const { getUserId } = useLoginStore()
    const loading = shallowRef(false)
    /// 获取当前是否已签约
    const sign = shallowRef<Model.BankAccountSignRsp[]>([])
    /// 常量信息
    const extendInfo = { certificate_photo_url: '' }
    /// formData
    const formData = reactive<Partial<Proto.t2bBankDepositReq>>({})

    const request = queryBankAccountSign({
        data: {
            userid: getUserId()
        },
        success: (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 loading = shallowRef(false)
    const { getUserInfo } = useUserStore()
    const { getFirstAccountId } = useLoginStore()

    /// 托管银行信息
    const cusSignBank = shallowRef<Model.CusBankSignBankRsp>()
    /// 查询签约银行信息
    const request = queryCusBankSignBank({
        success: (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)
    })

    const { getBankAccountList, bankInfo } = useBankAccountSign()
    /// 判断是否有签约信息 有就做修改
    getBankAccountList().then(() => {
        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: getFirstAccountId().toString(),
        CertID: decryptAES(getUserInfo()?.cardnum ?? ''),
        CertType: getUserInfo()?.cardtypeid.toString(),
        BankAccountName: getUserInfo()?.customername,
    })

    console.log(formData)

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

        return t2bBankSign({
            data: {
                ...formData,
                OperateType: bankInfo.value ? 2 : 1,
                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() {
    const { getBankAccountList, bankInfo } = useBankAccountSign()

    /// 获取UserId
    const loading = shallowRef(false)

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

    const formRefresh = () => {
        getBankAccountList().then(() => {
            ({
                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() {
    /// 获取UserId
    const { getFirstAccountId } = useLoginStore()

    /// 数据
    const fund = shallowRef<Partial<Proto.AccountFundInfoRsp>>({})

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

    return {
        fund
    }
}
