import { ActionOptions } from '@/components/DropDownButtons/type';
import type { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useFeesetList } from '@/store/list_feeset';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { validateCountType, validateFieldType } from '@/utils/feeSeting/validate';
import { Delete, Odometer } from "@element-plus/icons-vue";
import { isArrayLength, isNumber, isObject } from '@/utils/is';
import { ref, reactive, computed, onMounted, unref, watch } from 'vue';
import { BaseFormula } from '@/type/BaseFormula';
import { fee_deal_FilterValidate } from '@/utils/feeSeting/dealData';
import { getVxeGridData } from '../base/data';
import { TempFeeItemModelDto } from '@/api/receivable/receivableModel';
import { BillPayableDto, LadingPayableStableFeeItemModelDto } from '@/api/lading/ladingModle';
import { useTemplateStore } from '@/store/template';
import { api_costFeeSetProductIdList, api_getPayableModeData } from '@/api/lading/lading';
import { resCodeSuccess } from '@/utils/useReturnData';
import { CustomerFeeList } from '@/composables/lading/common/useFeeDateVersionList';
import { useVxeGridHanleHooks } from '@/components/VxeTable/hooks';
import { deal_FindItemName } from '@/utils/dealFindData';

// 临时、渠道商
type TableType = "temporary" | "providerId"
/**
 * 应付模版表格配置
 * @returns 
 */
