import type { ListIitem } from '@/api/base/BaseDataModel';
import { LadingPayableStableFeeItemModelDto } from '@/api/lading/ladingModle';
import { api_costFeeSetProductIdList } from '@/api/payable/payable';
import { CostFeeSetProductIdParam, CustomerFeeProviderIdObject, PayableStableFeeItemModelDto } from '@/api/payable/payableModel';
import { api_customerFeeProductIdList } from '@/api/receivable/receivable';
import { CustomerFeeProductIdParams, CustomerFeeProductObject, StableFeeItemModelDto } from '@/api/receivable/receivableModel';
import { VxeGridInstance } from '@/components/VxeTable';
import { useMessage } from '@/hooks/useMessage';
import { BaseFeeSetProductBind } from '@/type/BaseLadingBill';
import { deal_ResetObject } from '@/utils/dealData';
import { deal_FindItemName } from '@/utils/dealFindData';
import { useReturnData } from '@/utils/useReturnData';
import { reactive, Ref, unref, computed } from 'vue';

type ReceivableModelRef = Ref<VxeGridInstance | undefined>
type PayableStableFeeItemModelOmit = Omit<PayableStableFeeItemModelDto, "feeSetType">
type PartialPayableStableFeeItemModelOmit = Partial<PayableStableFeeItemModelOmit>
const { resData } = useReturnData()
const { createMessage } = useMessage()
/**
 * 应收下拉列表产品绑定费用
 */
function useReceivableSelectBind(
    ProductFeeRef: ReceivableModelRef,
    ClosingCostFeeRef: ReceivableModelRef,
) {
    const receivableSelectState = reactive({
        productId: '',//产品编号-产品费用绑定
        settleProductId: '',//产品编号-结算费用绑定 
        feeSetId: '',//费用-产品费用绑定
        customerFeeSetIdList: [] as CustomerFeeProductObject[],
        settleCustomerFeeSetId: '',//费用-结算费用绑定
        settleCustomerFeeSetList: [],
        customerFeeSetData: [] as Recordable[],//客户价表格数据
        settleCustomerFeeSetData: [] as Recordable[],//结算价表格数据
    })

    // 产品编号搜索费用
    const hanleProductIdBind = async (obj: ListIitem, type: 0 | 1) => {
        if (!obj.value) return
        const params: CustomerFeeProductIdParams = {
            feeSetType: type,//费用类型(客户价、结算价)
            productId: obj.value,//产品编号
            parentData: true
        }
        switch (type) {
            case 1://客户价
                const resProductId = await api_customerFeeProductIdList(params)
                receivableSelectState.customerFeeSetIdList = resData(resProductId)
                break;
            case 0://结算价
                const ressettleProductId = await api_customerFeeProductIdList(params)
                receivableSelectState.settleCustomerFeeSetList = resData(ressettleProductId)
                break;
        }
    }
    // 添加产品费用绑定、结算费用绑定数据
    const hanleCustomerFeeSetBind = async (obj: CustomerFeeProductObject, type: 0 | 1) => {
        if (!obj.feeSetName) return
        const params: Omit<LadingPayableStableFeeItemModelDto, "feeItemCategoryId"> = {
            feeSetType: type,
            feeSetId: obj.id,
            feeSetName: obj.feeSetName,
            productId: obj.productId,
            productName: obj.productName,
            feeSetParentId: obj.parentId,
            dateVersion: `${obj.beginDate}_${obj.endDate}`
        }
        switch (type) {
            case 1:
                await getFilterData(ProductFeeRef, params)
                receivableSelectState.feeSetId = ''
                break;
            case 0:
                await getFilterData(ClosingCostFeeRef, params)
                receivableSelectState.settleCustomerFeeSetId = ''
                break;
        }
    }
    // 去重费用数据
    const getFilterData = async (tableModelRef: ReceivableModelRef, params: Omit<StableFeeItemModelDto, "feeItemCategoryId">) => {
        const tableRef = unref(tableModelRef)
        if (!tableRef) return
        const tableList = await tableRef.getData()
        const isFlag = tableList.some(item => item.feeSetId === params.feeSetId)
        if (isFlag) {
            createMessage.error("不能添加重复费用数据！")
            return
        }
        tableRef.data?.push(params)
    }

    // 重置
    const receivableSelectReset = () => {
        const resetState = deal_ResetObject(receivableSelectState)
        Object.assign(receivableSelectState, resetState)
        receivableSelectState.productId = ""
        receivableSelectState.settleProductId = ""
    }

    // 客户费用绑定产品列表数据
    const getProductIdList = computed(() => {
        return receivableSelectState.customerFeeSetData.map(
            (item) => ({
                id: item.productId,
                productId: item.productId,
                productName: item.productName
            })
        )
    })
    // 结算费用绑定产品列表数据
    const getSettleProductIdList = computed(() => {
        return receivableSelectState.settleCustomerFeeSetData.map(
            (item) => ({
                id: item.productId,
                productId: item.productId,
                productName: item.productName
            })
        )
    })
    // 添加绑定数据
    const getFilterProductBindData = async (tableModelRef: ReceivableModelRef, params: Partial<StableFeeItemModelDto>) => {
        const tableRef = unref(tableModelRef)
        if (!tableRef) return
        tableRef.data?.push(params)
        switch (params.feeSetType) {
            case BaseFeeSetProductBind.CUSTOMER_FEE_BINDING:
                const customerList = await tableRef.getData()
                receivableSelectState.customerFeeSetData = customerList
                break;
            case BaseFeeSetProductBind.SETTLEMENT_FEE_BINDING:
                const settleCustomerList = await tableRef.getData()
                receivableSelectState.settleCustomerFeeSetData = settleCustomerList
                break;
        }
    }
    // 根据产品名称添加客户费用绑定数据
    const hanleCustomerFeeSetProductBind = async (obj: ListIitem, type: BaseFeeSetProductBind) => {
        if (!obj.value) return
        const params: Partial<LadingPayableStableFeeItemModelDto> = {
            feeSetType: type,
            productId: String(obj.value),
            productName: obj.label,
        }
        switch (type) {
            case BaseFeeSetProductBind.CUSTOMER_FEE_BINDING:
                await getFilterProductBindData(ProductFeeRef, params)
                receivableSelectState.productId = ""
                break;
            case BaseFeeSetProductBind.SETTLEMENT_FEE_BINDING:
                await getFilterProductBindData(ClosingCostFeeRef, params)
                receivableSelectState.settleProductId = ""
                break;
        }
    }

    return {
        receivableSelectState,
        getProductIdList,
        getSettleProductIdList,
        hanleProductIdBind,
        hanleCustomerFeeSetBind,
        receivableSelectReset,
        hanleCustomerFeeSetProductBind
    }
}

