import { MpsData } from '@/api/feecommon/mpsDataModel';
import { BaseTableProps } from '@/components/Table/src/types';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { CalculateUnit, EditType } from '@/type/BaseEnum';
import { cloneDeep } from '@/utils/cloneDeep';
import { ref, unref, reactive, computed, nextTick } from 'vue';
import { useAddEditProviderFeeSetRef } from './useAddEditProviderFeeSetRef';
import { v4 as uuidv4 } from 'uuid';
import { BaseZoningAction } from '@/type/BaseZoningAction';
import { useDealDynamicMeterHeadData } from '@/hooks/useDynamicMeterHead';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { isArray, isArrayLength, isNonNegativeInteger, isNumber, isUUIDv4 } from '@/utils/is';
import { FeeBasicDataDto, PartitionList, PartitionSpecialParametersList, WeightRateModel } from '@/api/customerfee/CustomerFeeSetModel';
import { zoningToInitObject, zoningToInitOnly } from '@/utils/dealData';
import { useDealHeaderData } from '@/utils/dealHeaderData';
import { CountModel } from '@/api/feecommon/countModel';
import { PartitionTemplateResult } from '@/api/costfeeitem/CostFeeItemSetModel';
import { zoningStore } from '@/store/zoning';
import { SubmitFeeItemModel } from '@/api/feeitem/FeeItemModle';
import { addFeeItemApi } from '@/api/feeitem/feeitem';
import { useReturnData } from '@/utils/useReturnData';
import { ListIitem } from '@/api/base/BaseDataModel';
import { BaseFormula } from '@/type/BaseFormula';
import { DialogModel } from '@/type/BastType';
import { formatDateTime } from '@/utils/dateFormate';
import { refreshTableColumn, useDealFeeItemData } from '@/hooks/useDealFeeItemData';
import { BasicTableProps } from '@/components/VxeTable';
import { fee_deal_Expense, fee_deal_FeeItemComputeList, fee_deal_FilterValidate } from '@/utils/feeSeting/dealData';
import { useFeesetList } from '@/store/list_feeset';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { SubmitCostFeeSetModel } from '@/api/costFeeSet/costFeeSetModel';
import { FeeItemCompute } from '@/api/feecommon/feeItemComputeModel';
import { api_costFeeSetListById } from '@/api/costFeeSet/costFeeSet';
import { useDropDownData } from '@/hooks/useDropDownData';

const { createMessage } = useMessage()
const { report } = useErrorConfirm()
/**
 * 成本费用设置-添加/编辑
 */