function usePayableModelAddModel(isLading = false, props?: Recordable) {
    let timerCalculator
    // 临时费用设置 ref
    const xTemporaryFeeRef = ref<VxeGridInstance>()
    // 渠道商费用绑定 ref
    const xProviderIdFeeRef = ref<VxeGridInstance>()
    // 查看费用设置
    // const addEditProviderFeeSetRef = ref<{ show: Fn }>()
    // 公式计算
    const formulaModleRef = ref<{ show: Fn }>()
    const payableState = reactive({
        referencePayableModelId: "",//参考应付（应付）模板编号
        dateVersionList: [] as CustomerFeeList[],//包含客户与结算的日期版本
    })
    // 模版列表
    const templateStore = useTemplateStore()
    // 费用设置列表stroe
    const storeFeesetList = useFeesetList()
    const feeItemCategoryList = computed(() => storeFeesetList.getFeeItemCategoryList)
    const {
        storeDropDownData,
        costFeeItemList,
        deliverChannelList,
        currencyList,
        allProvidersList,
        specialFeeItemList,
    } = useDropDownData()
    // 算法列表
    const countTypeList = computed(() => {
        return storeDropDownData.getCountTypeList.filter(
            item => {
                return isNumber(item.value) && item.value === 0//重量
                    || isNumber(item.value) && item.value === 1//按件
                    || isNumber(item.value) && item.value === 2//按单
                    || isNumber(item.value) && item.value === 8//体积
                    || isNumber(item.value) && item.value === 9//重量
            }
        )
    })
    // 临时费用设置列表-配置
    const temporaryFeeOptions = reactive<BasicTableProps>({
        id: 'temporary_fee_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        // height: 220,
        loading: false,
        stripe: true,
        rowConfig: { isHover: true, keyField: 'table_id' },
        editConfig: { trigger: 'click', mode: 'row', autoClear: false, showIcon: false, showAsterisk: false },
        cellStyle: { height: '38px', padding: 0 },
        columnConfig: { resizable: true },
        editRules: {
            providerId: [{ message: '请选择服务商', validator: validateFieldType }],
            feeItemCategoryId: [{ message: '请选择费项类型', validator: validateFieldType }],
            feeItemId: [{ message: '请选择费用类型', validator: validateFieldType }],
            productId: [{ message: '请选择产品名称', validator: validateFieldType }],
            countModel: [{ message: '请选择算法', validator: validateCountType }],
            countOrderNumber: [{ required: true, message: '请输入计算优先级' }],
            // parameter: [{ message: '请输入参数', validator: validateFieldType }],
            offerPrice: [{ required: true, message: '请输入价格' }],
            // organizationOfferPrice: [{ message: '请输入结算价', validator: validateFieldType }],
            currencyCode: [{ message: '请选择币种', validator: validateFieldType }],
            shareType: [{ message: '请选择分摊方式', validator: validateFieldType }],
        },
        columns: [
            // { type: "seq", width: 45 },
            { field: 'providerId', title: '服务商', editRender: {}, slots: { default: 'default_providerId', edit: 'edit_providerId' }, minWidth: 120 },
            { field: 'feeItemCategoryId', title: '费项类型', editRender: {}, slots: { default: 'default_feeItemCategory', edit: 'edit_feeItemCategory' }, minWidth: 120 },
            { field: 'feeItemId', title: '费用类型', editRender: {}, slots: { default: 'default_feeItemId', edit: 'edit_feeItemId' }, minWidth: 120 },
            { field: 'productId', title: '产品名称', editRender: {}, slots: { default: 'default_productId', edit: 'edit_productId' }, minWidth: 120 },
            { field: 'countModel', title: '算法', editRender: {}, slots: { default: 'default_countModel', edit: 'edit_countModel' }, minWidth: 120 },
            { field: 'countOrderNumber', title: '计算优先级', editRender: {}, slots: { edit: 'edit_countOrderNumber' }, minWidth: 80 },
            { field: 'parameter', title: '参数', editRender: {}, slots: { edit: 'edit_parameter' }, minWidth: 80 },
            { field: 'offerPrice', title: '价格', editRender: {}, slots: { edit: 'edit_price' }, minWidth: 80 },
            // { field: 'organizationOfferPrice', title: '结算价', editRender: {}, slots: { edit: 'edit_discount' }, minWidth: 80 },
            { field: 'currencyCode', title: '币种', editRender: {}, slots: { default: 'default_currencyCode', edit: 'edit_currencyCode' }, minWidth: 100 },
            // { field: 'shareType', title: '分摊方式', editRender: {}, slots: { default: 'default_shareType', edit: 'edit_shareType' }, minWidth: 100 },
            { title: '操作', slots: { header: "header_actions", default: 'default_actions' }, align: "center", width: 60, fixed: 'right' }
        ],
        data: []
    })
    // 渠道商费用绑定
    const providerIdFeeOptions = reactive<BasicTableProps>({
        id: 'providerId_fee_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        // height: 220,
        loading: false,
        stripe: true,
        rowConfig: { isHover: true, keyField: 'table_id' },
        editConfig: { trigger: 'click', mode: 'row', autoClear: false, showIcon: false, showAsterisk: false },
        cellStyle: { height: '38px', padding: 0 },
        columnConfig: { resizable: true },
        editRules: {
            feeItemCategoryId: [{ message: '请选择费项类型', validator: validateFieldType }],
            productName: [{ message: '请选择产品名称', validator: validateFieldType }],
            dateVersion: [{ message: '请选择日期版本', validator: validateFieldType }],
        },
        columns: [
            { type: "seq", title: "序号", width: 65 },
            { field: 'feeItemCategoryId', title: '费项类型', editRender: {}, slots: { default: 'default_feeItemCategory', edit: 'edit_feeItemCategory' }, minWidth: 120 },
            { field: 'providerName', title: '服务商', minWidth: 120 },
            { field: 'productName', title: '产品名称', minWidth: 120, editRender: {}, slots: { edit: 'edit_productId' } },
            { title: '操作', slots: { default: 'default_actions' }, align: "center", width: 135, fixed: 'right' }
        ],
        data: []
    })
    onMounted(() => {
        templateStore.addPayableIdList()
        storeDropDownData.addFeeItemList()
        storeDropDownData.addDeliverChannelListApi()
        // 成本费用类型
        storeDropDownData.addCostFeeItemList()
        storeDropDownData.addCountTypeList()
        storeDropDownData.addCurrencyList()
        storeDropDownData.addParametersList()
        storeDropDownData.addAllProvidersList()
        if (isLading) {
            const columns = [
                { field: 'dateVersion', title: '日期版本', editRender: {}, slots: { edit: 'edit_dateVersion' }, minWidth: 120 },
                // { field: 'weightRatio', title: '计抛系数', editRender: {}, slots: { edit: 'edit_weightRatio' }, minWidth: 120 },
                {
                    field: 'specialFeeItemNameList',
                    title: '特殊费用类型',
                    editRender: {},
                    slots: { edit: 'edit_specialFeeItem' },
                    minWidth: 150,
                    formatter: ({ row }) => {
                        return isArrayLength(row.specialFeeItemNameList) ? row.specialFeeItemNameList.join(",") : ''
                    },
                },
            ]
            providerIdFeeOptions.columns = providerIdFeeOptions.columns?.concat(columns)
            const parameter = [{ message: '请输入参数', validator: validateFieldType }]
            if (temporaryFeeOptions.editRules) Object.assign(temporaryFeeOptions.editRules, { parameter })
        }
    })

    // vxe-grid操作事件
    const { updateStatus: updateStatusTemporary } = useVxeGridHanleHooks(xTemporaryFeeRef)//临时费用
    const { updateStatus: updateStatusProviderId } = useVxeGridHanleHooks(xProviderIdFeeRef)//渠道商
    // 初始化数据
    const initData = (data) => {
        // 临时费用设置
        if (isArrayLength(data.tempFeeItemModelList)) {
            temporaryFeeOptions.data = data.tempFeeItemModelList.map(item => {
                if (isNumber(item.feeItemCategoryId)) item.feeItemCategoryId = String(item.feeItemCategoryId)
                if (!item.countModel) item.countModel = { countType: undefined }
                return item
            })
        }
        if (isArrayLength(data.stableFeeItemModelList)) {
            // 稳定费用
            providerIdFeeOptions.data = data.stableFeeItemModelList.map((item) => {
                if (isNumber(item.feeItemCategoryId)) item.feeItemCategoryId = String(item.feeItemCategoryId)
                return item
            })
            initDateVersion(data.stableFeeItemModelList)
        }
    }
    // 加载
    const setLoading = (isLoad: boolean) => {
        temporaryFeeOptions.loading = isLoad
        providerIdFeeOptions.loading = isLoad
    }
    // 费用版本列表
    const initDateVersion = async (list: any[]) => {
        const parentIdList = list.map(item => item.feeSetParentId)
        if (parentIdList.length > 0) {
            const resGroup = await api_costFeeSetProductIdList({ parentIdList })
            if (resCodeSuccess(resGroup)) {
                payableState.dateVersionList = resGroup.data || []
            }
        }
    }
    const getDateVersionList = computed(() => payableState.dateVersionList)
    // 加载模版的数据
    const changePayableModeData = async (id: string) => {
        if (!id) return
        setLoading(true)
        const res = await api_getPayableModeData({ id })
        if (resCodeSuccess(res)) {
            const data = res.data
            initData(data)
        }
        setLoading(false)
    }
    // 按钮权限
    const providerIdActionOptions: ActionOptions[] = [
        {
            value: BaseFeesetAction.VIEW,
            label: "查看",
            color: "#01aee6",
            icon: Odometer,
            permissions: ['sys:receivableModel:add', 'sys:receivableModel:edit'],
        },
        {
            value: BaseFeesetAction.DELETE,
            label: "删除",
            type: "danger",
            icon: Delete,
            permissions: ['sys:receivableModel:add', 'sys:receivableModel:edit']
        },
    ]
    watch(
        () => props?.payableForm,
        (val: BillPayableDto) => {
            if (isObject(val)) {
                payableState.referencePayableModelId = val.referencePayableModelId
                initData(val)
            }
        }
    )
    // 重置表格数据
    const resetTable = () => {
        payableState.referencePayableModelId = ""
        temporaryFeeOptions.data = []
        providerIdFeeOptions.data = []
        clearEdit()
    }
    // 清空当前所有表格编辑状态
    const clearEdit = () => {
        unref(xTemporaryFeeRef)?.clearEdit()
        unref(xProviderIdFeeRef)?.clearEdit()
    }

    // 删除(临时、产品、结算)
    const deleteTable = (type: TableType, scope) => {
        clearEdit()
        const index = scope.rowIndex;
        switch (type) {
            case "temporary":
                temporaryFeeOptions.data && temporaryFeeOptions.data.splice(index, 1);
                break;
            case "providerId":
                providerIdFeeOptions.data && providerIdFeeOptions.data.splice(index, 1);
                break;
        }
    }

    // 新增(临时、渠道商)
    const addTable = (type: TableType) => {
        clearEdit()
        switch (type) {
            case "temporary":
                temporaryFeeOptions.data && temporaryFeeOptions.data.push({ countModel: {} });
                break;
            case "providerId":
                providerIdFeeOptions.data && providerIdFeeOptions.data.push({ countModel: {} });
                break;
        }
    }

    // 查找特殊费用类型名称
    const changeSpecialFeeItem = (valArr: number[], row) => {
        if (!isArrayLength(valArr)) return
        const filteredArray = unref(specialFeeItemList).filter(item => valArr.includes(Number(item.value)))
        row.specialFeeItemNameList = filteredArray.map(item => item.label)
    }
    // 根据费用日期版本更新费用编号
    const changeCustomerFee = (val: string, list: Recordable[], scope) => {
        updateStatusProviderId(scope)
        if (!val) return
        const findObj = list.find(item => item.value === val)
        scope.row.feeSetParentId = findObj?.parentId
    }
    // 算法下拉框
    const hanleBlurCalculator = (row: Recordable) => {
        clearTimeout(timerCalculator)
        // 按照公式value显示公式弹框
        timerCalculator = setTimeout(() => {
            if (row.countModel.countType === BaseFormula.FORMULA) {
                unref(formulaModleRef)?.show(unref(storeDropDownData.parametersList), row)
            } else {
                // 如果是其它类型清空公式
                row.countModel.formula = undefined
                row.countModel.formulaExplain = undefined
            }
        }, 100)
    }
    const hanleChangeAction = (scope) => {
        // 去除查看费用明细
        // BaseFeesetAction.VIEW === row.types ?
        //     unref(addEditProviderFeeSetRef)?.show(BaseFeesetAction.VIEW, { ...row, id: row.feeSetId })
        //     : deleteTable('providerId', scope)
        deleteTable('providerId', scope)
    }

    // 获取数据
    const getConfirmData = async () => {
        const results = await Promise.all([unref(xTemporaryFeeRef)?.validate(true), unref(xProviderIdFeeRef)?.validate(true)])
        // 校验的全部状态
        const isValidate = await fee_deal_FilterValidate(results)
        if (!isValidate) return isValidate
        const payableModelSetDto: BillPayableDto = {
            referencePayableModelId: payableState.referencePayableModelId,
            tempFeeItemModelList: [],
            stableFeeItemModelList: []
        }
        // 临时费用
        payableModelSetDto.tempFeeItemModelList = await getVxeGridData<TempFeeItemModelDto>(xTemporaryFeeRef)
        // 稳定费用
        payableModelSetDto.stableFeeItemModelList = await getVxeGridData<LadingPayableStableFeeItemModelDto>(xProviderIdFeeRef)
        clearEdit()
        return payableModelSetDto
    }

    return {
        temporaryFeeOptions,
        providerIdFeeOptions,
        providerIdActionOptions,
        xTemporaryFeeRef,
        xProviderIdFeeRef,
        formulaModleRef,
        payableState,
        getDateVersionList,
        resetTable,
        addTable,
        deleteTable,
        getConfirmData,
        hanleBlurCalculator,
        hanleChangeAction,
        changePayableModeData,
        changeSpecialFeeItem,
        changeCustomerFee,
        updateStatusTemporary,
        updateStatusProviderId,
        feeItemCategoryList,
        costFeeItemList,
        deliverChannelList,
        currencyList,
        countTypeList,
        allProvidersList,
        specialFeeItemList,
        templateStore,
    }
}

export {
    usePayableModelAddModel
}