import { api_getReceivableModelByPId } from '@/api/receivable/receivable';
import { ReceivableModelDto, StableFeeItemModelDto, TempFeeItemModelDto } from '@/api/receivable/receivableModel';
import type { BasicTableProps, VxeGridInstance } from '@/components/VxeTable';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import { useMessage } from '@/hooks/useMessage';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { BaseFeeSetType, DialogModel } from '@/type/BastType';
import { cloneDeep } from '@/utils/cloneDeep';
import { deal_ResetObject } from '@/utils/dealData';
import { fee_deal_FilterValidate } from '@/utils/feeSeting/dealData';
import { isArrayLength, isNumber } from '@/utils/is';
import { useReturnData } from '@/utils/useReturnData';
import { ref, Ref, reactive, computed, unref, nextTick } from 'vue';
import { getVxeGridData } from '../base/data';

const { resData } = useReturnData()
const { createMessage } = useMessage()
type ReceivableModelRef = Ref<VxeGridInstance | undefined>
/**
 * 新增应收模版处理
 * @returns 
 */
function useReceivableModelSetAdd(
    dialog: DialogModel,
    onClose: Fn,
    onShow: Fn,
    TemporaryFeeRef: ReceivableModelRef,
    ProductFeeRef: ReceivableModelRef,
    ClosingCostFeeRef: ReceivableModelRef,
    temporaryFeeOptions: BasicTableProps,
    productFeeOptions: BasicTableProps,
    closingCostFeeOptions: BasicTableProps,
    reset: Fn,
    setLoading: Fn,
    emit
) {
    const { formValidate, resetForm } = useEleFormValidate();
    // 基础参数
    const receivableModelSetDto = reactive<ReceivableModelDto>({
        activeFlag: false,
        modelName: '',
        remark: '',
        tempFeeItemModelList: [],
        stableFeeItemModelList: [],
    })
    const receivableModelSetState = reactive({
        type: -1
    })
    const receivableModelSetRules = reactive({
        modelName: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
    })
    const formReceivableModelSetRef = ref()
    const isShowView = computed(() => {
        return receivableModelSetState.type !== BaseFeesetAction.VIEW
    })

    // 显示
    const show = (type: number, data?: Recordable) => {
        receivableModelSetState.type = BaseFeesetAction.ADD
        // 标题
        switch (type) {
            case BaseFeesetAction.ADD:
                dialog.title = '新增应收模版'
                break;
            case BaseFeesetAction.EDIT:
                dialog.title = '编辑应收模版'
                receivableModelSetState.type = BaseFeesetAction.EDIT
                break;
            case BaseFeesetAction.VIEW:
                dialog.title = '查看应收模版'
                receivableModelSetState.type = BaseFeesetAction.VIEW
                break;
        }
        // 编辑
        if (type === BaseFeesetAction.EDIT || type === BaseFeesetAction.VIEW) {
            nextTick(() => {
                initLoadData(data)
            })
        }
        onShow()
    }
    // 隐藏
    const onclose = () => {
        resetForm(unref(formReceivableModelSetRef))
        const resetDto = deal_ResetObject(receivableModelSetDto)
        Object.assign(receivableModelSetDto, resetDto)
        reset()
        onClose()
    }
    // 初始化数据
    const initLoadData = async (data) => {
        if (data.id) {
            const res = await api_getReceivableModelByPId({ id: data.id })
            if (res && res.code == 200) {
                const data = res.data
                Object.assign(receivableModelSetDto, { ...data })
                // 临时费用设置
                if (isArrayLength(data.tempFeeItemModelList)) {
                    temporaryFeeOptions.data = data.tempFeeItemModelList.map(item => {
                        if (isNumber(item.feeItemCategoryId)) item.feeItemCategoryId = String(item.feeItemCategoryId)
                        return item
                    })
                }
                if (isArrayLength(data.stableFeeItemModelList)) {
                    const newData = data.stableFeeItemModelList.map((item) => {
                        if (isNumber(item.feeItemCategoryId)) item.feeItemCategoryId = String(item.feeItemCategoryId)
                        return item
                    })
                    // 客户
                    productFeeOptions.data = newData.filter(item => item.feeSetType === BaseFeeSetType.CUSTOMER_PRICE)
                    // 结算
                    closingCostFeeOptions.data = newData.filter(item => item.feeSetType === BaseFeeSetType.SETTLEMENT_PRICE)
                }
            }
        }
    }

    // 提交
    const confirm = async () => {
        // 校验
        const $tableTemporaryFee = unref(TemporaryFeeRef)
        const $tableProductFee = unref(ProductFeeRef)
        const $tableClosingCostFee = unref(ClosingCostFeeRef)
        Promise.all([formValidate(unref(formReceivableModelSetRef)), $tableTemporaryFee?.validate(true), $tableProductFee?.validate(true), $tableClosingCostFee?.validate(true)])
            .then(async (results) => {
                // 校验的全部状态
                const isValidate = await fee_deal_FilterValidate(results)
                if (!isValidate) return
                setLoading(true)
                // 临时费用
                receivableModelSetDto.tempFeeItemModelList = await getVxeGridData<TempFeeItemModelDto>(TemporaryFeeRef)
                // 稳定费用
                receivableModelSetDto.stableFeeItemModelList = [...await getVxeGridData<StableFeeItemModelDto>(ProductFeeRef), ...await getVxeGridData<StableFeeItemModelDto>(ClosingCostFeeRef)]
                emit("saveReceivableModel", cloneDeep(receivableModelSetDto), onclose, setLoading)
            })
    }

    return {
        show,
        onclose,
        confirm,
        receivableModelSetDto,
        receivableModelSetRules,
        formReceivableModelSetRef,
        isShowView
    }
}

export {
    useReceivableModelSetAdd
}