import { ActionOptions } from '@/components/DropDownButtons/type';
import type { BasicTableProps } from '@/components/VxeTable';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useQueryList } from '@/hooks/useQueryList';
import timeFiltering from '@/utils/timeFiltering';
import { ref, reactive, unref, computed, onMounted } from 'vue';
import { Tickets, Document } from "@element-plus/icons-vue";
import { cloneDeep } from '@/utils/cloneDeep';
import { useFeesetList } from '@/store/list_feeset';
import { useDropDownData } from '@/hooks/useDropDownData';
import { FeeSetTypeListType } from '@/type/BaseLading';
import { useStateFinancialType } from '@/store/list_financial';
import { LadingBillMoneyDetailParam, LadingBillMoneyPageParam, OrderReCountFeeDto, OrderReCountFeeParam } from '@/api/lading/ladingModle';
import { resCodeSuccess, useReturnData } from '@/utils/useReturnData';
import { api_ladingBillMoneyDetailList, api_ladingBillMoneyPageList, api_orderReCountFee } from '@/api/lading/lading';

enum LadingBillMoneyActions {
    /**
     * 重算
     */
    RECOMPUTE = 1,
    /**
     * 明细
     */
    DETAILS = 2
}
enum OrderReCountFeeText {
    FEE_ITEM_CATEGORY_NAME = '尾程',
    FEE_SET_TYPE_NAME = '应付'
}
const { resData } = useReturnData()
/**
 * 提单费用基础数据
 * @returns 
 */
function useLadingBillMoney(ladingBillMoneyOptions: BasicTableProps, actionOptions: ActionOptions[]) {
    // 基础数据
    const ladingBillMoneyListState = reactive({
        loading: false,//加载
        disabledArr: [] as number[],//按钮组禁止
        actionOptions: [] as ActionOptions[],
        waybillNumbers: new Map()
    })
    const getActionOptions = computed(() => ladingBillMoneyListState.actionOptions)
    // 查询参数
    const ladingBillMoneyParams = reactive<LadingBillMoneyPageParam>({
        feeItemCategory: undefined,
        feeSetType: undefined,
        billCodeType: undefined,
        waybillNumber: undefined,
        showFinal: 1,
        pageNum: 1,
        pageSize: 10,
        total: 10
    })
    // ref
    const ladingBillMoneyFormRef = ref()
    // 提单费用列表明细
    const ladingBillMoneyDetailListRef = ref<{ show: Fn }>()
    // 尾程重算
    const courseReturnRef = ref<{ show: Fn }>()
    const storeFeesetList = useFeesetList()
    const storeFinancialType = useStateFinancialType()
    const { storeDropDownData, feeSetTypeList } = useDropDownData()
    const selectfeeSetTypeList = computed(() => {
        return unref(feeSetTypeList).filter((item) => {
            return item.value === FeeSetTypeListType.SETTLEMENT || //结算价
                item.value === FeeSetTypeListType.CUSTOMER || //客户价
                item.value === FeeSetTypeListType.PAYABLE //应付
        })
    })
    onMounted(() => {
        storeDropDownData.addFeeSetTypeList()
        storeFeesetList.addFeeItemCategoryList()
        storeFinancialType.addBillCodeTypeList()
    })
    // 初始化数据
    const initList = async () => {
        ladingBillMoneyListState.loading = true
        try {
            const res = await api_ladingBillMoneyPageList(listParams)
            if (resCodeSuccess(res)) {
                ladingBillMoneyOptions.data = res.data.records
                ladingBillMoneyParams.total = res.data.total
                ladingBillMoneyListState.loading = false
            }
        } catch (error) {
            ladingBillMoneyListState.loading = false
        }
    }
    // 重算
    const hanleTailRecalculation = () => {
        const dataArr: OrderReCountFeeDto[] = []
        for (const list of ladingBillMoneyListState.waybillNumbers.entries()) {
            if (list.length === 2) {
                dataArr.push({ ladingId: list[0], orderIdList: list[1] })
            }
        }
        unref(courseReturnRef)?.show(dataArr)
    }
    const hanleSaveReturn = async (params: OrderReCountFeeParam, onclose: Fn, setLoading: Fn) => {
        try {
            setLoading(true)
            const res = await api_orderReCountFee(params)
            const resCode = resData(res, "操作成功")
            if (resCode !== 500) onclose()
        } finally {
            setLoading(false)
        }
    }
    // 明细
    const hanleViewDetail = async (row) => {
        const params: LadingBillMoneyDetailParam = {
            mainId: row.mainId,
            billMoneyId: row.id
        }
        const res = await api_ladingBillMoneyDetailList(params)
        if (resCodeSuccess(res)) {
            unref(ladingBillMoneyDetailListRef)?.show(res.data)
        }
    }
    // 校验表单
    const { resetForm } = useEleFormValidate();
    const resetParams = () => {
        resetForm(unref(ladingBillMoneyFormRef))
    }
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<LadingBillMoneyPageParam>(initList, resetParams, ladingBillMoneyParams)
    // 操作按钮组
    const handleClickChange = (row) => {
        const data = cloneDeep(row)
        switch (data.types) {
            case LadingBillMoneyActions.RECOMPUTE:
                const orderIds = data.orderId ? [data.orderId] : []
                const orderReCountFeeDto = {
                    ladingId: data.waybillNumber,
                    orderIdList: orderIds,
                }
                unref(courseReturnRef)?.show([orderReCountFeeDto])
                break;
            case LadingBillMoneyActions.DETAILS:
                hanleViewDetail(data)
                break;
            default:
                break;
        }
    }
    // 下拉按钮显示事件
    const changeVisibleChange = (val, row) => {
        if (!val) return
        // 是否激活状态
        const returnBtn = row.feeItemCategoryName === OrderReCountFeeText.FEE_ITEM_CATEGORY_NAME
            && row.feeSetTypeName === OrderReCountFeeText.FEE_SET_TYPE_NAME ?
            LadingBillMoneyActions.RECOMPUTE : -1;
        const index = actionOptions.findIndex((item) => item.value === returnBtn)
        if (index === -1) {
            ladingBillMoneyListState.actionOptions = actionOptions.filter((item) => item.value !== LadingBillMoneyActions.RECOMPUTE)
        } else {
            ladingBillMoneyListState.actionOptions = actionOptions
        }
    }
    // 选中复选框
    const handleSelectionChange = ({ records }) => {
        ladingBillMoneyListState.waybillNumbers.clear()
        for (const item of records) {
            if (
                item.feeItemCategoryName === OrderReCountFeeText.FEE_ITEM_CATEGORY_NAME &&
                item.feeSetTypeName === OrderReCountFeeText.FEE_SET_TYPE_NAME
            ) {
                if (ladingBillMoneyListState.waybillNumbers.has(item.waybillNumber)) {
                    const orderIds = ladingBillMoneyListState.waybillNumbers.get(item.waybillNumber)
                    item.orderId && orderIds.push(item.orderId)
                    ladingBillMoneyListState.waybillNumbers.set(item.waybillNumber, orderIds)
                } else {
                    const orderIds = item.orderId ? [item.orderId] : []
                    ladingBillMoneyListState.waybillNumbers.set(item.waybillNumber, orderIds)
                }
            }
        }
    }

    return {
        ladingBillMoneyParams,
        ladingBillMoneyListState,
        ladingBillMoneyFormRef,
        ladingBillMoneyDetailListRef,
        courseReturnRef,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        handleClickChange,
        changeVisibleChange,
        hanleSaveReturn,
        handleSelectionChange,
        hanleTailRecalculation,
        selectfeeSetTypeList,
        storeFeesetList,
        storeFinancialType,
        getActionOptions,
    }
}

