import { FeeBasicDataDto } from '@/api/customerfee/CustomerFeeSetModel';
import { BaseTableProps, TableActionType } from '@/components/Table/src/types';
import { EditType, Title } from '@/type/BaseEnum';
import { cloneDeep } from '@/utils/cloneDeep';
import { ref, Ref, unref, reactive, computed, nextTick } from 'vue';
import { dealStrCalculatorData } from '@/utils/dealData';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useMessage } from '@/hooks/useMessage';
import { isArrayLength, isNumber, isString } from '@/utils/is';
import { clearData } from '@/utils/clearData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { ListIitem } from '@/api/base/BaseDataModel';
import { MpsCountExpressions } from '@/api/feecommon/mpsCountExpressionsModel';

/**
 * 费用计算公式
 * @param tableObj 表格数据
 * @param choiceList 显示的计算公式
 * @param generatingFormula 计算公式
 * @param methodsTable 列表表格事件
 * @param calculatorData 计算符号的参数数据
 * @returns 
 */

const { createMessage } = useMessage()

export default function useBusinessFeesetRote(onClose: Function, onShow: Function, emit, tableObj: BaseTableProps, choiceList: Ref, generatingFormula, methodsTable: TableActionType, calculatorData: Recordable) {
    // 费用设置基础表单数据
    const calculatorParams = reactive({
        mpsWeightCountType: "",//重量计算方式
        mpsWeightRound: "",//单件取整
        mpsTotalWeightRound: "",//总重取整
        guaranteeWeight: "",//保底重
        mpsMaxWeight: "",//单件最大重
        pickValueType: 0,//取整类型
        isNotCountVolume: false,//计抛
        unitType: "",//单位类型
        orderNumber: 1,//序号
        unitTypeList: [],//排它单位类型
        mpsCountFeeType: 0,// 一票多件计费方式
    })
    // 下拉列表数据
    const { unitTypeParamList } = useDropDownData()
    const { validateFieldForm } = useEleFormValidate()
    // 生成或编辑状态
    const stateExpenseFormula = reactive({
        editState: {} as Recordable,
        generatStatus: '0'
    })
    const validateFieldRef = ref()
    const { unitTypeIntegerList, mpsParametersList } = useDropDownData()
    // 显示
    const show = (feeBasicData: FeeBasicDataDto) => {
        // 清空当前计算公式
        clearEditState()
        if (isArrayLength(unitTypeParamList.value)) {
            calculatorData.EexpenseOne = unitTypeParamList.value.map(item => ({ key: `{${item.value}}`, value: item.label, active: false }))
        }
        onShow()
        nextTick(() => {
            // Object.assign(calculatorParams, { ...feeBasicData.mpsData })
            feeBasicData.mpsData && Object.keys(feeBasicData.mpsData).forEach((key) => {
                if(feeBasicData.mpsData[key] !== null) {
                    calculatorParams[key] = feeBasicData.mpsData[key]
                }
            })
            if (feeBasicData.mpsData && feeBasicData.mpsData.mpsCountExpressionsList) {
                tableObj.dataSource = orderNumberSort(feeBasicData.mpsData.mpsCountExpressionsList)
                methodsTable.setDataSource(feeBasicData.mpsData.mpsCountExpressionsList)
            }
            calculatorParams.orderNumber = tableObj.dataSource.length + 1
        })
    }

    // 按照序号排序
    const orderNumberSort = (mpsArr: MpsCountExpressions[]) => {
        if (!isArrayLength(mpsArr)) return []
        const sortArr = mpsArr.sort((a, b) => a.orderNumber - b.orderNumber)
        return sortArr
    }

    // 获取的数据 
    const confirm = async () => {
        const data = methodsTable.getDataSource();
        // 深拷贝
        const newData = cloneDeep(data);
        const mpsData = {
            mpsWeightCountType: calculatorParams.mpsWeightCountType,//重量计算方式
            mpsWeightRound: calculatorParams.mpsWeightRound,//单件重量
            mpsTotalWeightRound: calculatorParams.mpsTotalWeightRound,//总重
            guaranteeWeight: calculatorParams.guaranteeWeight,//保底重
            mpsMaxWeight: calculatorParams.mpsMaxWeight,//单件最大重
            pickValueType: calculatorParams.pickValueType,//取整类型
            isNotCountVolume: calculatorParams.isNotCountVolume,//计抛
            mpsCountFeeType: calculatorParams.mpsCountFeeType,//一票多件计费方式
            mpsCountExpressionsList: newData,
        }
        emit('saveMpsData', mpsData)
        clear()
        // 校验
    }

    // 重置
    const clear = () => {
        // 清空数据
        const data = clearData(calculatorParams)
        Object.assign(calculatorParams, data)
        tableObj.dataSource = []
        methodsTable.setDataSource([])
        clearEditState()
        onClose()
    }
    // 重置编辑公式状态
    const clearEditState = () => {
        choiceList.value = []
        stateExpenseFormula.editState = {}
        stateExpenseFormula.generatStatus = EditType.ADD;
        calculatorParams.unitTypeList = []
    }

    // 状态文字
    const generatStr = computed(() => {
        return stateExpenseFormula.generatStatus === EditType.ADD ? Title.ADD : Title.EDIT
    })

    // 生成公式数据
    const hanleGenerate = async () => {
        // 指定字段校验
        const isValidate = await validateFieldForm(validateFieldRef.value, ["unitType", "orderNumber"])
        if (!isValidate) return;
        // 公式数据
        const [formulaStr, formulaList] = generatingFormula();
        if (formulaList === 0) return createMessage.warning('请选择计算符号！')
        // 深拷贝
        const oldFormulaList = cloneDeep(formulaList)
        // oldFormulaList：符号数组类型 formulaExplain：公式说明
        const orderLength = tableObj.dataSource.length + 1
        // 公式的参数
        const dataParams = {
            formulaExplain: formulaStr,
            unitType: calculatorParams.unitType,
            orderNumber: calculatorParams.orderNumber,
            unitTypeList: calculatorParams.unitTypeList,
            formula: oldFormulaList.map(item => item.key).join(""),
        }
        switch (stateExpenseFormula.generatStatus) {
            case EditType.ADD:
                tableObj.dataSource.push(dataParams)
                calculatorParams.orderNumber = orderLength + 1
                break;
            case EditType.EDIT:
                Object.assign(stateExpenseFormula.editState, dataParams)
                calculatorParams.orderNumber = orderLength
                break;
            default:
                createMessage.error('状态出错！')
                break;
        }
        // 排序
        const sortArr = orderNumberSort(tableObj.dataSource as MpsCountExpressions[])
        methodsTable.setDataSource(sortArr)
        clearEditState()
    }

    // 编辑公式
    const hanleFormula = async (row: Recordable, calculatorData: Recordable) => {
        // 公式-编辑状态
        stateExpenseFormula.generatStatus = EditType.EDIT;
        calculatorData.mpsParametersList = unref(mpsParametersList).map(item => ({ key: `{${item.value}}`, value: item.label, active: false }))
        choiceList.value = dealStrCalculatorData(row, calculatorData)
        // console.log(row, ":公式-编辑状态", choiceList.value);
        stateExpenseFormula.editState = row
        // 赋值表单内容
        Object.assign(calculatorParams, { ...row })
    }

    // 删除
    const hanleDelete = (row: Recordable) => {
        const index = row.$index
        tableObj.dataSource.splice(index, 1)
        methodsTable.setDataSource(tableObj.dataSource)
        clearEditState()
    }

    // 处理单位类型显示
    const dealUnitType = (type: string) => {
        if (!isNumber(type) && !isString(type)) return ''
        const data = unitTypeIntegerList.value.find(item => item.value === type)
        return data?.label
    }
    // 显示排它单位类型名称
    const changeUnitTypeList = (valArr: number[], selectList: ListIitem[]) => {
        if (!isArrayLength(valArr)) return
        const filteredData = selectList.filter(obj => valArr.includes(Number(obj.value)));
        const labelArr = filteredData.map((item) => item.label)
        return labelArr.join(',')
    }

    return {
        hanleGenerate,
        hanleFormula,
        hanleDelete,
        dealUnitType,
        changeUnitTypeList,
        show,
        confirm,
        clear,
        generatStr,
        calculatorParams,
        validateFieldRef
    }
}