import { ListIitem } from "@/api/base/BaseDataModel";
import { PartitionTemplateResult, SubmitCustomerFeeSetModel } from "@/api/costfeeitem/CostFeeItemSetModel";
import { FeeBasicDataDto, PartitionList, PartitionSpecialParametersList, WeightRateModel } from "@/api/customerfee/CustomerFeeSetModel";
import { FeeItemCompute } from "@/api/feecommon/feeItemComputeModel";
import { MpsData } from "@/api/feecommon/mpsDataModel";
import { EexpenseType } from "@/components/FormulaList/types";
import { BaseTableProps, TableActionType } from "@/components/Table/src/types";
import { useDealDynamicMeterHeadData } from "@/hooks/useDynamicMeterHead";
import { useMessage } from "@/hooks/useMessage";
import { BaseZoningAction } from "@/type/BaseZoningAction";
import { cloneDeep } from "@/utils/cloneDeep";
import { useDealHeaderData } from "@/utils/dealHeaderData";
import { ElMessage } from "element-plus";
import { ref, reactive, computed, unref, nextTick } from "vue";
import { v4 as uuidv4 } from 'uuid';
import { useEleFormValidate } from "@/hooks/useEleFormValidate";
import { useDropDownData } from "@/hooks/useDropDownData";
import { CountModel } from "@/api/feecommon/countModel";
import { isArray, isArrayLength, isNonNegativeInteger, isNumber, isUUIDv4 } from "@/utils/is";
import { zoningToInitObject, zoningToInitOnly } from "@/utils/dealData";
import { useErrorConfirm } from "@/utils/useErrorConfirm";
import { CalculateUnit } from "@/type/BaseEnum";
import { zoningStore } from '@/store/zoning';
import { BaseFormula } from "@/type/BaseFormula";
import { refreshTableColumn, useDealFeeItemData } from "@/hooks/useDealFeeItemData";
import { api_GetCustomerFeeSetByPId } from "@/api/customerfee/customerfeeset";
import { useFilterTypeList } from "@/hooks/useFilterTypeList";
import { BasicTableProps, VxeGridInstance, VxeTableInstance } from "@/components/VxeTable";
import { fee_deal_FeeItemComputeList, fee_deal_FilterValidate } from "@/utils/feeSeting/dealData";
import { BaseFeesetAction } from "@/type/BaseFeesetAction";
import { BusinessFeesetField, FeeSetType } from "@/type/BaseBusinessFeeseType";

const { createMessage } = useMessage()
const { report } = useErrorConfirm()
/**
 * 费用设置主内容
 */
