import { ListIitem } from "@/api/base/BaseDataModel";
import { api_costFeeSetProductIdList, api_getpayableModelByPId } from "@/api/payable/payable";
import { CostFeeSetProductIdParam, CustomerFeeProviderIdObject, PayableModelDto, PayableStableFeeItemModelDto, PayableTempFeeItemModelDto } from "@/api/payable/payableModel";
import type { BasicTableProps, VxeGridInstance } from "@/components/VxeTable";
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { useMessage } from "@/hooks/useMessage";
import { BaseFeesetAction } from "@/type/BaseFeesetAction";
import { DialogModel } from "@/type/BastType"
import { cloneDeep } from "@/utils/cloneDeep";
import { deal_ResetObject } from "@/utils/dealData";
import { fee_deal_FilterValidate } from "@/utils/feeSeting/dealData";
import { isArrayLength, isNumber } from "@/utils/is";
import { useReturnData } from "@/utils/useReturnData";
import { ref, Ref, reactive, computed, unref, nextTick } from 'vue';
import { getVxeGridData } from "../base/data";

const { resData } = useReturnData()
const { createMessage } = useMessage()
type ReceivableModelRef = Ref<VxeGridInstance | undefined>
type PayableStableFeeItemModelOmit = Omit<PayableStableFeeItemModelDto, "feeSetType">
type PartialPayableStableFeeItemModelOmit = Partial<PayableStableFeeItemModelOmit>
/**
 * 新增或编辑应付模版
 * @returns 
 */
