/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react-hooks/rules-of-hooks */
import React, { useEffect, useRef, useState, memo, useMemo } from 'react';
import { ProTable } from '@ant-design/pro-components';
import Resizecell from './Resizecell';
import { Tooltip } from 'antd';
import { doFetch } from '@/utils/doFetch';
import { useAsyncEffect } from 'ahooks';
import bodyParse from 'query-string';

let handlEmptyChild = (tree = []) => {
  const newtree = tree.map((item) => {
    if (!item.children || item.children.length == 0) {
      item.value = item.key;
      return item;
    } else {
      item.value = item.key;
      return {
        ...item,
        children: handlEmptyChild(item.children),
      };
    }
  });
  return newtree;
};

const Mtable = (props) => {
  const {
    headerTitle,
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams, //额外参数
    pageSize, //修改默认pageSize
    pagination = true, //分页设置
    x, //横向滚动
    activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
    refreshDep, //依赖刷新 （已废弃）
    getDefaultSelected, //存在默认选中向上返回选中值
    resizeable = false,
    dataSource,
    iscurrent = true,
    toolBarRender = false,
    dataSourceFieldsChange
  } = props;
  const actionRefs = actionRef ?? useRef(),
    formRefs = formRef ?? useRef(),
    ifspagination = pagination == 'false' || pagination === false,
    [size, setsize] = useState('small'),
    [valueColumns, setvalueColumns] = useState({});
  const [columnes, setcolumnes] = useState(columns ?? []);
  const [newparames, setnewparams] = useState({});

  //调用接口
  const request = async (params, sort, filter) => {
    if (!path) return;
    let newparams = {
      ...params,
      ...extraparams, //父组件传参
      pageIndex: params.current,
      pageSize: params.pageSize || pageSize,
    };
    delete newparams.current;
    if (ifspagination) {
      delete newparams.pageIndex;
      delete newparams.pageSize;
    }
    const result = await doFetch({ url: path, params: newparams });
    //分页结果
    let data = result?.data?.page?.list,
      success = true,
      total = result?.data?.page?.total;
    //不带分页获取结果
    if (ifspagination) {
      data = result?.data?.dataList;
      total = result?.data?.dataList?.length;
    }
    //存在默认选中向上返回选中值
    getDefaultSelected && getDefaultSelected(result?.data);
    return {
      data,
      success,
      total,
    };
  };
  //更新 columns
  useEffect(() => {
    setcolumnes((s) => {
      return columns.map((item, index) => {
        let it = { ...item };
        let itemwidth = valueColumns[it.key]?.width
          ? valueColumns[it.key].width
          : it.width
            ? it.width
            : resizeable
              ? 160
              : 'auto';
        let options = {},
          faoptopns = it?.searchOptions ?? it?.options;
        if (['select', 'treeSelect', 'radio', 'checkbox', 'cascader'].includes(it?.valueType)) {
          if (Array.isArray(faoptopns)) {
            options = {
              fieldProps: {
                ...it?.fieldProps,
                options: [...faoptopns],
              },
            };
          } else if (faoptopns) {
            options = {
              request: async (params) => {
                let list = await doFetch({ url: it?.options?.path, params: it?.options?.params });
                const res = list.data.dataList;
                return it.valueType == 'treeSelect' ? handlEmptyChild(res) : res;
              },
            };
          }
        }
        if (it.valueType == 'option') {
          options = {
            key: 'option',
            dataIndex: 'option',
            fixed: 'right',
          };
        }
        if (!it.render) {
          options = {
            ...options,
            render: (text, row) => {
              return (
                <Tooltip title={row[it.dataIndex]} placement="topLeft">
                  <span className="table-cell">{row[it.dataIndex] ?? '-'}</span>
                </Tooltip>
              );
            },
          };
        }
        options = {
          ...options,
          width: itemwidth,
        };

        delete it.formItemProps;
        return {
          ...it,
          ...options,
          onHeaderCell: (column) => ({
            width: column.width ?? itemwidth,
            onResize: handleResize(index),
            onResizeStop: handleResizeStop(index),
          }),
        };
      });
    });
  }, [valueColumns]);

  let columncs = useMemo(() => {
    if (resizeable) return;
    return columns.map((item, index) => {
      let it = { ...item };
      let itemwidth = it.width ? it.width : resizeable ? 160 : 'auto';
      let options = {},
        faoptopns = it?.searchOptions ?? it?.options;
      if (['select', 'treeSelect', 'radio', 'checkbox', 'cascader'].includes(it?.valueType)) {
        if (Array.isArray(faoptopns)) {
          options = {
            fieldProps: {
              ...it?.fieldProps,
              options: [...faoptopns],
            },
          };
        } else if (faoptopns) {
          options = {
            params: newparames,
            request: async (params) => {
              if (Object.keys(it?.options).includes('linkParams')) {
                let resparams = {},
                  linkParams = it?.options?.linkParams ?? {};
                for (let i in linkParams) {
                  let paramsKey = !linkParams[i] ? i : linkParams[i];
                  resparams[paramsKey] = newparames[i];
                }
                let list = await doFetch({ url: it?.options?.path, params: resparams });
                const res = list.data.dataList;
                return it.valueType == 'treeSelect' ? handlEmptyChild(res) : res;
              } else {
                let list = await doFetch({ url: it?.options?.path, params: it?.options?.params });
                const res = list.data.dataList;
                return it.valueType == 'treeSelect' ? handlEmptyChild(res) : res;
              }
            },
          };
        }
      }
      if (it.valueType == 'option') {
        options = {
          key: 'option',
          dataIndex: 'option',
          fixed: 'right',
        };
      }
      if (!it.render) {
        options = {
          ...options,
          render: (text, row) => {
            return (
              <Tooltip title={row[it.dataIndex]} placement="topLeft">
                <span className="table-cell">{row[it.dataIndex] ?? '-'}</span>
              </Tooltip>
            );
          },
        };
      }

      options = {
        ...options,
        width: itemwidth,
      };

      delete it.formItemProps;
      return {
        ...it,
        ...options,
        key: it.searchKey ?? it?.key,
        valueType: it.searchValueType ?? it?.valueType,
      };
    });
  }, [columns, newparames]);

  //初始化操作数据
  const initDrage = async () => {
    if (!path) return;
    let res = await doFetch({
      url: '/ngic-base-business/paFieldScene/queryContro',
      params: {
        sceneMark: activeTabKey ? path + activeTabKey : path,
      },
    });
    if (res.code == '0000') {
      //datalist:接口返回状态
      let datalist = {};
      res?.data?.dataList &&
        res.data.dataList.map((it) => {
          const { fieldKey, fieldWidth, fieldOrder, fieldFixed, fieldShow } = it ?? {};
          datalist[fieldKey] = {
            width: fieldWidth,
            order: fieldOrder,
            fixed: fieldKey == 'option' || fieldKey == 'option_dataindex' ? 'right' : fieldFixed,
            show: fieldShow,
          };
        });
      //allcol 默认状态设置 valueColumns 为columns全列设置
      let allcol = {};
      columns.map((it, i) => {
        if (it.valueType == 'option') {
          allcol.option = {
            order: columns.length - 1,
            show: true,
            fixed: 'right',
            ...datalist.option,
          };
        } else {
          allcol[it.key] = {
            order: i,
            show: true,
            ...datalist[it.key],
          };
        }
      });
      setvalueColumns(allcol);
    }
  };

  //调用重新渲染表格
  useAsyncEffect(async () => {
    if (resizeable) {
      await initDrage();
    }
    iscurrent && actionRefs?.current?.reload();
    // actionRefs?.current?.reset();
  }, [columns, extraparams, path, activeTabKey, refreshDep, iscurrent]);

  //缩放表格
  const handleResize =
    (index) =>
      (e, { size }) => {
        e.stopImmediatePropagation();
        setcolumnes((s) => {
          const nextColumns = [...s];
          nextColumns[index] = {
            ...nextColumns[index],
            width: size.width,
          };
          return nextColumns;
        });
      };

  //更新表格缩放
  const handleResizeStop =
    (index) =>
      (e, { size }) => {
        e.stopImmediatePropagation();
        let submitdata = { ...valueColumns } ?? {},
          curkey = Object.keys(submitdata)[index];
        submitdata[curkey].width = parseInt(size.width);
        setvalueColumns(submitdata);
        doFetch({
          url: '/ngic-base-business/paFieldScene/save',
          params: {
            sceneMark: activeTabKey ? path + activeTabKey : path,
            controList: Object.keys(submitdata).map((it, i) => {
              return {
                fieldKey: it,
                fieldWidth: i == index ? parseInt(size.width) : submitdata[it].width,
                fieldOrder: submitdata[it].order,
                fieldFixed: submitdata[it].fixed,
                fieldShow: submitdata[it].show,
              };
            }),
          },
        });
      };

  const components = resizeable
    ? {
      components: {
        header: {
          cell: Resizecell,
        },
      },
      columnsState: {
        value: valueColumns,
        onChange: (val, state) => {
          setvalueColumns((s) => {
            let submitdata = {
              ...s,
              ...val,
            };
            doFetch({
              url: '/ngic-base-business/paFieldScene/save',
              params: {
                sceneMark: activeTabKey ? path + activeTabKey : path,
                controList: Object.keys(submitdata).map((it) => {
                  return {
                    fieldKey: it,
                    fieldWidth: submitdata[it].width,
                    fieldOrder: submitdata[it].order,
                    fieldFixed: submitdata[it].fixed,
                    fieldShow: submitdata[it].show,
                  };
                }),
              },
            });
            return submitdata;
          });
        },
      },
    }
    : {};

  const datas = dataSource ? { dataSource, toolBarRender: toolBarRender == false ? false : () => { } } : { request };
  return (
    <ProTable
      {...props}
      {...components}
      {...datas}
      size={size}
      onSubmit={(params) => {
        let newparams = {},
          curkey = Object.keys(params)[Object.keys(params).length - 1],
          curval = Object.values(params)[Object.keys(params).length - 1];
        columns
          ?.filter((it) => !(it.search === false || it.hideInSearch === true))
          .map((it, i) => {
            let { linkParams } = it?.options ?? {};
            if (linkParams && Object.keys(linkParams).includes(curkey)) {
              for (let dataindex in linkParams) {
                newparams[dataindex] = formRefs?.current?.getFieldValue?.(dataindex);
              }
            }
          });
        if (Object.keys(newparams).length > 0) {
          setnewparams((s) => ({
            ...s,
            ...newparams,
          }));
        }
        dataSourceFieldsChange && dataSourceFieldsChange(params)
      }}
      onSizeChange={(size) => {
        localStorage.setItem('size', size); //设置全局表格规格缓存
        setsize(size);
      }}
      columns={
        resizeable
          ? columnes?.filter?.((it) => ['split', 'nosubmit'].indexOf(it.valueType) == -1) ?? []
          : columncs?.filter?.((it) => ['split', 'nosubmit'].indexOf(it.valueType) == -1) ?? []
      }
      style={style || {}}
      actionRef={actionRefs}
      formRef={formRefs}
      rowKey={rowKey ?? 'id'} //表格每行数据的key
      dateFormatter="string"
      scroll={
        x
          ? {
            x: x,
          }
          : {}
      }
      pagination={
        pagination
          ? {
            showTotal: (total, range) => <span>共{total}条</span>,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [5, 10, 15, 30, 50, 100, 200],
            defaultPageSize: pageSize || 15,
          }
          : false
      }
      search={{
        filterType: 'light', //轻量模式
        placement: 'bottomLeft',
      }}
    />
  );
};

export default memo(Mtable);
