import { ListIitem } from "@/api/base/BaseDataModel";
import { TableColumns } from "@/components/Table/src/types";
import type { BasicTableProps, VxeTableInstance } from "@/components/VxeTable";
import { useDealDynamicMeterHeadData } from "@/hooks/useDynamicMeterHead";
import useResizeHeight from "@/hooks/useResizeHeight";
import { FeeApprovalStatus, FeeNoticeShowType } from "@/type/BaseBusinessFeeseType";
import { cloneDeep } from "@/utils/cloneDeep";
import { formatDate } from "@/utils/dateTimeStr";
import { isArrayLength, isNonNegativeInteger, isNumber, isString } from "@/utils/is";
import { ref, reactive, computed, unref, nextTick, watch } from 'vue';

/**
 * 处理客户费用异常提示
 * @returns 
 */
function useFeeNoticeShow(onClose: Fn, onShow: Fn, setLoading: Fn, props: Recordable, emit: Fn) {
    const xCustomerFeeGridTableRef = ref<VxeTableInstance>()
    const feeNoticeShowState = reactive({
        infoDto: [
            { field: 'productName', title: '产品名称' },
            { field: 'feeSetName', title: '费用设置名称' },
            { field: 'feeSetTypeName', title: '费用类型' },
            { field: 'beginDate', title: '起始时间' },
            { field: 'endDate', title: '结束时间' },
        ],
        currentRow: {} as Recordable,
        versionValue: '',//结算价版本
        versionList: [] as ListIitem[],//结算价版本列表
        customerFeeIndex: 0
    })
    // vxe-gird-表格配置
    const abnormalGridOptions = reactive<BasicTableProps>({
        id: 'abnormal_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        // height: 300,
        loading: false,
        rowConfig: { isHover: true },
        columnConfig: { resizable: true },
        columns: [
            {
                type: "seq",
                width: 60,
                title: '序号',
                align: 'left'
            },
            {
                field: 'feeCompareResultName',
                title: '异常类型',
                width: 120,
                align: 'left'
            },
            {
                field: 'message',
                title: '提示信息',
                minWidth: 360,
                align: 'left'
            },
        ],
        data: []
    })
    const customerFeeGridOptionsOne = reactive<BasicTableProps>({
        id: 'abnormal_table',
        border: true,
        keepSource: true,
        showOverflow: true,
        // height: 300,
        loading: false,
        rowConfig: { isHover: true },
        columnConfig: { resizable: true },
        columns: [
            {
                type: "seq",
                width: 60,
                title: '序号',
                align: 'left'
            },
            {
                field: 'feeCompareResultName',
                title: '异常类型',
                width: 120,
                align: 'left'
            },
            {
                field: 'feeItemName',
                title: '费用名称',
                minWidth: 120,
                align: 'left'
            },
            {
                field: 'priceVariance',
                title: '价格差异',
                minWidth: 120,
                align: 'left'
            },
            {
                field: 'organizationOfferPrice',
                title: '结算价',
                minWidth: 120,
                align: 'left'
            },
            {
                field: 'discount',
                title: '折扣标准（%）',
                minWidth: 120,
                align: 'left'
            },
            {
                field: 'offerPrice',
                title: '客户价',
                minWidth: 120,
                align: 'left'
            },
            {
                field: 'message',
                title: '提示信息',
                minWidth: 260,
                align: 'left'
            },
        ],
        data: []
    })
    const partitionColumns: TableColumns[] = [
        {
            prop: 'feeCompareResultName',
            label: '异常类型',
            width: 100,
            slotName: "feeCompareResultName",
            align: 'left',
            fixed: "left"
        },
        {
            prop: 'feeItemName',
            label: '费用名称',
            width: 120,
            slotName: "feeItemName",
            align: 'left',
            fixed: "left"
        },
        {
            prop: "originalBeginWeight",
            label: "起始重量",
            width: 100,
            slotName: "originalBeginWeight",
            align: 'left',
            fixed: "left"
        },
        {
            prop: "originalEndWeight",
            label: "结束重量",
            width: 100,
            slotName: "originalEndWeight",
            align: 'left',
            fixed: "left"
        },
    ]
    const customerFeeGridOptionsTwo = reactive<BasicTableProps>({
        id: 'abnormal_table',
        border: true,
        keepSource: true,
        showOverflow: false,
        maxHeight: 900,
        loading: false,
        rowStyle: { height: '136px' },
        tooltipConfig: {
            showAll: true,
            enterable: true,
            contentMethod: ({ type, column, row, items, _columnIndex }) => {
                const { field } = column
                // 重写默认的提示内容
                if (field === 'originalBeginWeight' || field === 'originalEndWeight') {
                    return ''
                } else {
                    if (type === 'header') {
                        return ''
                    } else if (type === 'footer') {
                        return ''
                    }
                    return row[field] && row[field].message ? '提示信息：' + row[field].message : ''
                }
            }
        },
        rowConfig: { isHover: true },
        columnConfig: { resizable: true },
        columns: [],
        data: []
    })
    const { tableHeight } = useResizeHeight(0)
    watch(
        () => tableHeight.value,
        (val) => {
            val > 900 ? 
            customerFeeGridOptionsTwo.maxHeight = val - 90 : 
            customerFeeGridOptionsTwo.maxHeight = 820;
        }
    )

    // 单条客户费用比对结果
    const fristCustomerFeeSetCompare = computed(() => {
        if (isArrayLength(props.customerFeeSetCompareList)) {
            const cloneData = cloneDeep(props.customerFeeSetCompareList[feeNoticeShowState.customerFeeIndex])
            if (cloneData.beginDate) cloneData.beginDate = formatDate(new Date(cloneData.beginDate))
            if (cloneData.endDate) cloneData.endDate = formatDate(new Date(cloneData.endDate))
            return cloneData
        }
        return {}
    })
    // 多条
    const customerFeeSetCompareList = computed(() => {
        const list = props.customerFeeSetCompareList
        if (!isArrayLength(list)) return []
        return list[feeNoticeShowState.customerFeeIndex].customerFeeSetCompareDtoList
    })
    watch(
        () => props.customerFeeSetCompareList,
        (list: Recordable[]) => {
            if (isArrayLength(list)) {
                const oneFeeNotice = list[feeNoticeShowState.customerFeeIndex]
                const beginDateFeeNotice = formatDate(new Date(oneFeeNotice.beginDate))
                const endDateFeeNotice = formatDate(new Date(oneFeeNotice.endDate))
                feeNoticeShowState.versionValue = `${oneFeeNotice.productId}(${beginDateFeeNotice}/${endDateFeeNotice})`
                feeNoticeShowState.versionList = list.map((item) => {
                    const beginDate = formatDate(new Date(item.beginDate))
                    const endDate = formatDate(new Date(item.endDate))
                    return {
                        label: `${item.feeSetName}(${beginDate}/${endDate})`,
                        value: `${item.productId}(${beginDate}/${endDate})`
                    }
                })
            }
        }
    )
    // 切换结算价版本
    const changeFeeNotice = (val) => {
        const index = feeNoticeShowState.versionList.findIndex(item => item.value === val)
        if(index >= 0) {
            feeNoticeShowState.customerFeeIndex = index
            initListCustomerFeeSet()
            initFeeNoticeData()
        }
    }
    // 分区数据是否显示
    const isFeeSetCompareList = computed(() => {
        if (!customerFeeGridOptionsTwo.columns) return false
        return customerFeeGridOptionsTwo.columns.length > 0
    })

    // 获取对应表头数据
    const getDealHeader = (arr) => {
        if (!isArrayLength(arr)) return []
        const resultArr = Object.values(arr.reduce((acc, obj) => {
            const key = `${obj.feeItemId}-${obj.originalBeginWeight}-${obj.originalEndWeight}`;
            if (!acc[key]) {
                acc[key] = [];
            }
            acc[key].push(obj);
            return acc;
        }, {}));
        return resultArr
    }
    // 初始化表头
    const { columnsDynamicMeterHead, initDynamicMeterHead, clearMeterHead } = useDealDynamicMeterHeadData(partitionColumns)
    const initListCustomerFeeSet = async () => {
        const feeNoticeData = unref(customerFeeSetCompareList)
        const partitionList = feeNoticeData.filter((item) => {
            return isNumber(item.originalBeginWeight)
                && isNumber(item.originalEndWeight)
                && isString(item.partitionId)
                && item.feeCompareResult === FeeNoticeShowType.REMIND
        })
        // 获取数组分区数据
        if (isArrayLength(partitionList)) {
            const uniquePartitions = partitionList.reduce((acc, current) => {
                // 检查当前元素的 partitionName 是否已经存在于累加器中
                let existing = acc.find(item => item.partitionName === current.partitionName);
                // 如果不存在，则将当前元素添加到累加器中
                if (!existing) {
                    acc.push(current);
                }
                return acc;
            }, []);
            initPartitionList(uniquePartitions)
        } else {
            // 清空
            clearMeterHead()
            // @ts-ignore
            customerFeeGridOptionsTwo.columns = []
            unref(xCustomerFeeGridTableRef)?.refreshColumn()
        }
    }
    const initPartitionList = (partitionList) => {
        const { columns } = initDynamicMeterHead(partitionList, "partitionId")
        const gridColumns = columns.map((item) => {
            return {
                fixed: item.fixed,
                field: item.prop,
                title: item.label,
                minWidth: 120,
                width: item.width,
                align: 'left',
                slots: item.slot ? { default: item.prop } : {}
            }
        })
        // @ts-ignore
        customerFeeGridOptionsTwo.columns = gridColumns
        unref(xCustomerFeeGridTableRef)?.refreshColumn()
    }
    // 处理对应的分区数据
    const dealSourceFeeNoticeData = (arr) => {
        if (!isArrayLength(arr)) return []
        const resultArr = getDealHeader(arr)
        const targetResult = resultArr.map((subArr) => {
            return subArr.reduce((acc, item) => {
                const { partitionId, priceVariance, organizationOfferPrice, discount, offerPrice, message, ...rest } = item;
                if (partitionId) {
                    acc[partitionId] = {
                        priceVariance,
                        organizationOfferPrice,
                        discount,
                        offerPrice,
                        message
                    };
                }
                return { ...acc, ...rest };
            }, {});
        });
        return targetResult
    }
    // 初始化客户费用异常提示数据
    const initFeeNoticeData = () => {
        const feeNoticeData = unref(customerFeeSetCompareList)
        // 异常为终止状态
        abnormalGridOptions.data = feeNoticeData.filter((item) => item.feeCompareResult === FeeNoticeShowType.TERMINATE_OPERATION)
        // 是否有起始、结束重量、分区表格数据
        const sourceCustomerFeeTwoList = feeNoticeData.filter((item) => {
            return isNumber(item.originalBeginWeight)
                && isNumber(item.originalEndWeight)
                && isString(item.partitionId)
                && item.feeCompareResult === FeeNoticeShowType.REMIND
        })
        // 排序
        const sortCustomerFeeGridOptionsTwo = sourceCustomerFeeTwoList.sort((a, b) => {
            return a.feeItemId - b.feeItemId
        })
        // 扁平化数据
        customerFeeGridOptionsTwo.data = dealSourceFeeNoticeData(sortCustomerFeeGridOptionsTwo)

        // 中间的表格数据
        const sourceCustomerFeeList = feeNoticeData.filter((item) => {
            return item.feeCompareResult === FeeNoticeShowType.REMIND && !item.partitionId
        })
        // 排序
        customerFeeGridOptionsOne.data = sourceCustomerFeeList.sort((a, b) => {
            return a.feeItemId - b.feeItemId
        })
    }
    // 待审批及审批不通过状态
    const isFeeApprovalStatus = computed(() => {
        const status = feeNoticeShowState.currentRow?.feeApprovalStatus
        if (!isNonNegativeInteger(status)) return false
        return status === FeeApprovalStatus.PENDING_APPROVAL || status === FeeApprovalStatus.APPROVAL_FAILED
    })
    // 如果有终止状态则不显示激活按钮
    const isAbnormalList = computed(() => {
        const list = props.customerFeeSetCompareList
        const isFlag = list.some(it1 => {
            const itemArr = it1.customerFeeSetCompareDtoList.filter(it2 => it2.feeCompareResult === FeeNoticeShowType.TERMINATE_OPERATION)
            return isArrayLength(itemArr)
        })
        return isFlag
    })
    const isAbnormal = computed(() => {
        return !(unref(isAbnormalList)) && !isFeeApprovalStatus
    })

    // 显示、隐藏
    const show = (row: Recordable) => {
        feeNoticeShowState.currentRow = row
        onShow()
        nextTick(() => {
            initListCustomerFeeSet()
            initFeeNoticeData()
        })
    }
    // 审批状态判断
    const isApproval = computed(() => {
        if (feeNoticeShowState.currentRow?.feeApprovalStatus === FeeApprovalStatus.PENDING_APPROVAL ||
            feeNoticeShowState.currentRow?.feeApprovalStatus === FeeApprovalStatus.APPROVAL_BY) return false
        return true
    })
    const isApprovalAndAbnormal = computed(() => {
        return !(unref(isAbnormalList)) && unref(isApproval)
    })
    const onclose = () => {
        feeNoticeShowState.customerFeeIndex = 0
        feeNoticeShowState.versionValue = ''
        clearMeterHead()
        onClose()
    }
    const onconfirm = () => {
        setLoading(true)
        emit("onConfirm", feeNoticeShowState.currentRow, onclose, setLoading)
    }
    const onapply = () => {
        setLoading(true)
        emit("onApply", feeNoticeShowState.currentRow, onclose, setLoading)
    }

    return {
        show,
        onclose,
        onconfirm,
        onapply,
        abnormalGridOptions,
        customerFeeGridOptionsOne,
        customerFeeGridOptionsTwo,
        xCustomerFeeGridTableRef,
        fristCustomerFeeSetCompare,
        feeNoticeShowState,
        columnsDynamicMeterHead,
        isFeeSetCompareList,
        isAbnormal,
        isApprovalAndAbnormal,
        changeFeeNotice
    }
}

export {
    useFeeNoticeShow
}