import { shallowRef, reactive } from 'vue'
import { useUserStore, useAccountStore, useLoginStore } from '@/stores'
import { modifyPassword } from '@/services/api/account'
import { queryBankAccountSign } from '@/services/api/bank'
import cryptojs from 'crypto-js'

export function useAccount() {
    const { getUserDataInfo } = useUserStore()
    const { accountInfo } = useAccountStore()
    const loginInfo = getUserDataInfo('loginAccount')
    const userInfo = getUserDataInfo('userInfo')
    const bankInfo = shallowRef<Ermcp.BankAccountSignRsp>()
    const loading = shallowRef(false)

    // 获取签约信息
    const getBankAccountSign = () => {
        loading.value = true
        queryBankAccountSign({
            data: {
                userid: userInfo.userid
            },
            success: (res) => {
                if (res.data.length) {
                    bankInfo.value = res.data[0]
                }
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        loginInfo,
        userInfo,
        accountInfo,
        bankInfo,
        getBankAccountSign,
    }
}

// 修改密码
export function usePassword(ModifyPwdType: 0 | 1 | 2) {
    const { loginInfo } = useLoginStore()
    const { LoginCode, LoginID, AccountIDs } = loginInfo.value
    const loading = shallowRef(false)
    const checkPassword = shallowRef('')

    const formData = reactive<Proto.ModifyPwdReq>({
        ModifyPwdType, // 修改密码类型1：登陆密码2：资金账户密码
        ModifyPwdID: ModifyPwdType === 1 ? LoginID : AccountIDs[0], // 被修改的ID(ModifyType=1:LoginIDModifyType=2:AccountID)
        OldPwd: '', // 旧资金密码
        NewPwd: '' // 新资金密码
    })

    const formSubmit = () => {
        const { ModifyPwdType, ModifyPwdID, OldPwd, NewPwd } = formData
        loading.value = true

        return modifyPassword({
            data: {
                ModifyPwdType,
                ModifyPwdID,
                OldPwd: cryptojs.SHA256(ModifyPwdID + OldPwd).toString(),
                NewPwd: cryptojs.SHA256(ModifyPwdID + NewPwd).toString(),
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        LoginCode,
        checkPassword,
        formData,
        formSubmit
    }
}