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

export function useWarehouse() {
    const { getUserId } = useLoginStore()
    const { dataList, total, pageIndex, pageSize } = useDataTable<Ermcp.WarehouseInfoRsp>()
    const loading = shallowRef(false)
    const columns = shallowRef(getTableColumns('warehousing_warehouse'))

    const getWarehouseList = () => {
        loading.value = true
        return queryWarehouseInfo({
            data: {
                page: pageIndex.value,
                pagesize: pageSize.value,
                userid: getUserId(),
            },
            success: (res) => {
                total.value = res.total
                dataList.value = res.data
            },
            complete: () => {
                loading.value = false
            }
        })
    }

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

export function useWarehouseForm(selectedRow?: Ermcp.WarehouseInfoRsp) {
    const { getUserId } = useLoginStore()
    const { getAccountName } = useUserStore()

    const loading = shallowRef(false)
    const formData = reactive<Proto.WarehouseApplyReq>({
        type: selectedRow?.warehousecode ? 2 : 1,
        userid: getUserId(),
        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 = () => {
        loading.value = true
        return warehouseApply({
            data: formData,
            complete: () => {
                loading.value = false
            }
        })
    }

    return {
        loading,
        accountName: getAccountName(),
        formData,
        addOrUpdate,
    }
}