export default function useAddEditProviderFeeSet(dialog: DialogModel, onClose: Function, onShow: Function, emit, providerTable: BasicTableProps, providerDetailTable: BaseTableProps) {
    const {
        ruleFormFeeBasicDataRef,
        mpsdataRef,
        ruleFormProviderFeesetTableRef,
        formulaModleRef,
        basicZoningRef,
        zoningExportTemplateRef,
        zoningLoadTemplateRef,
        specialParameterRef,
        exportExpenseRef,
        xFeesetSetingDetailTableRef
    } = useAddEditProviderFeeSetRef()
    const { storeDropDownData, remoteSurveyTypeList } = useDropDownData()
    // 费用设置列表stroe
    const storeFeesetList = useFeesetList()
    // 校验表单
    const { formValidate, resetForm, clearValidateForm } = useEleFormValidate();
    // 返回数据处理
    const { resData } = useReturnData()
    // 基础参数
    const providerFeeSetParams = reactive({
        feeBasicData: {
            mpsData: {},
            currencyCode: "CNY",
        },
    } as SubmitCostFeeSetModel)
    // 基础数据
    const baseProviderFeeSet = reactive({
        type: BaseFeesetAction.ADD,
        packageType: 0,//包装类型
        zoningType: '',//分区管理
        feeItemCurrentData: {} as Recordable,//当前选中的费用类型信息
        headNum: 0,//分区数量
        editState: {} as Recordable,//编辑的数据
        allCalculateUnitList: undefined,//统一设置计量单位
        allCountTypeList: undefined,//统一设置算法
        loading: false,//加载
        lightFlagList: [
            { value: true, label: '是' },
            { value: false, label: '否' },
        ],
        remoteFlag: 0,//默认不是偏远
        remoteFlagIndex: 0,
        weightRateModelList: [
            { remoteFlag: 0, weightRatio: undefined },//否 偏远
            { remoteFlag: 1, weightRatio: undefined },//是 偏远
        ] as WeightRateModel[],//计抛系数模型
    })
    const allFeeItemComputeDetailsList = ref<Recordable[]>([])//全部费用明细数据
    let timerCalculator
    // 费用类型名称
    const feeItemName = computed(() => {
        const feeItemCurrentData = baseProviderFeeSet.feeItemCurrentData
        return feeItemCurrentData?.itemName ? feeItemCurrentData.itemName : ''
    })
    // 费项列表
    const feeItemCategoryList = computed(() => storeFeesetList.getFeeItemCategoryList)
    // 分区store数据
    const zoningstore = zoningStore()
    const portInfoList = computed(() => storeDropDownData.getPortInfoList)
    // 成本费用类型
    const costFeeItemList = computed(() => storeDropDownData.getCostFeeItemList)
    // 计量单位
    const originalCalculateUnit = computed(() => {
        const calculateUnitList = storeDropDownData.getCalculateUnitList
        const calculateUnit = calculateUnitList.find(item => item.label === "公斤")
        return calculateUnit
    })
    // 获取是否是偏远数据
    const changeRemoteFlag = (val) => {
        const findIndex = unref(remoteSurveyTypeList).findIndex(item => item.value === val)
        findIndex !== -1 ? baseProviderFeeSet.remoteFlagIndex = findIndex : baseProviderFeeSet.remoteFlagIndex = 0
    }
    // 初始化动态表头
    const { initDynamicMeterHead, clearMeterHead, columnsDynamicMeterHead, cloneColumns } = useDealDynamicMeterHeadData(providerDetailTable.columns)
    // 处理表头数据
    const { dealHeaderDetailsListDataTrget, dealOriginalDetailsListDataTrget, dealOriginalSpecialParameters } = useDealHeaderData()

    // 费用设置公用方法
    const {
        weightRateModelList,
        feesetSetingDetailFilterEmpty,
        currentFilterFeeItemData,
        hanleChangePackageType,
        hanleChangeCountTypeList,
        getUpdatefeeItemIdIndex,
        hanleInitRefresh
    } = useDealFeeItemData(baseProviderFeeSet, allFeeItemComputeDetailsList, providerDetailTable)

    // TODO 弹框确定回调
    const confirm = async () => {
        // 校验
        const $table = xFeesetSetingDetailTableRef.value
        const $tableFeesetSeting = ruleFormProviderFeesetTableRef.value
        Promise.all([formValidate(ruleFormFeeBasicDataRef.value), $tableFeesetSeting?.validate(true), $table?.validate(true)])
            .then(async (results) => {
                // 校验的全部状态
                const isValidate = await fee_deal_FilterValidate(results)
                if (!isValidate) return
                // 计抛系数参数
                providerFeeSetParams.feeBasicData.weightRateModelList = baseProviderFeeSet.weightRateModelList
                // 费用计算信息
                providerFeeSetParams.feeItemComputeList = fee_deal_FeeItemComputeList<FeeItemCompute>(providerTable.data)
                // 分区加载的模版的编号
                providerFeeSetParams.loadPartitionId = zoningstore.loadId
                // 费用明细列表数据
                await hanleSaveFeesetSetingTable()
                const customerFeeSetDto = {
                    ...baseProviderFeeSet.editState,//编辑携带过来的参数
                    ...providerFeeSetParams,//页面参数
                    beginDate: formatDateTime(providerFeeSetParams.beginDate),//更新起始时间
                }
                console.log(customerFeeSetDto, ":---------------------请求参数数据---------------------");
                emit('saveFeeBase', customerFeeSetDto, clearClose, baseProviderFeeSet.type)
            })
            .catch(errors => {
                // 校验失败，显示错误信息
                console.error(errors);
            });
    }

    // 隐藏
    const clearClose = () => {
        // 加载的模版编号设置为空
        zoningstore.addLoadId("")
        // 设置费用编号为空
        zoningstore.feeId = ""
        // 清空费用基础信息
        clearValidateForm(ruleFormFeeBasicDataRef.value)
        resetForm(ruleFormFeeBasicDataRef.value)
        // 清除动态表格校验
        // clearValidateForm(ruleFormProviderFeesetTableRef.value)
        // 重置费用设置参数
        const resetParams: Partial<SubmitCostFeeSetModel> = {
            id: "",
            beginDate: undefined,
            providerName: "",
            productName: "",
            feeItemCategoryName: "",
            feeBasicData: {
                mpsData: {} as MpsData,
                currencyCode: "CNY"
            } as FeeBasicDataDto,
            feeItemComputeList: [],
            feeItemComputeDetailsList: [],
            partitionList: [],
            partitionSpecialParametersList: []
        }
        Object.assign(providerFeeSetParams, resetParams)
        // 费用设置表格
        providerTable.data = []
        // 费用明细表格
        providerDetailTable.dataSource = []
        // 恢复费用明细表头
        providerDetailTable.columns = cloneColumns
        // 包装类型
        baseProviderFeeSet.packageType = 0
        // 分区操作
        baseProviderFeeSet.zoningType = ''
        // 关联费用明细：费用类型
        baseProviderFeeSet.feeItemCurrentData = {}
        baseProviderFeeSet.editState = {}
        // 清空费用明细的数据
        allFeeItemComputeDetailsList.value = []
        // 初始化计量单位、算法
        baseProviderFeeSet.allCalculateUnitList = undefined
        baseProviderFeeSet.allCountTypeList = undefined
        timerCalculator = null
        // 计抛系数
        baseProviderFeeSet.remoteFlagIndex = 0
        baseProviderFeeSet.remoteFlag = 0
        baseProviderFeeSet.weightRateModelList = weightRateModelList
        // 刷新费用明细表头
        refreshTableColumn(xFeesetSetingDetailTableRef, clearMeterHead)
        onClose()
    }
    // 同步获取分区数先
    const getheadNum = async (data: SubmitCostFeeSetModel) => {
        if (isArrayLength(data.partitionList)) {
            hanleSaveZoning(data.partitionList)
            return data.partitionList.length
        } else {
            // 刷新费用明细表头
            refreshTableColumn(xFeesetSetingDetailTableRef, clearMeterHead)
        }
        return 0
    }
    // 初始化编辑数据
    const initLoadData = async (row: Pick<SubmitCostFeeSetModel, "id">) => {
        baseProviderFeeSet.weightRateModelList = cloneDeep(weightRateModelList)
        baseProviderFeeSet.loading = true
        const feeRes = await api_costFeeSetListById({ id: row.id })
        if (feeRes.code !== 200) return
        const data = feeRes.data
        try {
            if (!data) return
            // 加载分区模版编号
            if (data.loadPartitionId) zoningstore.addLoadId(data.loadPartitionId)
            // 添加费用id
            if (data.id) zoningstore.feeId = data.id
            // 起始时间
            if (data.beginDate) providerFeeSetParams.beginDate = data.beginDate
            // 编辑显示：费用基础信息
            if (data.feeBasicData) {
                data.feeBasicData.currencyCode = providerFeeSetParams.feeBasicData.currencyCode//币种默认值   
                Object.assign(providerFeeSetParams.feeBasicData, data.feeBasicData)
                const weightRateModelList = data.feeBasicData.weightRateModelList
                if (isArray(weightRateModelList)) {
                    const newWeightRateModelList = baseProviderFeeSet.weightRateModelList.map(item => {
                        const findObj = weightRateModelList.find(modelItem => modelItem.remoteFlag === item.remoteFlag)
                        if (findObj) item.weightRatio = findObj.weightRatio
                        return item
                    })
                    providerFeeSetParams.feeBasicData.weightRateModelList = newWeightRateModelList
                    baseProviderFeeSet.weightRateModelList = newWeightRateModelList
                }
            }
            // 编辑显示：分区设置
            baseProviderFeeSet.headNum = await getheadNum(data)
            // 费用计算明细信息
            if (isArrayLength(data.feeItemComputeDetailsList)) {
                const newFeeItemComputeDetailsList = data.feeItemComputeDetailsList.map(item => {
                    if (!item.countModel) item.countModel = {} as CountModel
                    return item
                })
                // 处理显示明细数据
                allFeeItemComputeDetailsList.value = dealOriginalDetailsListDataTrget(newFeeItemComputeDetailsList, baseProviderFeeSet.headNum)
            }
            // 编辑显示：费用计算信息
            if (isArrayLength(data.feeItemComputeList)) {
                const feeItemComputeList = data.feeItemComputeList.map(item => {
                    if (!item.countModel) item.countModel = {} as CountModel
                    return item
                })
                providerTable.data = feeItemComputeList
                // 默认最后一条数据关联明细数据
                const lastCurrent = feeItemComputeList.length - 1
                // debugger
                hanleChangeFeeItem(feeItemComputeList[lastCurrent], unref(costFeeItemList))
            }
            // 合并主列表传的数据
            providerFeeSetParams.feeSetName = data.feeSetName//费用名称
            providerFeeSetParams.feeItemCategory = String(data.feeItemCategory)//费项类型
            providerFeeSetParams.feeItemCategoryName = data.feeItemCategoryName//费项类型
            providerFeeSetParams.providerId = data.providerId//服务商
            providerFeeSetParams.providerName = data.providerName//服务商
            providerFeeSetParams.productId = data.productId//产品名称
            providerFeeSetParams.productName = data.productName//产品名称
            providerFeeSetParams.id = baseProviderFeeSet.type === BaseFeesetAction.EDIT ? data.id : ''
            // 合并主列表传的数据
            Object.assign(baseProviderFeeSet.editState, { ...data, feeId: data.id })
        } catch (error) {
            report(error)
        } finally {
            baseProviderFeeSet.loading = false
        }
    }
    // 显示
    const show = async (type: number, data: Pick<SubmitCostFeeSetModel, "id">) => {
        // 标题
        switch (type) {
            case BaseFeesetAction.ADD:
                dialog.title = "新增成本费用设置"
                baseProviderFeeSet.type = BaseFeesetAction.ADD
                break;
            case BaseFeesetAction.VERSION:
                dialog.title = "新增成本费用设置版本"
                baseProviderFeeSet.type = BaseFeesetAction.VERSION
                break;
            case BaseFeesetAction.EDIT:
                dialog.title = "编辑成本费用设置"
                baseProviderFeeSet.type = BaseFeesetAction.EDIT
                break;
            case BaseFeesetAction.VIEW:
                dialog.title = "查看成本费用设置"
                baseProviderFeeSet.type = BaseFeesetAction.VIEW
                break;
        }
        storeDropDownData.addPackageTypeList()
        storeDropDownData.addCountTypeList()
        storeDropDownData.addUnitTypeList()
        storeDropDownData.addCalculateUnitList()
        storeDropDownData.addSpecialParametersList()
        storeDropDownData.addPartitionTypeList()
        storeDropDownData.addPortInfoList()
        storeDropDownData.addParametersList()
        storeDropDownData.addWeightArithmeticList()
        storeDropDownData.addPickValueTypeList()
        storeDropDownData.addUnitTypeIntegerList()
        storeDropDownData.addCurrencyList()
        storeDropDownData.addUnitTypeParamList()
        storeDropDownData.addShareTypeList()
        storeDropDownData.addFeeItemGetTypeList()
        storeFeesetList.addFeeItemCategoryList()
        storeDropDownData.addProductList()
        // 成本费用类型
        storeDropDownData.addCostFeeItemList()
        // 大货比价类型
        storeDropDownData.addCompareTypeList()
        // 一票多件计费方式 
        storeDropDownData.addMpsCountFeeTypeList()
        storeDropDownData.addRemoteSurveyTypeList()
        // 编辑
        if (type === BaseFeesetAction.EDIT || type === BaseFeesetAction.VERSION || type === BaseFeesetAction.VIEW) {
            // 拷贝一份数据
            nextTick(() => {
                initLoadData(data)
            })
        }
        onShow()
    }

    // 获取对应列表label值事件
    const hanleChangeGetVaule = (val: string | number, providerList: ListIitem[], field: string) => {
        const findObj = providerList.find(item => item.value === val)
        providerFeeSetParams[field] = findObj?.label || ''
    }
    // TODO 一票多件相关操作
    // 一票多件
    const hanleOpenOneVote = () => {
        const data = cloneDeep(unref(providerFeeSetParams.feeBasicData))
        unref(mpsdataRef)?.show(data)
    }
    // 获取一票多件信息
    const hanleSaveMpsData = (mpsData: MpsData) => {
        const data = cloneDeep(mpsData)
        delete data.unitType//删除外层的单位类型
        console.log(data, ":保存一票多件计算信息");
        providerFeeSetParams.feeBasicData.mpsData = data
    }

    // TODO 费用设置相关操作
    // 产品费用设置-添加行数据
    const hanleFeesetTableAdd = async () => {
        // vxe-table校验
        // const $table = xFeesetSetingDetailTableRef.value
        const $tableFeesetSeting = ruleFormProviderFeesetTableRef.value
        Promise.all([$tableFeesetSeting?.validate(true)])
            .then(async (results) => {
                // 校验的全部状态
                const isValidate = await fee_deal_FilterValidate(results)
                if (!isValidate) return
                hanleChangeFeeItem(cloneDeep(baseProviderFeeSet.feeItemCurrentData), unref(costFeeItemList))
                providerTable.data?.push({ countModel: {}, countCalculateUnit: CalculateUnit.COUNT_CALCULATE_UNIT })
                // 清除上一个费用类型
                providerDetailTable.dataSource = []
            }).catch((error) => console.error(error))
        // 
    }
    // 产品费用设置-删除行数据
    const hanleFeesetTableDelete = (data: Recordable) => {
        // const index = data.$index;
        const index = data.rowIndex;//vxe-table的index
        const dataSource = providerTable.data || []
        if (dataSource.length - 1 !== index) {
            createMessage.warning('不是最后一条不能删除！')
        } else {
            // 删除数组最后一个数据
            dataSource.pop()
            const feeItemId = data.row.feeItemId
            // 更新选中对比费用值
            const deleteIndex = getUpdatefeeItemIdIndex(providerFeeSetParams.feeBasicData.feeItemIdList, feeItemId)
            isArrayLength(providerFeeSetParams.feeBasicData.feeItemIdList) && deleteIndex > 0 ? 
                providerFeeSetParams.feeBasicData.feeItemIdList.splice(deleteIndex, 1) : 
                providerFeeSetParams.feeBasicData.feeItemIdList = []
            // 删除过滤费用设置 ==》 费用明细数据
            const cloneAllFeeItemComputeDetails = cloneDeep(allFeeItemComputeDetailsList.value)
            if (isNonNegativeInteger(feeItemId)) allFeeItemComputeDetailsList.value = cloneAllFeeItemComputeDetails.filter(item => item.feeItemId !== feeItemId)
            if (isArrayLength(dataSource)) {
                hanleChangeFeeItem(dataSource[dataSource.length - 1], unref(costFeeItemList))
                return
            }
            baseProviderFeeSet.feeItemCurrentData = {}
            providerDetailTable.dataSource = []
        }
    }
    // 打开新增费用列表
    const hanleShowFeeitem = () => {
        // addEditProviderFeeSetRef.value?.show(EditType.ADD)
    }
    // 保存新增费用列表-刷新
    const hanleSaveFeeItem = async (parm: SubmitFeeItemModel) => {
        if (parm.type !== EditType.ADD) return
        const res = await addFeeItemApi(parm)
        const code = resData(res)
        if (code !== 500) {
            storeDropDownData.feeItemList = []
            storeDropDownData.addCostFeeItemList()//刷新费用列表数据
        }
    }
    // 费用设置-费用类型
    const hanleChangeFeeItem = async (row: Recordable, list: Recordable[]) => {
        // 初始化计量单位、算法
        baseProviderFeeSet.allCalculateUnitList = undefined
        baseProviderFeeSet.allCountTypeList = undefined
        try {
            // 找到对应费用类型
            const findData = list.find(item => item.id === row.feeItemId)
            if (findData) {
                // 关联费用明细的费用类型
                baseProviderFeeSet.feeItemCurrentData = { ...findData, feeItemId: row.feeItemId } as Recordable
                // 向行数据添加费用类型名称
                Object.assign(row, { feeItemName: findData?.itemName })
            }
            // 费用设置 ==》 关联费用明细设置
            const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
            // 过滤费用明细（起始重量、结束重量、计量单位、算法）都为空
            const feesetSetingDetailFilter = feesetSetingDetailFilterEmpty(providerDetailTable.dataSource, columnsDynamicMeterHead)
            for (const details of feesetSetingDetailFilter) {
                // 去重
                if (!allFeeItemComputeDetails.some(item => item.id === details.id)) {
                    allFeeItemComputeDetails.push({ ...details, packageType: unref(baseProviderFeeSet.packageType) });
                }
            }
            // 先清空表格数据再赋值
            providerDetailTable.dataSource = []
            // 包装类型
            baseProviderFeeSet.packageType = 0
            //根据费用类型过滤数据显示
            isArrayLength(allFeeItemComputeDetails) && currentFilterFeeItemData(allFeeItemComputeDetails, row.feeItemId)
            // if (allFeeItemComputeDetails.length > 0) {
            //     currentFilterFeeItemData(allFeeItemComputeDetails, row.feeItemId)
            // }
            // console.log(allFeeItemComputeDetails, "全部费用明细数据");
        } catch (error) {
            report(error)
        }
    }
    // 产品-费用明细费添加表格数据
    const hanleFeesetDetailsTableAdd = async () => {
        const isValidate = await isFeeItemType()
        if (!isValidate) return
        // 当前操作的费用类型
        const feeItem = baseProviderFeeSet.feeItemCurrentData
        /**
         * countModel: 算法
         * feeItemId: 费用（科目）编号
         * feeItemName: 费用名称
         */
        providerDetailTable.dataSource.push({
            id: uuidv4(),
            countModel: {},
            feeItemId: feeItem.id,
            feeItemName: feeItem.itemName,
            originalCalculateUnit: unref(originalCalculateUnit)?.value
        })
    }
    // 判断
    const isFeeItemType = async () => {
        const feeItem = baseProviderFeeSet.feeItemCurrentData
        // TODO 判断费用类型、分摊方式不能为空
        if (!isNonNegativeInteger(feeItem.id)) {
            createMessage.warning('请选择费用类型！')
            return false
        }
        // if (!isNonNegativeInteger(feeItem.id) || !isNumber(Number(feeItem.shareType))) {
        //     createMessage.warning('请选择费用类型、分摊方式！')
        //     return false
        // }
        return isNonNegativeInteger(feeItem.id)// && isNonNegativeInteger(feeItem.shareType)
    }
    // 成本费用明细-表格数据删除
    const hanleFeesetDetailsTableDelete = (data: Recordable) => {
        const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
        const index = data.rowIndex
        // 删除当前费用明细表格数据
        providerDetailTable.dataSource.splice(index, 1);
        const findIndex = allFeeItemComputeDetails.findIndex(item => item._X_ROW_KEY === data.rowid)
        if (findIndex >= 0) {
            // 删除汇总的费用明细数据
            allFeeItemComputeDetails.splice(findIndex, 1);
        } else {
        }
        console.log(data, ":row");
    }
    // 保存费用明细数据
    const hanleSaveFeesetSetingTable = async () => {
        try {
            // 要排除以分区为键的编号
            const partitionExcludeKeys = isArrayLength(providerFeeSetParams.partitionList) && providerFeeSetParams.partitionList.map(item => item.id)
            // 判断费用明细原数据已当前数据做对比
            // 如果没有切换费用类型：更新费用明细设置
            const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
            // 过滤费用明细（起始重量、结束重量、计量单位、算法）都为空
            const feesetSetingDetailFilter = feesetSetingDetailFilterEmpty(providerDetailTable.dataSource, columnsDynamicMeterHead)
            for (const details of feesetSetingDetailFilter) {
                // 去重
                if (!allFeeItemComputeDetails.some(item => item.id === details.id)) {
                    allFeeItemComputeDetails.push({ ...details, packageType: unref(baseProviderFeeSet.packageType) });
                }
            }
            const targetDetailsList = dealHeaderDetailsListDataTrget(allFeeItemComputeDetails, partitionExcludeKeys as string[])
            console.log(targetDetailsList, ":获取处理费用明细表格数据");
            providerFeeSetParams.feeItemComputeDetailsList = targetDetailsList
        } catch (error) {
            report(error)
        }
    }

    // 改变原有的费用明细的费用类型
    const changeOnFeeItemList = (row: Recordable) => {
        if (!row.oldFees && !isNumber(row.oldFees.feeItemId)) return
        // 查找最新的费用类型信息
        const _costFeeItemList = unref(costFeeItemList) as Recordable[]
        const findData = _costFeeItemList.find(item => item.id === row.feeItemId) as Recordable
        // 改变当前行费用设置费用信息
        baseProviderFeeSet.feeItemCurrentData = { ...findData, feeItemId: row.feeItemId }
        Object.assign(row, { feeItemName: findData?.itemName })
        // 全部费用明细数据
        const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
        allFeeItemComputeDetails.map(item => {
            // 改变对应的费用类型信息
            if (item.feeItemId === row.oldFees.feeItemId) {
                item.feeItemId = findData.id
                item.feeItemName = findData.itemName
            }
        })
    }
    // 改变分摊类型
    const hanleChangeShareType = (shareType: string, row: Recordable) => {
        // 设置当前分摊类型
        baseProviderFeeSet.feeItemCurrentData.shareType = shareType
        // 从全部费用明细数据修改分摊类型
        const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
        if (isArrayLength(allFeeItemComputeDetails)) {
            allFeeItemComputeDetails.map(item => {
                // 改变分摊类型
                if (item.feeItemId === row.feeItemId) item.shareType = shareType
            })
        }
    }
    // 点击费用类型下拉框 ==> 费用明细数据
    const hanleChangeVisible = (visible: boolean, row: Recordable) => {
        // 保存旧的费用设置信息
        console.log(visible, ":保存旧的费用设置信息");
        if (visible) {
            hanleChangeFeeItem(row, unref(costFeeItemList))
            if (row.oldFees) delete row.oldFees
            row.oldFees = cloneDeep(row)
        } else {
            changeOnFeeItemList(row)
        }
    }
    // 点击费用设置表格单元格
    const hanleCellClick = (scope) => {
        const $table = ruleFormProviderFeesetTableRef.value
        if (!$table) return
        const isEditByRow = $table.isEditByRow(scope.row)
        if (isEditByRow) return
        hanleChangeFeeItem(scope.row, unref(costFeeItemList))
    }
    // 算法下拉框
    const hanleBlurCalculator = (row: Recordable) => {
        clearTimeout(timerCalculator)
        // 按照公式value显示公式弹框
        timerCalculator = setTimeout(() => {
            if (row.countModel.countType === BaseFormula.FORMULA) {
                formulaModleRef.value?.show(unref(storeDropDownData.parametersList), row)
            } else {
                // 如果是其它类型清空公式
                row.countModel.formula = undefined
                row.countModel.formulaExplain = undefined
            }
        }, 100)
    }

    // TODO 分区相关操作
    // 选择的分区操作
    const changeZoningAction = (val: number) => {
        // 分区数据
        const partitionList = cloneDeep(providerFeeSetParams.partitionList)
        switch (val) {
            case BaseZoningAction.ZONING_SETING:
                // 分区设置
                unref(basicZoningRef)?.show(unref(portInfoList), partitionList, undefined);
                break;
            case BaseZoningAction.ZONING_VIEW:
                // 分区查看
                unref(basicZoningRef)?.show(unref(portInfoList), partitionList, BaseZoningAction.ZONING_VIEW);
                break;
            case BaseZoningAction.ZONING_TEMPLATE:
                // 分区模板
                unref(zoningExportTemplateRef)?.show(partitionList)
                break;
            case BaseZoningAction.ZONING_TEMPLATE_LOAD:
                // 分区模版加载
                unref(zoningLoadTemplateRef)?.show()
                break;
            case BaseZoningAction.ZONING_SPECIAL_PARAMETER:
                // 特殊参数
                const partitionSpecialParametersList = cloneDeep(providerFeeSetParams.partitionSpecialParametersList)
                const tableList = dealOriginalSpecialParameters(partitionSpecialParametersList, baseProviderFeeSet.headNum)
                specialParameterRef.value?.show(tableList)
                break;
            default:
                createMessage.error('错误类型！')
                break;
        }
    }
    // 保存特殊参数数据
    const hanleSaveSpecialParameter = (parametersList: PartitionSpecialParametersList[]) => {
        providerFeeSetParams.partitionSpecialParametersList = parametersList
    }
    // 加载分区模版数据
    const hanleSaveLoadPartition = async (data: PartitionTemplateResult[]) => {
        // console.log(data, ":加载分区模版数据");
        if (!isArrayLength(data)) return
        const partitionList = data[0].partitionList as PartitionList[]
        if (!isArrayLength(partitionList)) return
        try {
            // 模版的费用编号列表
            const loadFeeIdList = await zoningstore.addFeeIdList(data[0])
            // 判断是否有用过这个模版
            const isUse = loadFeeIdList.some(id => id === providerFeeSetParams.id)
            // 全部费用明细数据
            const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
            const partitionListUuid = partitionList.map(item => item.id)
            // 显示分区表格表头
            displayZoningTableHead(partitionList)
            // 全部费用明细数据 ==》 重新过滤分区编号
            for (let obj of allFeeItemComputeDetails) {
                for (let key of Object.keys(obj)) {
                    if (isUUIDv4(key) && !partitionListUuid.includes(key)) {
                        delete obj[key];
                    }
                }
            }
            // 为重置明细数据的分区费用设置
            if (isUse) {
                if (!isArrayLength(allFeeItemComputeDetails)) return
                // 获取当前进来的分区编号
                const currentUuidArr: string[] = []
                for (let key of Object.keys(allFeeItemComputeDetails[0])) {
                    // 是uuid格式=分区编号
                    if (isUUIDv4(key)) {
                        currentUuidArr.push(key)
                    }
                }
                // 取不同分区编号值
                const targetArr = zoningToInitOnly(currentUuidArr, partitionListUuid)
                const zoningInitData = zoningToInitObject(targetArr)
                // 以键分区编号设置为0
                allFeeItemComputeDetails.map(details => {
                    if (details) {
                        // 添加新的分区编号
                        Object.assign(details, zoningInitData)
                    }
                })
            } else {
                // 以键分区编号设置为0
                const zoningInitData = zoningToInitObject(partitionListUuid)
                allFeeItemComputeDetails.map(details => {
                    if (details) {
                        // 添加新的分区编号
                        Object.assign(details, zoningInitData)
                    }
                })
            }
            console.log(allFeeItemComputeDetails, ":allFeeItemComputeDetails === 全部费用明细数据");
        } catch (error) {
            report(error)
        }
    }
    // 显示动态表头数据
    const displayZoningTableHead = (Zoningdata: PartitionList[]) => {
        providerDetailTable.columns = []
        // 分区数据
        debugger
        providerFeeSetParams.partitionList = Zoningdata
        const { columns, headNum } = initDynamicMeterHead(Zoningdata)
        providerDetailTable.columns = columns
        baseProviderFeeSet.headNum = headNum
        // 初始化分区费用值
        isArrayLength(providerDetailTable.dataSource) && feesetSetingDetailFilterEmpty(providerDetailTable.dataSource, columnsDynamicMeterHead)
        // 刷新表头信息
        xFeesetSetingDetailTableRef.value?.refreshColumn()
        // console.log(Zoningdata, ":《==保存分区信息", columns, ":《==合并表格表头");
    }
    // 保存分区信息
    const hanleSaveZoning = (Zoningdata: PartitionList[]) => {
        try {
            displayZoningTableHead(Zoningdata)
        } catch (error) {
            report(error)
        }
    }
    // 快速导入费用
    const hanleExportExpense = () => exportExpenseRef.value?.show()
    const hanleSaveExpense = (detailList: Recordable[]) => {
        // 处理添加进全部费用明细中
        allFeeItemComputeDetailsList.value = fee_deal_Expense(detailList, allFeeItemComputeDetailsList, baseProviderFeeSet.packageType)
        const allFeeItemComputeDetailsList_ = unref(allFeeItemComputeDetailsList)
        // 先清空表格数据再赋值
        providerDetailTable.dataSource = []
        //根据费用类型过滤数据显示
        isArrayLength(allFeeItemComputeDetailsList_) && currentFilterFeeItemData(allFeeItemComputeDetailsList_, baseProviderFeeSet.feeItemCurrentData.id)
    }

    return {
        show,
        confirm,
        clearClose,
        hanleOpenOneVote,
        hanleSaveMpsData,
        hanleChangeVisible,
        hanleFeesetTableAdd,
        hanleFeesetTableDelete,
        hanleFeesetDetailsTableAdd,
        hanleFeesetDetailsTableDelete,
        hanleBlurCalculator,
        hanleChangeFeeItem,
        hanleChangePackageType,
        hanleChangeCountTypeList,
        hanleInitRefresh,
        changeZoningAction,
        hanleSaveFeeItem,
        hanleSaveZoning,
        hanleSaveSpecialParameter,
        hanleSaveLoadPartition,
        hanleExportExpense,
        hanleSaveExpense,
        hanleChangeGetVaule,
        hanleCellClick,
        changeRemoteFlag,
        ruleFormFeeBasicDataRef,
        mpsdataRef,
        ruleFormProviderFeesetTableRef,
        formulaModleRef,
        basicZoningRef,
        zoningExportTemplateRef,
        zoningLoadTemplateRef,
        specialParameterRef,
        exportExpenseRef,
        xFeesetSetingDetailTableRef,
        columnsDynamicMeterHead,
        providerFeeSetParams,
        baseProviderFeeSet,
        feeItemName,
        feeItemCategoryList,
        originalCalculateUnit
    }
}