//  Copyright (c) 2024 Huawei Technologies Co., Ltd.
//  openUBMC is licensed under Mulan PSL v2.
//  You can use this software according to the terms and conditions of the Mulan PSL v2.
//  You may obtain a copy of Mulan PSL v2 at:
//        #  http://license.coscl.org.cn/MulanPSL2
//  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
//  EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
//  MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
//  See the Mulan PSL v2 for more details.
import { reactive, toRefs, ref, computed, nextTick } from 'vue';
import { ITableColumn } from '@/model/base-table';
import { deepClone } from '@/utils/utils';

/** 通用table
 * @param id 设置table id
 * @param columns 配置column项
 * @param isPage 是否是后台分页
 * @function callback 表格查询数据请求方法
 */
const defaultCallback = (res: any = {}) => {
  const { total = 0, data = [] } = res || {};
  return {
    total,
    data,
  };
};

/* eslint-disable-next-line max-lines-per-function*/
export function useTable(
  id: string,
  columns: ITableColumn[] = [],
  isPage: boolean = false,
  callback: any = defaultCallback,
): any {
  const defaultCurrentPage = 1;
  const defaultPageSize = 10;

  const currentPage = ref(defaultCurrentPage);
  const pageSize = ref(defaultPageSize);
  const pageSizes = ref([10, 20, 30, 50]);
  const layout = ref('total, sizes, prev, pager, next, jumper');
  const isPagination = ref(isPage);

  const data = reactive({
    id,
    columns,
    total: 0,
    oldTableData: [],
    tableData: [],
    isPagination,
    layout,
    currentPage,
    pageSize,
    pageSizes,
  });

  const showPagination = computed(() => {
    return data.tableData.length !== 0;
  });

  const displayedTableData = computed(() => {
    if (isPagination.value) {
      return data.tableData;
    }
    return data.tableData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value,
    );
  });

  function handleSizeChange(val: number) {
    pageSize.value = val;
    nextTick(() => {
      callback();
    });
  }

  function handleCurrentChange(val: number) {
    currentPage.value = val;
    if (isPagination.value) {
      callback();
    }
  }

  function handleReset() {
    pageSize.value = defaultPageSize;
    currentPage.value = defaultCurrentPage;
  }

  function getCurrentPage() {
    return data.currentPage;
  }

  function getPageSize() {
    return data.pageSize;
  }

  function filterContent(oldTableData: any[], filterFields: string, searchStr: string) {
    if (oldTableData instanceof Array) {
      return oldTableData.filter((item: any) => {
        let value = item[filterFields];
        if (value || value === 0) {
          value = value.toString();
        }
        // 数据对象是字符串类型时
        if (typeof value === 'string') {
          return value.toUpperCase().indexOf(searchStr) >= 0;
        } else if (value instanceof Array) {
          // 数据对象是字符串数组时
          let flag = false;
          for (let i = 0; i < value.length; i++) {
            if (typeof value[i] === 'string' && value[i].toUpperCase().indexOf(searchStr) >= 0) {
              flag = true;
              break;
            }
          }
          return flag;
        } else {
          return true;
        }
      });
    }
    return [];
  }

  /**
   * 数据过滤
   * @param searchContent 筛选条件-输入框内容
   * @param filterFields 过滤字段，可以是多个字段
   */
  function filterData(searchContent: string, filterFields: string | string[]) {
    let oldTableData: any = deepClone(data.oldTableData);
    if (searchContent) {
      const searchStr = searchContent.toUpperCase();
      if (typeof filterFields === 'string') {
        oldTableData = filterContent(oldTableData, filterFields, searchStr);
      } else if (filterFields instanceof Array) {
        const arr: any = [];
        filterFields.forEach((filed: string) => {
          if (typeof filed === 'string') {
            const list = filterContent(oldTableData, filed, searchStr);
            if (list) {
              arr.push(...list);
            }
          }
        });
        // 数组去重
        oldTableData = Array.from(new Set(arr));
      }
    }
    data.total = oldTableData.length;
    data.tableData = oldTableData.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value,
    );
  }

  function setTableData(total: number, tableData: any) {
    data.total = total;
    data.tableData = tableData;
    data.oldTableData = deepClone(tableData);
  }

  return {
    ...toRefs(data),
    showPagination,
    displayedTableData,
    handleSizeChange,
    handleCurrentChange,
    handleReset,
    getCurrentPage,
    getPageSize,
    setTableData,
    filterData,
  };
}
