import { shallowRef, reactive } from 'vue'
import { useDataTable } from '@/hooks/datatable'
import { queryWarehouseInfo, warehouseApply } from '@/services/api/warehouse'
import { useLoginStore, useUserStore } from '@/stores'

const loginStore = useLoginStore()
const { userId } = loginStore.$toRefs()

export function useWarehouse() {
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.WarehouseInfoRsp>()
    const loading = shallowRef(false)

    const getWarehouseList = async () => {
        try {
            loading.value = true
            const res = await queryWarehouseInfo({
                page: pageIndex.value,
                pagesize: pageSize.value,
                userid: userId.value,
            })
            total.value = res.total
            dataList.value = res.data
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        dataList,
        total,
        pageIndex,
        pageSize,
        getWarehouseList,
    }
}

export function useWarehouseForm(selectedRow?: Ermcp.WarehouseInfoRsp) {
    const userStore = useUserStore()
    const loading = shallowRef(false)
    const formData = reactive<Proto.WarehouseApplyReq>({
        type: selectedRow?.warehousecode ? 2 : 1,
        userid: userId.value,
        warehousetype: 2,
        warehousecode: '',
        warehousename: '',
        contactname: '',
        contactnum: '',
    })

    if (selectedRow?.warehousecode) {
        ({
            autoid: formData.warehouseid,
            warehousecode: formData.warehousecode,
            warehousename: formData.warehousename,
            provinceid: formData.provinceid,
            cityid: formData.cityid,
            districtid: formData.districtid,
            address: formData.address,
            contactname: formData.contactname,
            contactnum: formData.contactnum,
        } = selectedRow)
    }

    const addOrUpdate = async () => {
        try {
            loading.value = true
            return await warehouseApply(formData)
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        accountName: userStore.accountName,
        formData,
        addOrUpdate,
    }
}