import { api_activePayableModel, api_addPayableModel, api_deletePayableModel, api_editPayableModel, api_payableModelList } from '@/api/payable/payable';
import { PayableModelDto, PayableModelParams } from '@/api/payable/payableModel';
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, unref, computed, onMounted } from 'vue';

const { resData } = useReturnData()
const { report } = useErrorConfirm()
/** 
 * 应付模版列表数据处理
 * @returns 
 */
function usePayableModelList(payableModelListOptions: BasicTableProps) {
    const { global } = useInstance();
    // 费用类型下拉列表的value与label键
    const fieldsObj = {
        valueField: 'id',
        labelField: 'itemName'
    }
    // 费用设置列表stroe
    const { storeDropDownData, costFeeItemList, allProvidersList } = useDropDownData()
    const storeFeesetList = useFeesetList()
    const feeItemCategoryList = computed(() => storeFeesetList.getFeeItemCategoryList)
    // 搜索参数
    const listParm = reactive<PayableModelParams>({
        idList: [],
        modelName: undefined,
        feeItemCategoryId: undefined,
        feeItemId: undefined,
        productId: undefined,
        providerId: undefined,
        pageNum: 1,
        pageSize: 10,
        total: 0
    })
    // 应付模版列表-基础数据
    const payableModelState = reactive({
        disabledArr: [] as number[],
        date: [],
        loading: false
    })
    const searchFormRef = ref()
    const payableModelAddRef = ref<{ show: Fn }>()
    const { resetForm } = useEleFormValidate();
    onMounted(() => {
        storeFeesetList.addFeeItemCategoryList()
        storeDropDownData.addFeeItemList()
        storeDropDownData.addAllProvidersList()
    })

    // 初始化
    const initPayableModelList = async () => {
        try {
            // 起始时间、结束时间参数
            const dateArr = payableModelState.date
            if (isArrayLength(dateArr)) {
                listParams.beginDate = formatDateTime(dateArr[0])
                listParams.endDate = formatDateTime(dateArr[1])
            }
            payableModelState.loading = true
            const res = await api_payableModelList(listParams)
            if (res && res.code == 200) {
                payableModelListOptions.data = res.data.records
                listParm.total = res.data.total;
            }
        } catch (error) {
            report(error)
        } finally {
            payableModelState.loading = false
        }
    }
    // 重置
    const resetParams = () => {
        listParams.beginDate = undefined
        listParams.endDate = undefined
        resetForm(unref(searchFormRef))
        payableModelState.date = []
    }
    // 初始化列表、分页数据
    const { sizeChange, currentChange, searchBtn, resetBtn, listParams } = useQueryList<PayableModelParams>(initPayableModelList, resetParams, listParm)
    // 添加
    const addBtn = () => { unref(payableModelAddRef)?.show(BaseFeesetAction.ADD) }
    // 操作类型
    const hanleChangeAction = async (data: Recordable) => {
        const row = cloneDeep(data)
        const types = row.types;
        switch (types) {
            // 应付模版-编辑
            case BaseFeesetAction.EDIT:
                unref(payableModelAddRef)?.show(BaseFeesetAction.EDIT, row)
                break;
            // 应付模版-删除
            case BaseFeesetAction.DELETE:
                deleteBtn(row.id)
                break;
            // 应付模版-查看
            case BaseFeesetAction.VIEW:
                unref(payableModelAddRef)?.show(BaseFeesetAction.VIEW, row)
                break;
            // 激活
            case BaseFeesetAction.FEESET_ACTIVE:
                const res = await api_activePayableModel({ id: row.id, activeFlag: !row.activeFlag })
                const codeData = resData(res, "修改成功！")
                if (codeData !== 500) initPayableModelList();
                break;
            default:
                break;
        }
    }

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

    // 下拉按钮显示事件
    const changeVisibleChange = (val, scope) => {
        if (!val) return
        // 是否激活状态
        const seting = scope.row.activeFlag ? BaseFeesetAction.EDIT : -1
        payableModelState.disabledArr = [seting]
    }

    const hanleSavePayableModel = async (params: PayableModelDto, onclose: Fn, setLoading: Fn) => {
        try {
            if (params.id) {
                // 编辑
                const res = await api_editPayableModel(params)
                const resCode = resData(res, "保存成功")
                if (resCode !== 500) {
                    initPayableModelList()
                    onclose()
                }
                return
            }
            // 添加
            const res = await api_addPayableModel(params)
            const resCode = resData(res, "保存成功")
            if (resCode !== 500) {
                initPayableModelList()
                onclose()
            }
        } finally {
            setLoading(false)
        }
    }

    return {
        listParm,
        payableModelState,
        searchFormRef,
        payableModelAddRef,
        fieldsObj,
        addBtn,
        sizeChange,
        currentChange,
        searchBtn,
        resetBtn,
        hanleChangeAction,
        changeVisibleChange,
        hanleSavePayableModel,
        feeItemCategoryList,
        costFeeItemList,
        allProvidersList
    }
}

export {
    usePayableModelList
}