import { shallowRef, reactive } from 'vue'
import { useDataTable } from '@/hooks/datatable'
import { queryWrUserReceiptInfo, userReceiptInfo, delUserReceiptInfo } from '@/services/api/user'
import { useLoginStore } from '@/stores'
import { getCertificateTypeList } from '@/constants/certificate'

export function useInvoice() {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize } = useDataTable<Model.WrUserReceiptInfoRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef([])

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

    return {
        loading,
        dataList,
        columns,
        total,
        pageIndex,
        pageSize,
        getUserInvoiceList,
    }
}

export function useInvoiceForm(selectedRow?: Model.WrUserReceiptInfoRsp) {
    const { getUserId } = useLoginStore()
    const loading = shallowRef(false)
    const certificateTypeList = getCertificateTypeList()

    const formData = reactive<Proto.UserReceiptInfoReq>({
        UserID: getUserId(), // 用户ID
        UserName: '', // 发票抬头姓名
        ReceiptType: 1, // 发票类型
        TaxpayerID: '', // 纳税人识别号
        ContactInfo: '', // 联系方式
        ReceiptInfoId: 0, // 修改时填用户发票信息id
        ReceiptBank: '', // 发票开户行[发票类型:企业]
        ReceiptAccount: '', // 发票帐号[发票类型:企业]
        Address: '', // 地址[发票类型:企业]
    })

    if (selectedRow?.autoid) {
        ({
            autoid: formData.ReceiptInfoId,
            userid: formData.UserID,
            username: formData.UserName,
            receipttype: formData.ReceiptType,
            taxpayerid: formData.TaxpayerID,
            contactinfo: formData.ContactInfo,
            receiptbank: formData.ReceiptBank,
            receiptaccount: formData.ReceiptAccount,
            address: formData.Address,
            idnum: formData.IDNum,
            email: formData.Email,
        } = selectedRow)
    }

    const addOrUpdate = () => {
        loading.value = true
        return userReceiptInfo({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    const deleteInvoice = () => {
        loading.value = true
        return delUserReceiptInfo({
            data: {
                ReceiptInfoId: formData.ReceiptInfoId
            },
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        certificateTypeList,
        formData,
        addOrUpdate,
        deleteInvoice,
    }
}