export function useBusinessFeesetDetailRote(onShow: Fn, onClose: Fn, setLoading: Fn, feesetSetingTable: BasicTableProps, feesetSetingDetailTable: BaseTableProps, emit, ruleFormFeeBasicData, feesetSetingGridRules) {
    // 客户费用设置
    const customerFeeSetParams = reactive<SubmitCustomerFeeSetModel>({
        feeBasicData: {
            mpsData: {},
            currencyCode: "CNY",
            weightRateModelList: []
        },//费用基础信息
        feeItemComputeDetailsList: [],//费用计算明细信息
        partitionList: [],//分区设置
    } as unknown as SubmitCustomerFeeSetModel)
    // 组件的基础数据
    const baseData = reactive({
        zoningType: '',//分区管理
        headNum: 0,//分区数量
        packageType: 0,//包装类型
        baseFeeset: {} as Recordable,//主体列表信息
        feeItemRow: {} as Recordable,//费用类型id参数
        loading: false,//加载
        actionsType: BaseFeesetAction.FEESET_SETING,//默认是设置
        lightFlagList: [
            { value: true, label: '是' },
            { value: false, label: '否' },
        ],
        remoteFlag: 0,//默认不是偏远
        remoteFlagIndex: 0,
        weightRateModelList: [] as WeightRateModel[],//计抛系数模型
        oldPartitionSpecialParametersList: [] as Recordable[]
    })
    // 全部费用明细数据
    const allFeeItemComputeDetailsList = ref<Recordable[]>([])
    // 基础表单Ref
    const ruleFormFeeBasicDataRef = ref()
    //分区 ref属性
    const zoningActionsRef = ref<{ show: (portInfos?: ListIitem[], partitionList?: Recordable[], actionType?: number) => void }>()
    //特殊参数 ref属性
    const specialParameterRef = ref<{ show: (list: Recordable[]) => void }>()
    //一票多件 ref属性
    const mpsdataRef = ref<{ show: (feeBasicData: Partial<FeeBasicDataDto>) => void }>()
    //公式计算 ref属性
    const formulaModle = ref<{ show: (unitTypes?: ListIitem[], row?: Recordable) => void }>()
    // 分区导出模版
    const zoningExportTemplateRef = ref<{ show: (data: PartitionList[]) => void }>()
    // 分区模版加载
    const zoningLoadTemplateRef = ref<{ show: () => void }>()
    // 快速导入费用
    const exportExpenseRef = ref<{ show: () => void }>()
    // 费用设置动态表格-表单-DOM节点
    const ruleFormFeesetSetingTableRef = ref<VxeGridInstance>();
    // 费用明细动态表格-表单-DOM节点
    const ruleFormFeesetSetingDetailTableRef = ref()
    // 费用明细 vxe-table ref
    const xFeesetSetingDetailTableRef = ref<VxeTableInstance>()
    // 费用设置状态
    const isActionsType = computed(() => {
        return baseData.actionsType === BaseFeesetAction.FEESET_SETING
    })
    // 处理表头数据
    const { dealHeaderDetailsListDataTrget, dealOriginalDetailsListDataTrget, dealOriginalSpecialParameters, dealPartitionListResult } = useDealHeaderData()
    // 分区store数据
    const zoningstore = zoningStore()
    // 下拉列表数据
    const { 
        storeDropDownData,
        portInfoList, 
        parametersList, 
        feeItemLists, 
        countTypeList, 
        packageTypeList, 
        calculateUnitList, 
        specialParametersList, 
        feeItemGetTypeList,
        currencyList,
        compareTypeList,
        remoteSurveyTypeList
    } = useDropDownData()
    // 获取是否是偏远数据
    const changeRemoteFlag = (val) => {
        const findIndex = unref(remoteSurveyTypeList).findIndex(item => item.value === val)
        findIndex !== -1 ? baseData.remoteFlagIndex = findIndex : baseData.remoteFlagIndex = 0
    }
    // 初始化动态表头
    const { initDynamicMeterHead, clearMeterHead, columnsDynamicMeterHead, cloneColumns } = useDealDynamicMeterHeadData(feesetSetingDetailTable.columns)

    // 校验表单
    const { formValidate, resetForm, clearValidateForm } = useEleFormValidate();

    // 处理费用类型数据 
    const { newSourceLists: newFeeItemList, oldList: oldFeeItemList, filterNewsList: filterOnFeeItemList } = useFilterTypeList<BasicTableProps>(feesetSetingTable, 'feeItemId', feeItemLists, 'id')

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

    // 同步获取分区数先
    const getheadNum = async (data: SubmitCustomerFeeSetModel) => {
        if (isArrayLength(data.partitionList)) {
            hanleSaveZoning(data.partitionList)
            return data.partitionList.length
        } else {
            refreshTableColumn(xFeesetSetingDetailTableRef, clearMeterHead)
        }
        return 0
    }
    // 更新最低折扣列是否显示
    const initDiscountIsShow = async (data) => {
        if (!data) return
        /**
         * 费用设置类型
         * Integer feeSetType;
            OperatingOrganization(0,"结算价"), ==>才校验
            Customer(1,"客户价"),
            Public(2,"公布价");
        */
        const _ruleFormFeesetSetingTableRef = unref(ruleFormFeesetSetingTableRef)
        data.feeSetType === FeeSetType.OPERATING_ORGANIZATION ? 
            feesetSetingGridRules[BusinessFeesetField.DISCOUNT] = [{ required: true, message: '请输入最低折扣' }] : 
            feesetSetingGridRules[BusinessFeesetField.DISCOUNT] = [{ required: false }];
        if(_ruleFormFeesetSetingTableRef) await _ruleFormFeesetSetingTableRef.resetColumn() 
        feesetSetingTable.columns?.map((item) => {
            if(_ruleFormFeesetSetingTableRef) {
                item.field === BusinessFeesetField.DISCOUNT && data.feeSetType !== FeeSetType.OPERATING_ORGANIZATION && _ruleFormFeesetSetingTableRef.hideColumn(BusinessFeesetField.DISCOUNT)
            }
        })
    }
    // 初始化编辑数据
    const initLoadData = async (row: SubmitCustomerFeeSetModel) => {
        baseData.weightRateModelList = cloneDeep(weightRateModelList)
        baseData.loading = true
        const feeRes = await api_GetCustomerFeeSetByPId({ 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.feeBasicData) {
                // data.feeBasicData.currencyCode = customerFeeSetParams.feeBasicData.currencyCode//币种默认值
                Object.assign(customerFeeSetParams.feeBasicData, data.feeBasicData)
                const weightRateModelList = data.feeBasicData.weightRateModelList
                if (isArray(weightRateModelList)) {
                    const newWeightRateModelList = baseData.weightRateModelList.map(item => {
                        const findObj = weightRateModelList.find(modelItem => modelItem.remoteFlag === item.remoteFlag)
                        if (findObj) item.weightRatio = findObj.weightRatio
                        return item
                    })
                    customerFeeSetParams.feeBasicData.weightRateModelList = newWeightRateModelList
                    baseData.weightRateModelList = newWeightRateModelList
                }
            }
            // 编辑显示：分区设置
            baseData.headNum = await getheadNum(data)
            // 费用计算明细信息
            if (isArrayLength(data.feeItemComputeDetailsList)) {
                const newFeeItemComputeDetailsList = data.feeItemComputeDetailsList.map(item => {
                    if (!item.countModel) item.countModel = {} as CountModel
                    return item
                })
                // console.log(newFeeItemComputeDetailsList, ":newFeeItemComputeDetailsList ==>");
                // 处理显示明细数据
                allFeeItemComputeDetailsList.value = dealOriginalDetailsListDataTrget(newFeeItemComputeDetailsList, baseData.headNum)
            }
            // 编辑显示：费用计算信息
            if (isArrayLength(data.feeItemComputeList)) {
                const feeItemComputeList = data.feeItemComputeList.map(item => {
                    if (!item.countModel) item.countModel = {} as CountModel
                    return item
                })
                feesetSetingTable.data = feeItemComputeList
                // 默认最后一条数据关联明细数据
                const lastCurrent = feeItemComputeList.length - 1
                hanleChangeFeeItem(feeItemComputeList[lastCurrent], feeItemLists.value)
            }
            // 编辑显示：特殊参数列表
            if (isArrayLength(data.partitionSpecialParametersList)) {
                const _partitionSpecialParametersList = data.partitionSpecialParametersList
                customerFeeSetParams.partitionSpecialParametersList = _partitionSpecialParametersList
                // 异常数据处理
                if (data.length % baseData.headNum !== 0) {
                    const idList = customerFeeSetParams.partitionList.map(item => item.id)
                    customerFeeSetParams.partitionSpecialParametersList = _partitionSpecialParametersList.filter(item => idList.includes(item.partitionId))
                }
                baseData.oldPartitionSpecialParametersList = dealPartitionListResult(customerFeeSetParams.partitionSpecialParametersList, baseData.headNum)
            }
            initDiscountIsShow(data)
            // 合并主列表传的数据
            customerFeeSetParams.feeId = data.id
            Object.assign(baseData.baseFeeset, data)
        } catch (error) {
            report(error)
        } finally {
            baseData.loading = false
        }
    }
    // 控制费用设置弹框显示操作
    const show = async (row: SubmitCustomerFeeSetModel, type: number) => {
        // 查看/设置
        baseData.actionsType = type
        //显示
        onShow();
        // 拷贝一份数据
        const customerFeeSetData = cloneDeep(row)
        initLoadData(customerFeeSetData)
        storeDropDownData.addCurrencyList()
        storeDropDownData.addPackageTypeList()
        storeDropDownData.addCountTypeList()
        storeDropDownData.addUnitTypeList()
        storeDropDownData.addCalculateUnitList()
        storeDropDownData.addSpecialParametersList()
        storeDropDownData.addPartitionTypeList()
        storeDropDownData.addPortInfoList()
        storeDropDownData.addParametersList()
        storeDropDownData.addMpsParametersList()
        storeDropDownData.addWeightArithmeticList()
        storeDropDownData.addPickValueTypeList()
        storeDropDownData.addUnitTypeIntegerList()
        storeDropDownData.addFeeItemGetTypeList()
        storeDropDownData.addUnitTypeParamList()
        storeDropDownData.addCompareTypeList()
        storeDropDownData.addMpsCountFeeTypeList()
        storeDropDownData.addRemoteSurveyTypeList()
    };

    // 费用设置-弹框确定事件
    const confirm = async () => {
        // 校验
        const $table = xFeesetSetingDetailTableRef.value
        const $tableFeesetSeting = ruleFormFeesetSetingTableRef.value
        Promise.all([formValidate(ruleFormFeeBasicDataRef.value), $tableFeesetSeting?.validate(true), $table?.validate(true)])
            .then(async (results) => {
                debugger
                // 校验的全部状态
                const isValidate = await fee_deal_FilterValidate(results)
                if (!isValidate) return
                setLoading(true)
                // 计抛系数参数
                customerFeeSetParams.feeBasicData.weightRateModelList = baseData.weightRateModelList as WeightRateModel[]
                // 费用计算信息
                customerFeeSetParams.feeItemComputeList = fee_deal_FeeItemComputeList<FeeItemCompute>(feesetSetingTable.data)
                // 分区加载的模版的编号
                customerFeeSetParams.loadPartitionId = zoningstore.loadId
                // 费用明细列表数据
                await hanleSaveFeesetSetingTable()
                const customerFeeSetDto = {
                    ...baseData.baseFeeset,
                    ...customerFeeSetParams
                }
                console.log(customerFeeSetDto, ":请求参数数据---------------------");
                emit('saveFeeBase', customerFeeSetDto, clearClose)
                // 取消弹窗
                // onClose()
            })
            .catch(errors => {
                // 校验失败，显示错误信息
                console.error(errors);
            });
    };

    // 初始化分区特殊参数数据
    const initPartitionSpecialParametersList = () => {
        if (isArrayLength(baseData.oldPartitionSpecialParametersList)) {
            const idList = customerFeeSetParams.partitionList.map(item => item.id)
            baseData.oldPartitionSpecialParametersList.map((oItem, oIndex) => {
                if (isArrayLength(oItem)) {
                    const currentOld = oItem[0]
                    const oldIdList = oItem.map(sItem => sItem.partitionId)
                    // 分区数据大于原有的数据，就添加新数据
                    if (idList.length > oldIdList.length) {
                        idList.forEach((id, index) => {
                            if (!oldIdList.includes(id)) {
                                oItem.splice(index, 0, {
                                    feeItemId: currentOld.feeItemId,
                                    specialParametersId: currentOld.specialParametersId,
                                    partitionId: id,
                                    setValue: 0,
                                })
                            }
                        })
                    } else {
                        // 过滤没有的分区数据
                        const filterResult = oldIdList.filter(id => !idList.includes(id));
                        baseData.oldPartitionSpecialParametersList[oIndex] = oItem.filter(fItem => !filterResult.includes(fItem.partitionId))
                    }
                }
            })
            // 特殊参数数据 ==> 按顺序判断是否是相同分区编号
            const newsPartitionSpecialParametersList: PartitionSpecialParametersList[] = []
            baseData.oldPartitionSpecialParametersList.map(item => {
                if (isArrayLength(item)) {
                    const fristItem = item[0]
                    idList.forEach((iId, index) => {
                        const currentItem = item[index] as PartitionSpecialParametersList
                        if (currentItem) {
                            idList.includes(currentItem.partitionId) ?
                            newsPartitionSpecialParametersList.push(currentItem) :
                            newsPartitionSpecialParametersList.splice(index, 0, {
                                feeItemId: fristItem.feeItemId,
                                specialParametersId: fristItem.specialParametersId,
                                partitionId: iId,
                                setValue: 0,
                            })
                        } else {
                            newsPartitionSpecialParametersList.push({
                                feeItemId: fristItem.feeItemId,
                                specialParametersId: fristItem.specialParametersId,
                                partitionId: iId,
                                setValue: 0,
                            })
                        }
                    })
                }
            })
            customerFeeSetParams.partitionSpecialParametersList = newsPartitionSpecialParametersList
        }
    }

    // 显示动态表头数据
    const displayZoningTableHead = (Zoningdata: PartitionList[]) => {
        feesetSetingDetailTable.columns = []
        // 分区数据
        customerFeeSetParams.partitionList = Zoningdata
        const { columns, headNum: headnum } = initDynamicMeterHead(Zoningdata)
        feesetSetingDetailTable.columns = columns
        baseData.headNum = headnum
        // 初始化分区费用值
        isArrayLength(feesetSetingDetailTable.dataSource) && feesetSetingDetailFilterEmpty(feesetSetingDetailTable.dataSource, columnsDynamicMeterHead)
        xFeesetSetingDetailTableRef.value?.refreshColumn()
        // console.log(Zoningdata, ":保存分区信息", columns, ":合并表格表头");
        initPartitionSpecialParametersList()
    }
    // 保存分区信息
    const hanleSaveZoning = (Zoningdata: PartitionList[]) => {
        try {
            displayZoningTableHead(Zoningdata)
        } catch (error) {
            report(error)
        }
    }

    // 保存费用明细数据
    const hanleSaveFeesetSetingTable = async () => {
        try {
            // 更新全部费用明细数据
            hanleChangeFeeItem(cloneDeep(baseData.feeItemRow), unref(feeItemLists))
            // 要排除以分区为键的编号
            const partitionExcludeKeys = customerFeeSetParams.partitionList && customerFeeSetParams.partitionList.map(item => item.id)
            const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
            // 过滤费用明细（起始重量、结束重量、计量单位、算法）都为空
            const feesetSetingDetailFilter = feesetSetingDetailFilterEmpty(feesetSetingDetailTable.dataSource, columnsDynamicMeterHead)
            for (const details of feesetSetingDetailFilter) {
                // 去重
                if (!allFeeItemComputeDetails.some(item => item.id === details.id)) {
                    allFeeItemComputeDetails.push({ ...details, packageType: baseData.packageType });
                }
            }
            const targetDetailsList = dealHeaderDetailsListDataTrget(allFeeItemComputeDetails, partitionExcludeKeys as string[])
            console.log(targetDetailsList, ":获取处理费用明细表格数据");
            customerFeeSetParams.feeItemComputeDetailsList = targetDetailsList
        } catch (error) {
            report(error)
        }
    }

    // 保存特殊参数数据
    const hanleSaveSpecialParameter = (parametersList: PartitionSpecialParametersList[]) => {
        customerFeeSetParams.partitionSpecialParametersList = parametersList
        baseData.oldPartitionSpecialParametersList = dealPartitionListResult(parametersList, baseData.headNum)
    }

    // 选择的分区操作
    const changeZoningAction = (val: number) => {
        const partitionList = cloneDeep(customerFeeSetParams.partitionList)
        switch (val) {
            case BaseZoningAction.ZONING_SETING:
                // 分区设置
                unref(zoningActionsRef)?.show(unref(portInfoList), partitionList, undefined);
                break;
            case BaseZoningAction.ZONING_VIEW:
                // 分区查看
                unref(zoningActionsRef)?.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: PartitionSpecialParametersList[] = cloneDeep(customerFeeSetParams.partitionSpecialParametersList)
                const tableList = dealOriginalSpecialParameters(partitionSpecialParametersList, baseData.headNum)
                specialParameterRef.value?.show(tableList)
                break;
            default:
                createMessage.error('错误类型！')
                break;
        }
    }

    // 一票多件弹框
    const hanleOpenOneVote = () => {
        const data = cloneDeep(unref(customerFeeSetParams.feeBasicData))
        mpsdataRef.value?.show(data)
    }

    // 保存一票多件计算信息
    const hanleSaveMpsData = (mpsData: MpsData) => {
        const data = cloneDeep(mpsData)
        console.log(data, ":保存一票多件计算信息");
        customerFeeSetParams.feeBasicData.mpsData = data
    }

    // 计量单位
    const originalCalculateUnit = computed(() => {
        const calculateUnitList = storeDropDownData.getCalculateUnitList
        const calculateUnit = calculateUnitList.find(item => item.label === "公斤")
        return calculateUnit
    })
    /**
     * 费用设置-添加表格数据
     */
    const hanleFeesetTableAdd = async () => {
        const $table = ruleFormFeesetSetingTableRef.value
        Promise.all([$table?.validate(true)])
            .then(async (results) => {
                // 校验的全部状态
                const isValidate = await fee_deal_FilterValidate(results)
                if (!isValidate) return
                // 校验费用设置、费用明细
                hanleChangeFeeItem(cloneDeep(baseData.feeItemRow), unref(feeItemLists))
                feesetSetingTable.data?.push({
                    countModel: {},
                    countCalculateUnit: CalculateUnit.COUNT_CALCULATE_UNIT,
                    originalCalculateUnit: unref(originalCalculateUnit)?.value//计量单位
                })
                baseData.feeItemRow = {}
                feesetSetingDetailTable.dataSource = []
            }).catch((error) => console.error(error))
    }
    /**
     * 费用明细-添加表格数据
     */
    const hanleFeesetDetailsTableAdd = async () => {
        const isValidate = await isPackageType()
        if (!isValidate) return
        // 包裹类型
        /**
         * feeItemId: 费用（科目）编号
         * feeItemSpecialFlag: 费用特殊计费标志
         * packageType: 包装类型
         * feeItemName: 费用名称
         * originalCalculateUnit: 计量单位
         */
        const feeItem = baseData.feeItemRow
        feesetSetingDetailTable.dataSource.push({
            id: uuidv4(),
            countModel: feeItem.countModel ? cloneDeep(feeItem.countModel) : {},
            feeItemId: feeItem.id,
            feeItemSpecialFlag: feeItem.feeItemSpecialFlag,
            feeItemName: feeItem.itemName,
            originalCalculateUnit: unref(originalCalculateUnit)?.value
        })
    }
    // 判断费用类型以及包裹类型不能为空
    const isPackageType = async () => {
        const feeItem = baseData.feeItemRow
        const isPackageType = isNonNegativeInteger(baseData.packageType)
        const isFeeItemId = isNonNegativeInteger(feeItem.id)
        if (!isPackageType) {
            createMessage.warning('请选择包装类型！')
        }
        if (!isFeeItemId) {
            createMessage.warning('请选择费用类型！')
        }
        return isPackageType && isFeeItemId
    }

    /**
     * 费用设置-表格数据删除
     */
    const hanleFeesetTableDelete = (data: Recordable) => {
        // debugger
        const index = data.rowIndex;//vxe-table的index
        // const index = data.$index;
        const dataSource = feesetSetingTable.data
        if (dataSource && dataSource.length - 1 !== index) {
            ElMessage({
                message: '不是最后一条不能删除！',
                type: 'warning'
            })
        } else {
            // 删除并且过滤费用明细数据
            dataSource?.pop()
            const feeItemId = data.row.feeItemId
            // 更新选中对比费用值
            const deleteIndex = getUpdatefeeItemIdIndex(customerFeeSetParams.feeBasicData.feeItemIdList, feeItemId)
            isArrayLength(customerFeeSetParams.feeBasicData.feeItemIdList) && deleteIndex > 0 ? 
                customerFeeSetParams.feeBasicData.feeItemIdList.splice(deleteIndex, 1) : 
                customerFeeSetParams.feeBasicData.feeItemIdList = []
            // 更新所有的费用明细数据
            if (isNonNegativeInteger(feeItemId)) allFeeItemComputeDetailsList.value = unref(allFeeItemComputeDetailsList).filter(item => item.feeItemId !== feeItemId)
            if (dataSource && isArrayLength(dataSource)) {
                // 显示费用设置最后一条数据内容
                hanleChangeFeeItem(dataSource[dataSource.length - 1], unref(feeItemLists))
                return false
            }
            // 清空当前费用明细表格数据
            feesetSetingDetailTable.dataSource = []
            baseData.feeItemRow = {}
        }
    }
    /**
     * 费用明细-表格数据删除
     */
    const hanleFeesetDetailsTableDelete = (data: Recordable) => {
        const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
        const index = data.rowIndex
        // const index = data.$index
        // 删除当前费用明细表格数据
        feesetSetingDetailTable.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 hanleSaveFormula = (choiceList: EexpenseType) => {
        // console.log(choiceList, ":choiceList");
    }
    // 算法-下拉框
    let timerCalculator
    const hanleBlurCalculator = (row: Recordable) => {
        clearTimeout(timerCalculator)
        // console.log(row, "<==row", row.countModel.countType, BaseFormula.FORMULA, isChange);
        // 按照公式value显示公式弹框
        timerCalculator = setTimeout(() => {
            if (row.countModel.countType === BaseFormula.FORMULA) {
                formulaModle.value?.show(unref(parametersList), row)
            } else {
                // 如果是其它类型清空公式
                row.countModel.formula = undefined
                row.countModel.formulaExplain = undefined
            }
        }, 100);
    }

    // 费用设置-费用类型
    const hanleChangeFeeItem = async (row: Recordable, list: Recordable[]) => {
        try {
            // 找到对应费用类型
            const findData = list.find(item => item.id === row.feeItemId)
            if (findData) {
                // 关联费用明细的费用类型
                baseData.feeItemRow = { 
                    ...findData, 
                    feeItemId: row.feeItemId, 
                    countModel: row.countModel 
                } as Recordable
                // 向行数据添加费用类型名称、特殊参数
                Object.assign(row, { feeItemSpecialFlag: findData?.feeItemSpecialFlag, feeItemName: findData?.itemName })
            }
            // 费用设置 ==》 关联费用明细设置
            const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
            // 过滤费用明细（起始重量、结束重量、计量单位、算法）都为空
            // debugger
            const feesetSetingDetailFilter = feesetSetingDetailFilterEmpty(feesetSetingDetailTable.dataSource, columnsDynamicMeterHead)
            for (const details of feesetSetingDetailFilter) {
                // 去重
                if (!allFeeItemComputeDetails.some(item => item.id === details.id)) {
                    allFeeItemComputeDetails.push({ ...details, packageType: baseData.packageType });
                }
            }
            // 先清空表格数据再赋值
            feesetSetingDetailTable.dataSource = []
            // 包装类型
            baseData.packageType = 0
            if (allFeeItemComputeDetails.length > 0) {
                //根据费用类型过滤数据显示
                currentFilterFeeItemData(allFeeItemComputeDetails, row.feeItemId)
                // feesetSetingDetailTable.dataSource = allFeeItemData
            }
            updateRuleFormFeeBasicData()
            // console.log(allFeeItemComputeDetails, "全部费用明细数据");
        } catch (error) {
            report(error)
        }
    }
    // 更新首重与续重的校验
    const weightListAction = new Map([
        ['首重', { firstWeight: [{ required: true, message: '首重重量', trigger: ['change', 'blur'] }] }],
        ['续重', { continuousWeight: [{ required: true, message: '续重重量', trigger: ['change', 'blur'] }] }]
    ])
    // 时效更新首重、续重的校验
    const updateRuleFormFeeBasicData = () => {
        // 重置校验
        ruleFormFeeBasicData.firstWeight = [{ required: false }]
        ruleFormFeeBasicData.continuousWeight = [{ required: false }]
        nextTick(() => {
            clearValidateForm(ruleFormFeeBasicDataRef.value)
            const weightList = ['首重', '续重']
            if (feesetSetingTable.data) {
                for (const item of feesetSetingTable.data) {
                    if (weightList.includes(item.feeItemName)) {
                        // 添加校验
                        const obj = weightListAction.get(item.feeItemName)
                        Object.assign(ruleFormFeeBasicData, { ...obj })
                    }
                }
            }
        })
    }

    // 加载分区模版数据
    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 === customerFeeSetParams.feeId)
            // 全部费用明细数据
            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)
                    }
                })
                // console.log(customerFeeSetParams.partitionSpecialParametersList, ":《===分区特殊参数");
            } else {
                // 以键分区编号设置为0
                const zoningInitData = zoningToInitObject(partitionListUuid)
                allFeeItemComputeDetails.map(details => {
                    if (details) {
                        // 添加新的分区编号
                        Object.assign(details, zoningInitData)
                    }
                })
                // 清除分区特殊参数设置
                customerFeeSetParams.partitionSpecialParametersList = []
            }
            console.log(allFeeItemComputeDetails, ":allFeeItemComputeDetails === 全部费用明细数据");
        } catch (error) {
            report(error)
        }
    }

    // 改变原有的费用明细的费用类型
    const changeOnFeeItemList = (row: Recordable) => {
        if (!row.oldFees && !isNumber(row.oldFees.feeItemId)) return
        // 查找最新的费用类型信息
        const findData = feeItemLists.value.find(item => item.id === row.feeItemId) as Recordable
        // 改变当前行费用设置费用信息
        baseData.feeItemRow = { ...findData, feeItemId: row.feeItemId }
        Object.assign(row, { feeItemSpecialFlag: findData?.feeItemSpecialFlag, feeItemName: findData?.itemName })
        // 全部费用明细数据
        const allFeeItemComputeDetails = unref(allFeeItemComputeDetailsList)
        allFeeItemComputeDetails.map(item => {
            // 改变对应的费用类型信息
            if (item.feeItemId === row.oldFees.feeItemId) {
                item.feeItemId = findData.id
                item.feeItemName = findData.itemName
                item.feeItemSpecialFlag = findData.feeItemSpecialFlag
            }
        })
        updateRuleFormFeeBasicData()
        // console.log(allFeeItemComputeDetails, ":改变原有的费用明细的费用类型", row);
    }

    // 点击费用类型下拉框 ==> 费用明细数据
    const hanleRowDblclick = (visible: boolean, row: Recordable) => {
        // 保存旧的费用设置信息
        if (visible) {
            hanleChangeFeeItem(row, unref(feeItemLists))
            // 删除旧的费用设置数据再更新
            if (row.oldFees) delete row.oldFees
            row.oldFees = cloneDeep(row)
        } else {
            changeOnFeeItemList(row)
        }
    }
    // 点击费用设置表格单元格
    const hanleCellClick = (scope) => {
        const $table = ruleFormFeesetSetingTableRef.value
        if (!$table) return
        const isEditByRow = $table.isEditByRow(scope.row)
        if (isEditByRow) return
        hanleChangeFeeItem(scope.row, unref(feeItemLists))
    }

    // 快速导入费用
    const hanleExportExpense = () => {
        exportExpenseRef.value?.show()
    }
    const hanleSaveExpense = (detailList: Recordable[]) => {
        if (!isArrayLength(detailList)) return
        // 快速导入的费用id
        const expenseFeeItemId = detailList[0].feeItemId
        // 按照当前费用id过滤现有的费用明细数据
        const filterAllFeeItemComputeDetailsList = allFeeItemComputeDetailsList.value.filter(item => item.feeItemId !== expenseFeeItemId)
        const allFeeItemComputeDetails = cloneDeep(filterAllFeeItemComputeDetailsList)
        debugger
        // 保存到全部费用明细中
        allFeeItemComputeDetailsList.value = detailList.reduce((acc, curr) => {
            if (acc) acc.push({ ...curr, packageType: baseData.packageType });
            return acc;
        }, allFeeItemComputeDetails);
        const allFeeItemComputeDetailsList_ = unref(allFeeItemComputeDetailsList)
        // 先清空表格数据再赋值
        feesetSetingDetailTable.dataSource = []
        if (allFeeItemComputeDetailsList_.length > 0) {
            //根据费用类型过滤数据显示
            currentFilterFeeItemData(allFeeItemComputeDetailsList_, baseData.feeItemRow.id)
        }
    }

    // 清空表格数据
    const clearClose = async () => {
        // 加载的模版编号设置为空
        zoningstore.addLoadId("")
        // 设置费用编号为空
        zoningstore.feeId = ""
        // 清空费用基础信息
        clearValidateForm(ruleFormFeeBasicDataRef.value)
        resetForm(ruleFormFeeBasicDataRef.value)
        // 清除动态表格校验
        // clearValidateForm(ruleFormFeesetSetingTableRef.value)
        // clearValidateForm(ruleFormFeesetSetingDetailTableRef.value)
        // 一票多件计算信息
        // customerFeeSetParams.feeBasicData.mpsData = {} as MpsData
        customerFeeSetParams.feeBasicData = { mpsData: {} as MpsData, currencyCode: "CNY" } as FeeBasicDataDto
        // 费用设置
        customerFeeSetParams.feeItemComputeList = []
        // 费用明细
        customerFeeSetParams.feeItemComputeDetailsList = []
        // 分区
        customerFeeSetParams.partitionList = []
        // 特殊参数
        customerFeeSetParams.partitionSpecialParametersList = []
        // 费用设置表格
        feesetSetingTable.data = []
        // 费用明细表格
        feesetSetingDetailTable.dataSource = []
        // 清空费用明细数据
        allFeeItemComputeDetailsList.value = []
        // 恢复费用明细表头
        feesetSetingDetailTable.columns = cloneColumns
        // 包装类型
        baseData.packageType = 0
        // 分区操作
        baseData.zoningType = ''
        // 分区数量
        baseData.headNum = 0
        // 关联费用明细：费用类型
        baseData.feeItemRow = {}
        baseData.actionsType = BaseFeesetAction.FEESET_SETING
        // 计抛系数
        baseData.remoteFlagIndex = 0
        baseData.remoteFlag = 0
        baseData.weightRateModelList = weightRateModelList
        baseData.oldPartitionSpecialParametersList = []
        setLoading(false)
        clearTimeout(timerCalculator)
        // resetMore()
        onClose()
    }

    // TODO 查看分区：带不同参数显示
    // TODO 费用设置：选择费用类型 ==》 费用明细设置中费用类型：显示 ==》 费用明细设置只显示与（费用设置：选择费用类型）关联的数据

    return {
        hanleFeesetTableDelete,
        hanleFeesetTableAdd,
        hanleFeesetDetailsTableAdd,
        hanleFeesetDetailsTableDelete,
        changeZoningAction,
        hanleOpenOneVote,
        hanleSaveFormula,
        hanleBlurCalculator,
        hanleSaveZoning,
        hanleSaveMpsData,
        hanleChangeFeeItem,
        hanleSaveSpecialParameter,
        hanleSaveLoadPartition,
        hanleRowDblclick,
        hanleChangeCountTypeList,
        hanleExportExpense,
        hanleSaveExpense,
        hanleInitRefresh,
        hanleCellClick,
        show,
        clearClose,
        hanleChangePackageType,
        confirm,
        baseData,
        ruleFormFeeBasicDataRef,
        specialParameterRef,
        zoningActionsRef,
        mpsdataRef,
        ruleFormFeesetSetingTableRef,
        ruleFormFeesetSetingDetailTableRef,
        xFeesetSetingDetailTableRef,
        zoningExportTemplateRef,
        zoningLoadTemplateRef,
        exportExpenseRef,
        formulaModle,
        columnsDynamicMeterHead,
        feeItemLists,
        newFeeItemList,
        oldFeeItemList,
        filterOnFeeItemList,
        countTypeList,
        packageTypeList,
        specialParametersList,
        customerFeeSetParams,
        feeItemGetTypeList,
        isActionsType,
        originalCalculateUnit,
        currencyList,
        compareTypeList,
        remoteSurveyTypeList,
        changeRemoteFlag
    }
}