/**
 * 应付下拉列表渠道商绑定费用
 */
function usePayableSelectBind(ProviderIdFeeRef: ReceivableModelRef) {
    const payableSelectState = reactive({
        providerId: '',//渠道商-渠道商费用绑定
        feeSetId: '',//费用-渠道商费用绑定
        customerFeeSetIdList: [],
        providerIdFeeSetData: [] as Recordable[],//渠道商费用列表
    })

    // 产品编号搜索费用
    const hanleProductIdBind = async (obj: ListIitem) => {
        if (!obj.value) return
        const params: CostFeeSetProductIdParam = {
            providerId: obj.value,//产品编号
            parentData: true
        }
        const resProviderId = await api_costFeeSetProductIdList(params)
        payableSelectState.customerFeeSetIdList = resData(resProviderId)
    }
    // 添加产品费用绑定、结算费用绑定数据
    const hanleCustomerFeeSetBind = async (obj: CustomerFeeProviderIdObject) => {
        if (!obj.feeSetName) return
        const params: PayableStableFeeItemModelOmit = {
            providerId: obj.providerId,
            providerName: obj.providerName,
            productId: obj.productId,
            productName: obj.productName,
            feeItemCategoryId: obj.feeItemCategory,
            feeSetId: obj.id,
            feeSetParentId: obj.parentId,
            feeSetName: obj.feeSetName,
            dateVersion: `${obj.beginDate}_${obj.endDate}`
        }
        await getFilterData(ProviderIdFeeRef, params)
        payableSelectState.feeSetId = ''
    }

    // 添加渠道商费用绑定数据
    const hanleChannelFeesSetBind = async (obj: ListIitem) => {
        if (!obj.value) return
        const params: PartialPayableStableFeeItemModelOmit = {
            providerId: obj.value,
            providerName: obj.label,
        }
        const tableRef = unref(ProviderIdFeeRef)
        if (!tableRef) return
        tableRef.data?.push(params)
        payableSelectState.providerId = ""
    }
    // 获取渠道商列表
    const getProviderIdList = computed(() => {
        return payableSelectState.providerIdFeeSetData.map(
            (item) => ({
                id: item.providerId,
                productId: item.providerId,
                productName: item.providerName
            })
        )
    })

    // 去重费用数据
    const getFilterData = async (tableModelRef: ReceivableModelRef, params: PayableStableFeeItemModelOmit) => {
        const tableRef = unref(tableModelRef)
        if (!tableRef) return
        const tableList = await tableRef.getData()
        const isFlag = tableList.some(item => item.feeSetId === params.feeSetId)
        if (isFlag) {
            createMessage.error("不能添加重复费用数据！")
            return
        }
        tableRef.data?.push(params)
    }

    // 重置
    const payableSelectReset = () => {
        const resetState = deal_ResetObject(payableSelectState)
        Object.assign(payableSelectState, resetState)
        payableSelectState.providerId = ""
    }

    return {
        payableSelectState,
        getProviderIdList,
        hanleProductIdBind,
        hanleCustomerFeeSetBind,
        hanleChannelFeesSetBind,
        payableSelectReset,
    }
}

/**
 * change事件
 * @param fn1 
 * @param fn2 
 * @returns 
 */
function useChangeSelectId(updateStatusFn1: Fn, updateStatusFn2: Fn) {
    // 产品名称及校验
    const changeSelectId = (val, scope, list, field, isTemporary = true) => {
        const itemName = deal_FindItemName(val, list);
        if (!itemName) return itemName;
        scope.row[field] = itemName;
        if (isTemporary) {
            updateStatusFn1(scope);
        } else {
            updateStatusFn2(scope);
        }
    };

    return {
        changeSelectId
    }
}

export {
    useReceivableSelectBind,
    usePayableSelectBind,
    useChangeSelectId
}