import { api_addCostFeeItemSet, api_deleteReceivableModel, api_editReceivableModel, api_receivableModelActive, api_receivableModelList } from '@/api/receivable/receivable';
import { ReceivableModelDto, ReceivableParams } from '@/api/receivable/receivableModel';
import type { BasicTableProps } from '@/components/VxeTable';
import { useDropDownData } from '@/hooks/useDropDownData';
import { useEleFormValidate } from '@/hooks/useEleFormValidate';
import useInstance from '@/hooks/useInstance';
import { useQueryList } from '@/hooks/useQueryList';
import { useFeesetList } from '@/store/list_feeset';
import { BaseFeesetAction } from '@/type/BaseFeesetAction';
import { cloneDeep } from '@/utils/cloneDeep';
import { formatDateTime } from '@/utils/dateFormate';
import { isArrayLength } from '@/utils/is';
import { useErrorConfirm } from '@/utils/useErrorConfirm';
import { useReturnData } from '@/utils/useReturnData';
import { ref, reactive, computed, unref, onMounted } from 'vue';

const { resData } = useReturnData()
const { report } = useErrorConfirm()
/**
 * 应收模版列表处理
 * @returns 
 */
function useReceivableModelList(receivableListOptions: BasicTableProps) {
    // 下拉列表的value与label键
    const fieldsObj = {
        valueField: 'id',
        labelField: 'itemName'
    }
    const { global } = useInstance();
    // 费用设置列表stroe
    const { storeDropDownData, feeItemLists } = useDropDownData()
    const storeFeesetList = useFeesetList()
    const feeItemCategoryList = computed(() => storeFeesetList.getFeeItemCategoryList)
    const searchFormRef = ref()
    const addReceivableModelSetRef = ref<{ show: Fn }>()
    // 搜索参数
    const listParm = reactive<ReceivableParams>({
        idList: [],
        modelName: undefined,
        feeItemCategoryId: undefined,
        feeItemId: undefined,
        productId: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    // 应收模版列表-基础数据
    const receivableModelList = reactive({
        date: [],
        disabledArr: [] as number[],
        loading: false
    })

    onMounted(() => {
        storeFeesetList.addFeeItemCategoryList()
        storeDropDownData.addFeeItemList()
    })

    const { resetForm } = useEleFormValidate();

    // 操作类型
    const hanleChangeAction = async (data: Recordable) => {
        const row = cloneDeep(data)
        const types = row.types;
        switch (types) {
            // 应收模版-编辑
            case BaseFeesetAction.EDIT:
                unref(addReceivableModelSetRef)?.show(BaseFeesetAction.EDIT, row)
                break;
            // 应收模版-删除
            case BaseFeesetAction.DELETE:
                deleteBtn(row.id)
                break;
            // 应收模版-查看
            case BaseFeesetAction.VIEW:
                unref(addReceivableModelSetRef)?.show(BaseFeesetAction.VIEW, row)
                break;
            // 激活
            case BaseFeesetAction.FEESET_ACTIVE:
                const res = await api_receivableModelActive({ id: row.id, activeFlag: !row.activeFlag })
                const codeData = resData(res, "修改成功！")
                if (codeData !== 500) initReceivableModelList();
                break;
            default:
                break;
        }
    }

    //费用设置删除
    const deleteBtn = async (id: number) => {
        //信息确认
        let confirm = await global.$myconfirm('确定删除该数据吗?')
        if (confirm) {
            const deleteRes = await api_deleteReceivableModel({ id })
            const deleteCode = resData(deleteRes, "删除成功")
            if (deleteCode !== 500) initReceivableModelList()
        }
    }

    // 初始化
    const initReceivableModelList = async () => {
        try {
            // 起始时间、结束时间参数
            const dateArr = receivableModelList.date
            if (isArrayLength(dateArr)) {
                listParams.beginDate = formatDateTime(dateArr[0])
                listParams.endDate = formatDateTime(dateArr[1])
            }
            receivableModelList.loading = true
            const res = await api_receivableModelList(listParams)
            if (res && res.code == 200) {
                receivableListOptions.data = res.data.records
                listParm.total = res.data.total;
            }
        } catch (error) {
            report(error)
        } finally {
            receivableModelList.loading = false
        }
    }

    // 重置
    const resetParams = () => {
        resetForm(unref(searchFormRef))
        receivableModelList.date = []
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<ReceivableParams>(initReceivableModelList, resetParams, listParm)
    // 添加
    const addBtn = () => { unref(addReceivableModelSetRef)?.show(BaseFeesetAction.ADD) }
    // 保存/编辑
    const hanleSaveReceivableModel = async (params: ReceivableModelDto, onclose: Fn, setLoading: Fn) => {
        try {
            if (params.id) {
                // 编辑
                const res = await api_editReceivableModel(params)
                const resCode = resData(res, "保存成功")
                if (resCode !== 500) {
                    initReceivableModelList()
                    onclose()
                }
                return
            }
            // 添加
            const res = await api_addCostFeeItemSet(params)
            const resCode = resData(res, "保存成功")
            if (resCode !== 500) {
                initReceivableModelList()
                onclose()
            }
        } finally {
            setLoading(false)
        }
    }
    // 下拉按钮显示事件
    const changeVisibleChange = (val, scope) => {
        if (!val) return
        // 是否激活状态
        const seting = scope.row.activeFlag ? BaseFeesetAction.EDIT : -1
        receivableModelList.disabledArr = [seting]
    }

    return {
        listParm,
        receivableModelList,
        addReceivableModelSetRef,
        searchFormRef,
        searchBtn,
        resetBtn,
        addBtn,
        hanleChangeAction,
        sizeChange,
        currentChange,
        hanleSaveReceivableModel,
        changeVisibleChange,
        feeItemLists,
        feeItemCategoryList,
        fieldsObj,
    }
}

export {
    useReceivableModelList
}