function usePayableModelAdd(
    dialog: DialogModel,
    onClose: Fn,
    onShow: Fn,
    TemporaryFeeRef: ReceivableModelRef,
    ProviderIdFeeRef: ReceivableModelRef,
    temporaryFeeOptions: BasicTableProps,
    providerIdFeeOptions: BasicTableProps,
    resetTable: Fn,
    setLoading: Fn,
    emit
) {
    const { formValidate, resetForm } = useEleFormValidate();
    // 基础参数
    const payableModelDto = reactive<PayableModelDto>({
        activeFlag: false,
        modelName: '',
        remark: '',
        tempFeeItemModelList: [],
        stableFeeItemModelList: [],
    })
    const payableModelState = reactive({
        providerId: '',//渠道商-渠道商费用绑定
        feeSetId: '',//费用-渠道商费用绑定
        customerFeeSetIdList: [],
        type: -1,
        providerIdFeeSetData: [] as Recordable[],//渠道商列表
    })
    // 表单ref
    const formReceivableModelSetRef = ref()
    const payableModelRules = reactive({
        modelName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    })
    // 判断不是编辑状态
    const isShowView = computed(() => {
        return payableModelState.type !== BaseFeesetAction.VIEW
    })

    // 初始化数据
    const initLoadData = async (data) => {
        if (data.id) {
            const res = await api_getpayableModelByPId({ id: data.id })
            if (res && res.code == 200) {
                const data = res.data
                Object.assign(payableModelDto, { ...data })
                // 临时费用设置
                if (isArrayLength(data.tempFeeItemModelList)) {
                    temporaryFeeOptions.data = data.tempFeeItemModelList.map(item => {
                        if (isNumber(item.feeItemCategoryId)) item.feeItemCategoryId = String(item.feeItemCategoryId)
                        return item
                    })
                }
                if (isArrayLength(data.stableFeeItemModelList)) {
                    // 稳定费用
                    providerIdFeeOptions.data = data.stableFeeItemModelList.map((item) => {
                        if (isNumber(item.feeItemCategoryId)) item.feeItemCategoryId = String(item.feeItemCategoryId)
                        return item
                    })
                }
            }
        }
    }

    // 显示
    const show = (type: number, data?: Recordable) => {
        payableModelState.type = BaseFeesetAction.ADD
        // 标题
        switch (type) {
            case BaseFeesetAction.ADD:
                dialog.title = '新增应付模版'
                break;
            case BaseFeesetAction.EDIT:
                dialog.title = '编辑应付模版'
                payableModelState.type = BaseFeesetAction.EDIT
                break;
            case BaseFeesetAction.VIEW:
                dialog.title = '查看应付模版'
                payableModelState.type = BaseFeesetAction.VIEW
                break;
        }
        // 编辑
        if (type === BaseFeesetAction.EDIT || type === BaseFeesetAction.VIEW) {
            nextTick(() => {
                initLoadData(data)
            })
        }
        onShow()
    }
    // 隐藏
    const onclose = () => {
        resetForm(unref(formReceivableModelSetRef))
        const resetState = deal_ResetObject(payableModelState)
        Object.assign(payableModelState, resetState)
        payableModelState.providerId = ""
        const resetDto = deal_ResetObject(payableModelDto)
        Object.assign(payableModelDto, resetDto)
        resetTable()
        onClose()
    }

    // 产品编号搜索费用
    const hanleProductIdBind = async (obj: ListIitem) => {
        const params: CostFeeSetProductIdParam = {
            providerId: obj.value,//产品编号
            parentData: true
        }
        const resProviderId = await api_costFeeSetProductIdList(params)
        payableModelState.customerFeeSetIdList = resData(resProviderId)
    }
    // 添加产品费用绑定、结算费用绑定数据
    const hanleCustomerFeeSetBind = async (obj: CustomerFeeProviderIdObject) => {
        if (!obj.feeSetName) return
        const params: PayableStableFeeItemModelOmit = {
            providerId: obj.providerId,
            providerName: obj.providerName,
            feeItemCategoryId: obj.feeItemCategory,
            productId: obj.productId,
            productName: obj.productName,
            feeSetId: obj.id,
            feeSetParentId: obj.parentId,
            feeSetName: obj.feeSetName,
            dateVersion: `${obj.beginDate}_${obj.endDate}`
        }
        await getFilterData(ProviderIdFeeRef, params)
        payableModelState.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)
        payableModelState.providerId = ""
        payableModelState.providerIdFeeSetData = await tableRef.getData()
    }
    // 获取渠道商列表
    const getProviderIdList = computed(() => {
        return payableModelState.providerIdFeeSetData.map(
            (item) => ({ 
                id: item.providerId, 
                productId: item.providerId, 
                productName: item.providerName
            })
        )
    })

    // 去重费用数据
    const getFilterData = async (tableModelRef: ReceivableModelRef, params: PartialPayableStableFeeItemModelOmit) => {
        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 confirm = async () => {
        // 校验
        const $tableTemporaryFee = unref(TemporaryFeeRef)
        const $tableProviderFee = unref(ProviderIdFeeRef)
        Promise.all([formValidate(unref(formReceivableModelSetRef)), $tableTemporaryFee?.validate(true), $tableProviderFee?.validate(true)])
            .then(async (results) => {
                // 校验的全部状态
                const isValidate = await fee_deal_FilterValidate(results)
                if (!isValidate) return
                setLoading(true);
                // 临时费用
                payableModelDto.tempFeeItemModelList = await getVxeGridData<PayableTempFeeItemModelDto>(TemporaryFeeRef)
                // 稳定费用
                payableModelDto.stableFeeItemModelList = await getVxeGridData<PayableStableFeeItemModelDto>(ProviderIdFeeRef)
                // console.log(payableModelDto, ":参数");
                emit("savePayableModel", cloneDeep(payableModelDto), onclose, setLoading)
            })
    }

    return {
        show,
        onclose,
        confirm,
        formReceivableModelSetRef,
        payableModelDto,
        payableModelState,
        payableModelRules,
        hanleProductIdBind,
        hanleCustomerFeeSetBind,
        hanleChannelFeesSetBind,
        isShowView,
        getProviderIdList
    }
}

export {
    usePayableModelAdd
}