import { Table } from "./interface";
import { reactive, computed, toRefs, nextTick } from "vue";
import { useUserStore } from "@/stores/modules/user";
import { useGlobalStore } from "@/stores/modules/global";
interface PageChange {
  currentPage: number;
  pageSize: number;
}
/**
 * @description table 页面操作方法封装
 * @param {Function} api 获取表格数据 api 方法 (必传)
 * @param {Object} initParam 获取数据初始化参数 (非必传，默认为{})
 * @param {Boolean} isPageable 是否有分页 (非必传，默认为true)
 * @param {Function} dataCallBack 对后台返回的数据进行处理的方法 (非必传)
 * @param {String} dwname 布局窗口模块 (非必传)
 * @param {number} pageSizes 每页显示数量
 * @param {Boolean} loadLayout 加载布局数据
 * @param {Boolean} loadLayoutCallBack 加载布局数据, 返回的数据进行处理的方法 (非必传)
 * */
export const useTable = (
  api?: (params: any) => Promise<any>,
  initParam: object = {},
  isPageable: boolean = true,
  dataCallBack?: (data: any) => any,
  requestError?: (error: any) => void,
  dwname: string = "",
  pageSizes?: number,
  loadLayout: boolean = false,
  loadLayoutCallBack?: (data: any) => any,
  pageChangeCallBack?: () => void
) => {
  const state = reactive<Table.TableStateProps>({
    // 表格数据
    tableData: [],
    // 分页数据
    pageable: {
      // 当前页数
      pageNum: 1,
      // 每页显示条数
      pageSize: pageSizes ?? 20,
      // 总条数
      total: 0
    },
    // 查询参数(只包括查询)
    searchParam: {},
    // 初始化默认的查询参数
    searchInitParam: {},
    // 总参数(包含分页和查询参数)
    totalParam: {},
    tableLoading: false,
    lastPageable: {
      pageNum: 1,
      pageSize: pageSizes ?? 20,
      total: 0
    }
  });

  /**
   * @description 分页查询参数(只包括分页和表格字段排序,其他排序方式可自行配置)
   * */
  const pageParam = computed({
    get: () => {
      return {
        pageNum: state.pageable.pageNum,
        pageSize: state.pageable.pageSize
      };
    },
    set: (newVal: any) => {
      console.log("我是分页更新之后的值", newVal);
    }
  });

  /**
   * @description 获取表格数据
   * @return void
   * */
  const getTableList = async () => {
    if (!api) return;
    try {
      // 先把初始化参数和分页参数放到总参数里面
      console.log("state.totalParam :>> ", state.totalParam);
      console.log("state.initParam :>> ", initParam);
      console.log("state.searchParam :>> ", state.searchParam);
      Object.assign(state.totalParam, initParam, isPageable ? pageParam.value : {});
      state.tableLoading = true;
      console.log("state.searchInitParam :>> ", state.searchInitParam, { ...state.searchInitParam, ...state.totalParam });
      let data = await api({ ...state.searchInitParam, ...state.totalParam });
      dataCallBack && (data = dataCallBack(data));
      // state.tableData = isPageable ? data.list : data;
      state.tableData = data.list;
      state.tableLoading = false;
      console.log("getTableList data :>> ", data);
      console.log("aff  loadLayout :>> ", loadLayout);
      // 第一页的时候会执行这个回调，第二页开始没有tableinfo返回
      data.tableinfo && loadLayout && loadLayoutCallBack && loadLayoutCallBack(data.tableinfo);
      // state.tableData = data[reqProp];
      // 解构后台返回的分页数据 (如果有分页更新分页信息)
      const { pageNum, pageSize, total } = data;
      isPageable && updatePageable({ pageNum, pageSize, total });
      nextTick(() => {
        console.log(" autoUpdateTableCheckbox pageChangeCallBack :>> ");
        pageChangeCallBack && pageChangeCallBack();
      });
    } catch (error) {
      requestError && requestError(error);
      state.tableLoading = false;
      state.pageable.pageNum = state.lastPageable.pageNum;
      state.pageable.pageSize = state.lastPageable.pageSize;
    }
  };

  /**
   * @description 更新查询参数
   * @return void
   * */
  const updatedTotalParam = () => {
    state.totalParam = {};
    // 处理查询参数，可以给查询参数加自定义前缀操作
    let nowSearchParam: { [key: string]: any } = {};
    // 防止手动清空输入框携带参数（这里可以自定义查询参数前缀）
    for (let key in state.searchParam) {
      // * 某些情况下参数为 false/0 也应该携带参数
      if (state.searchParam[key] || state.searchParam[key] === false || state.searchParam[key] === 0) {
        nowSearchParam[key] = state.searchParam[key];
      }
    }
    Object.assign(state.totalParam, nowSearchParam, isPageable ? pageParam.value : {});
    console.log("updatedTotalParam state.searchParam :>> ", state.searchParam);
    console.log("updatedTotalParam state.totalParam :>> ", state.totalParam);

    if (dwname) {
      const userStore = useUserStore();
      userStore.setSearchQueryHabit(dwname, state.totalParam);
    }
  };

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

  /**
   * @description 表格数据查询
   * @return void
   * */
  const search = () => {
    state.pageable.pageNum = 1;
    updatedTotalParam();
    getTableList();
  };

  /**
   * @description 表格数据重置
   * @return void
   * */
  const reset = () => {
    state.pageable.pageNum = 1;
    state.searchParam = {};
    // 重置搜索表单的时，如果有默认搜索参数，则重置默认的搜索参数
    Object.keys(state.searchInitParam).forEach(key => {
      state.searchParam[key] = state.searchInitParam[key];
    });
    updatedTotalParam();
    getTableList();
  };

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

  /**
   * @description 每页条数改变
   * @return void
   * */
  const handlePageChange = ({ currentPage, pageSize }: PageChange) => {
    state.lastPageable.pageNum = state.pageable.pageNum;
    state.lastPageable.pageSize = state.pageable.pageSize;
    if (state.pageable.pageSize != pageSize && dwname) {
      const globalStore = useGlobalStore();
      let _pageSize = globalStore.pageSizes;
      _pageSize[dwname] = pageSize;
      globalStore.setGlobalState("pageSizes", _pageSize);
    }
    state.pageable.pageNum = currentPage;
    state.pageable.pageSize = pageSize;
    getTableList();
  };

  /**
   * @description 当前页改变
   * @param {Number} val 当前页
   * @return void
   * */
  const handleCurrentChange = (val: number) => {
    state.pageable.pageNum = val;
    getTableList();
  };

  return {
    ...toRefs(state),
    getTableList,
    search,
    reset,
    handleSizeChange,
    handleCurrentChange,
    handlePageChange,
    updatedTotalParam
  };
};
