import { Table } from "./interface";
import { reactive, computed, toRefs } from "vue";
// import { cloneDeep } from "lodash-es";
// import $Bus from "@/utils/mittBus";
// import { cloneDeep } from "lodash-es";
/**
 * @description table 页面操作方法封装
 * @param {Function} api 获取表格数据 api 方法 (必传)
 * @param {Object} initParam 获取数据初始化参数 (非必传，默认为{})
 * @param {Boolean} isPageable 是否有分页 (非必传，默认为true)
 * @param {Function} dataCallBack 对后台返回的数据进行处理的方法 (非必传)
 * */
export const useTable = (
    ruleForm: any,
    routeName: any,
    api?: (params: any) => Promise<any>,
    initParam: object = {},
    isPageable: boolean = true,
    dataCallBack?: (data: any) => any,
    requestError?: (error: any) => void,
    clearSelection?: () => void
) => {
    const state = reactive<Table.StateProps>({
        // 表格数据
        tableData: [],
        // 分页数据
        pageable: {
            // 当前页数
            pageNo: 1,
            // 每页显示条数
            pageSize: 20,
            // 总条数
            total: 0
        },
        searchParams: ruleForm,
        // 初始化默认的查询参数
        searchInitParam: initParam,
        totalQty: 0,
        details: []
    });

    /**
     * @description 分页查询参数(只包括分页和表格字段排序,其他排序方式可自行配置)
     * */
    const pageParam = computed({
        get: () => {
            return {
                pageNo: state.pageable.pageNo,
                pageSize: state.pageable.pageSize
            };
        },
        set: (newVal: any) => {
            console.log("我是分页更新之后的值", newVal);
        }
    });
    const noExprotTimeDate = (params: any) => {
        if (params.time) {
            params.createBeginDate = params.time[0];
            params.createEndDate = params.time[1];
        } else {
            params.createBeginDate = "";
            params.createEndDate = "";
        }
    };
    const exportTimeDate = (params: any) => {
        if (params.time) {
            params.beginDate = params.time[0];
            params.endDate = params.time[1];
        } else {
            params.beginDate = "";
            params.endDate = "";
        }
    };
    const getTableList = async (params: Record<string, any> = state.searchInitParam) => {
        state.tableData = [];

        if (!api) return;
        try {
            //置空复选框
            clearSelection && clearSelection();

            //routeName !== "exportList"  ? noExprotTimeDate(params) : exportTimeDate(params);
            routeName === "exportList" ? exportTimeDate(params) : noExprotTimeDate(params);
            // 先把初始化参数和分页参数放到总参数里面
            let { data, totalCount, totalQty, details } = await api({ ...params, ...pageParam.value });

            dataCallBack && (data = dataCallBack(data));
            //表格赋值
            state.tableData = data;
            //出入库回退列表（备注remark）后台给null的时候前端显示 -- 数据处理
            // if (data && data.length > 0 && routeName !== "exportList") {
            //     data.forEach((o: any) => (o.remark = o.remark === null ? "" : o.remark));
            //     //表格赋值
            //     state.tableData = data;
            // }

            if (routeName === "warehouseReceiptList" || routeName === "immediately") {
                state.totalQty = totalQty;
            }
            if (routeName === "finishedProductIndex") {
                state.details = details;
            }
            if (routeName === "exportList") {
                state.tableData = data.list;
            }
            // 解构后台返回的分页数据 (如果有分页更新分页信息)
            if (isPageable) {
                let total = totalCount;
                if (routeName === "exportList") {
                    total = data.totalCount;
                }
                updatePageable({ pageNo: state.pageable.pageNo, pageSize: state.pageable.pageSize, total });
            }
        } catch (error) {
            requestError && requestError(error);
        }
    };

    /**
     * @description 更新分页信息
     * @param {Object} pageable 后台返回的分页数据
     * @return void
     * */
    const updatePageable = (pageable: Table.Pageable) => {
        Object.assign(state.pageable, pageable);
    };

    /**
     * @description 每页条数改变
     * @param {Number} val 当前条数
     * @return void
     * */
    const handleSizeChange = (val: number) => {
        state.pageable.pageSize = val;
        getTableList(state.searchParams);
    };

    /**
     * @description 当前页改变
     * @param {Number} val 当前页
     * @return void
     * */
    const handleCurrentChange = (val: number) => {
        state.pageable.pageNo = val;
        getTableList(state.searchParams);
    };
    /**
     * @description 重置页码
     * @return void
     * */
    const initPage = (params: Record<string, any>) => {
        state.pageable.pageSize = 20;
        state.pageable.pageNo = 1;
        getTableList(params);
    };
    return {
        ...toRefs(state),
        getTableList,
        handleSizeChange,
        handleCurrentChange,
        initPage
    };
};
