import { shallowRef, reactive } from 'vue'
import { loginStore } from '@/stores'
import { investorDel, modifyPassword, requestAddAuth } from '@/services/api/account'
import cryptojs from 'crypto-js'

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

// 用户实名认证
export function addAuthReq() {
    const loading = shallowRef(false)

    const formData = reactive<Partial<Model.AddAuthReq>>({
        userid: userId.value,
        cardtype: 0
    })

    const formSubmit = async () => {
        try {
            loading.value = true
            const res = await requestAddAuth({
                ...formData,
                username: formData.username,
                cardtype: formData.cardtype,
                cardbackphotourl: formData.cardbackphotourl,
                cardfrontphotourl: formData.cardfrontphotourl,
                cardnum: formData.cardnum
            })
            console.log(res)
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        formData,
        formSubmit
    }
}

// 修改密码
export function useAccountPassword(ModifyPwdType: 0 | 1 | 2) {
    const loading = shallowRef(false)

    const formData = reactive<Proto.ModifyPwdReq>({
        ModifyPwdType, // 修改密码类型1：登陆密码2：资金账户密码
        ModifyPwdID: ModifyPwdType === 1 ? loginId.value : firstAccountId.value, // 被修改的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,
        formData,
        formSubmit
    }
}

// 账户注销
export function useAccountCancellation() {
    const loading = shallowRef(false)

    const formSubmit = () => {
        loading.value = true
        return investorDel({
            data: {
                UserID: userId.value
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        formSubmit,
    }
}