/**
 * 提单费用表格配置
 */
function useFinancialBillListModel() {
    const ladingBillMoneyListOptions = reactive<BasicTableProps>({
        id: 'ladingbill_moneylist_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        height: 520,
        loading: false,
        stripe: true,
        rowConfig: { isHover: true, keyField: 'id' },
        columnConfig: { resizable: true },
        toolbarConfig: { custom: true },
        columns: [
            { type: "checkbox", width: 45 },
            { field: 'waybillNumber', title: '提单号', minWidth: 110 },
            { field: 'orderId', title: '订单号 ', minWidth: 110 },
            { field: 'trackingId', title: '尾程单号', minWidth: 110 },
            { field: 'bookingNumber', title: ' 订舱号', minWidth: 110 },
            { field: 'feeItemCategoryName', title: '费项类型', minWidth: 110 },
            { field: 'providerName', title: '供应商', minWidth: 110 },
            { field: 'productName', title: '产品名称', minWidth: 110 },
            { field: 'feeSetTypeName', title: '结算类型', minWidth: 110 },
            { field: 'feeWeight', title: '计费重量', minWidth: 100 },
            { field: 'fee', title: '金额', minWidth: 90 },
            { field: 'formulaDescription', title: '公式描述', minWidth: 120 },
            {
                field: 'createTime',
                title: '计算时间',
                minWidth: 110,
                formatter: ({ row }) => {
                    return timeFiltering(row.createTime)
                }
            },
            { title: '操作', slots: { default: 'actions' }, width: 135, fixed: 'right' }
        ],
        data: []
    })

    // 操作类别
    const ladingBillMoneyListActionOptions: ActionOptions[] = [
        {
            value: LadingBillMoneyActions.RECOMPUTE,
            label: "尾程重算",
            type: "success",
            icon: Document,
            permissions: ['sys:ladingBillMoney:save']
        },
        {
            value: LadingBillMoneyActions.DETAILS,
            label: "明细",
            type: "primary",
            icon: Tickets,
            permissions: ['sys:ladingBillFeeSet:edit'],
        },
    ]

    return {
        ladingBillMoneyListOptions,
        ladingBillMoneyListActionOptions
    }
}

export {
    useLadingBillMoney,
    useFinancialBillListModel,
}