/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-11-14 14:55:02
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { createFromIconfontCN } from '@ant-design/icons';
import {
  ActionType,
  arrayMoveImmutable,
  ProFormRadio,
  useRefFunction,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDependency,
  ProFormInstance,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import {
  Dropdown,
  Input,
  MenuProps,
  message,
  Switch,
  Tooltip,
  Popconfirm,
  Form,
} from 'antd';
import { ColumnsType } from 'antd/es/table/interface';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { Key, ReactNode } from 'react';
import { useEffect, useRef, useState } from 'react';

import {
  getReportColumn,
  getClolumnTableData,
  addReport,
  editReport,
  editReportTbaleData,
  delLeftReportData,
  batchDelTableData,
  addReportTbaleData,
  delData,
} from './service';

import './style.less';

import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';

import '../../../../utils/zhongtaiB';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { getTargetDic } from '@/services/auth';
import TableSelecter from './tableSelector';
import UpDateActBtn from '../reportColumnMana/UpDateActBtn';
const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

var temp_dataSource: any[] = [];
let _currentSelectedType: any = undefined;

const reportListMana = () => {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const [selectedRowKeys, set_selectedRowKeys] = useState<Key[]>([]);
  const [typeList, set_typeList] = useState<any[]>([]);
  const [showTypeListArr, set_showTypeListArr] = useState<any[]>([]);
  const [currentSelectedType, set_currentSelectedType] = useState<
    any | undefined
  >(undefined);

  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const SortableItem = SortableElement((props: any) => <tr {...props} />);
  const SortContainer = SortableContainer((props: any) => <tbody {...props} />);

  const [currentEditLeftData, set_currentEditLeftData] = useState<
    any | undefined
  >(undefined);

  const [ifEditTable, set_ifEditTable] = useState(true);

  const tableRef = useRef<ActionType>();

  const DragHandle = SortableHandle(() => (
    <img
      width={16}
      style={{ cursor: 'pointer' }}
      src={require('../../../../../static/tuozhuai_icon.png')}
      alt=""
    />
  ));

  const column: ProColumns[] = [
    {
      title: '列名称',
      width: 120,
      ellipsis: true,
      dataIndex: 'columnName',
    },
    {
      title: '列标题',
      width: 160,
      dataIndex: 'columnHeaderText',
    },
    {
      title: '主键',
      dataIndex: 'primaryKey',
      renderText: (_: any, record: any) => {
        return (
          <Switch
            disabled={!ifEditTable}
            size="small"
            checked={_ ? true : false}
            onChange={(bool) => switchChangeHandle(bool, record, 'primaryKey')}
          />
        );
      },
    },
    {
      title: '隐藏',
      dataIndex: 'hide',
      renderText: (_: any, record: any) => {
        return (
          <Switch
            disabled={!ifEditTable}
            size="small"
            checked={_}
            onChange={(bool) => switchChangeHandle(bool, record, 'hide')}
          />
        );
      },
    },
    {
      title: '冻结',
      dataIndex: 'freeze',
      renderText: (_: any, record: any) => {
        return (
          <Switch
            disabled={!ifEditTable}
            size="small"
            checked={_ == '1'}
            onChange={(bool) => switchChangeHandle(bool, record, 'freeze')}
          />
        );
      },
    },
    {
      title: '排序',
      dataIndex: 'sortStatus',
      renderText: (_: any, record: any) => {
        return (
          <Switch
            disabled={!ifEditTable}
            size="small"
            checked={_ == '1'}
            onChange={(bool) => switchChangeHandle(bool, record, 'sortStatus')}
          />
        );
      },
    },
    {
      title: '检索',
      dataIndex: 'search',
      renderText: (_: any, record: any) => {
        return (
          <Switch
            disabled={!ifEditTable}
            size="small"
            checked={_ == '1'}
            onChange={(bool) => switchChangeHandle(bool, record, 'search')}
          />
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 90,
      valueType: 'option',
      renderText: (_: any, record: any) => {
        return [
          <UpDateActBtn
            record={{ ...record, id: null, request: true }}
            type="EDIT"
            onUpdated={() =>
              getTableData({ reportCode: _currentSelectedType.code })
            }
          />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record.id)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const [tableColumn, set_tableColumn] = useState<ProColumns[] | any[]>(column);

  const getTableData = async (params: any) => {
    const { reportCode } = params;

    if (reportCode) {
      const resp = await getClolumnTableData({
        ...params,
        pageSize: 500,
        current: 1,
      });
      if (resp) {
        //const dataSorted = resp.sort((prev:any,cur:any)=>prev.sort - cur.sort);
        setDataSource(resp.list);
        temp_dataSource = [...resp.list];
      }
    }
  };

  const switchChangeHandle = (checked: boolean, record: any, key: string) => {
    const newData = temp_dataSource.map((a: any) => {
      if (a.id == record.id) {
        return { ...a, [`${key}`]: checked ? 1 : 0 };
      }
      return a;
    });

    setDataSource([...newData]);
    updateTable(undefined, 'EDIT', newData);
  };

  //获取左侧单元
  const getPageLeftReports = async () => {
    const resp = await getReportColumn();

    if (resp) {
      set_typeList(resp);
      set_showTypeListArr(resp);
    }
  };

  const delTableData = async (id: number) => {
    const resp = await delData(id);
    if (resp) {
      message.success('操作成功！');
      getTableData({ reportCode: _currentSelectedType.code });
    }
  };

  const batchDelHandle = async () => {
    const resp = await batchDelTableData(selectedRowKeys);
    if (resp) {
      message.success('操作成功！');
      set_selectedRowKeys([]);
      getTableData({ reportCode: _currentSelectedType.code });
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any[]) => {
    const result = rows.map((a, index) => ({
      reportCode: _currentSelectedType.code,
      columnCode: a.code,
      columnHeaderText: a.headerText,
      columnName: a.name,
      sort: index + 1,
    }));
    const resp = await addReportTbaleData(result);
    if (resp) {
      message.success('操作成功');
      set_tableSelecterVisible(false);
      getTableData({ reportCode: _currentSelectedType.code });
    }
  };

  const updateTable = async (
    formVal: any,
    type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA',
    data?: any[],
  ) => {
    // console.log({ formVal, type });

    if (type == 'ADD_LEFTDATA') {
      const resp = await addReport({
        name: formVal.name,
        shortName: formVal.shortName,
        type: formVal.type,
        indexType: formVal.indexType,
        reportIndex: formVal.variableList,
      });
      if (resp) {
        getPageLeftReports();
      }
    }

    if (type == 'EDIT_LEFTDATA') {
      const resp = await editReport({
        id: formVal.id,
        name: formVal.name,
        shortName: formVal.shortName,
        type: formVal.type,
        indexType: formVal.indexType,
        reportIndex: formVal.variableList,
      });
      if (resp) {
        getPageLeftReports();
      }
    }

    if (type == 'EDIT') {
      let newDataSource = data?.map((a: any, index: number) => {
        //更新排序
        return { ...a, sort: index + 1 };
      });
      const resp = await editReportTbaleData(newDataSource);
      if (resp) {
        getTableData({ reportCode: _currentSelectedType.code });
      }
    }

    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA';
  }) => {
    const [rows, set_rows] = useState<any[]>([]);
    const [form] = Form.useForm(); // 创建表单实例

    const getTrriger = () => {
      if (type === 'ADD') {
        return <span className="add">新增</span>;
      }
      if (type === 'EDIT') {
        return <a key="edit">编辑</a>;
      }
      if (type === 'ADD_LEFTDATA') {
        return (
          <div className="add">
            <img
              src={require('../../../../../static/addIcon_black.png')}
              alt=""
            />
          </div>
        );
      }
      if (type === 'EDIT_LEFTDATA') {
        return <a key="edit">编辑</a>;
      }
    };

    // 初始化表单和 rows 数据
    useEffect(() => {
      if (
        type === 'EDIT_LEFTDATA' &&
        record?.reportIndex &&
        record.indexType === 2
      ) {
        // 初始化 rows 数据
        const initialRows = record.reportIndex.map((a: any) => ({
          id: a.id,
          varName: a.columnIndex,
          tip: a.tips,
        }));
        set_rows(initialRows);

        // 设置表单的初始值
        const initialValues = record.reportIndex.reduce(
          (acc: any, item: any) => {
            acc[`varName_${item.id}`] = item.columnIndex;
            acc[`tip_${item.id}`] = item.tips;
            return acc;
          },
          {},
        );
        // console.log({ initialValues });
        form.setFieldsValue({ ...record, ...initialValues });
      } else {
        if (type === 'ADD_LEFTDATA') {
          form.setFieldsValue({ ...record, indexType: 0 });
        } else {
          form.setFieldsValue({ ...record });
        }
      }
    }, [type, record, form]);

    // 处理表单变化的函数
    const handleValuesChange = (changedValues: any, allValues: any) => {
      const updatedRows = rows.map((row) => {
        if (allValues[`varName_${row.id}`] !== undefined) {
          row.varName = allValues[`varName_${row.id}`];
        }
        if (allValues[`tip_${row.id}`] !== undefined) {
          row.tip = allValues[`tip_${row.id}`];
        }
        return row;
      });
      set_rows(updatedRows); // 更新 rows 状态
    };

    const handleFinish = async (val: any) => {
      const formData = {
        ...val,
        variableList:
          val.indexType == 2
            ? rows.map((a: any) => ({ columnIndex: a.varName, tips: a.tip }))
            : null, // 将 rows 数组包含在提交的数据中
      };

      // 删除不需要的动态生成的表单字段
      Object.keys(formData).forEach((key) => {
        if (key.startsWith('varName_') || key.startsWith('tip_')) {
          delete formData[key];
        }
      });

      return updateTable(
        type === 'EDIT_LEFTDATA' ? { ...record, ...formData } : formData,
        type,
      );
    };

    return (
      <ModalForm
        form={form} // 绑定 form 实例
        title={type === 'ADD_LEFTDATA' ? `新增报表` : `编辑报表`}
        width={352}
        onFinish={handleFinish}
        trigger={getTrriger()}
        onValuesChange={handleValuesChange} // 添加表单变化处理
      >
        <ProFormText
          label="报表名称："
          name="name"
          rules={[{ required: true, message: '报表名称不能为空!' }]}
        />
        <ProFormText
          label="报表简称："
          name="shortName"
          rules={[{ required: true, message: '报表简称不能为空!' }]}
        />
        <ProFormSelect
          name="type"
          label="报表类型："
          placeholder="请选择"
          request={async () => {
            const resp = await getTargetDic('REPORT_TYPE');
            if (resp) {
              const { dataVoList } = resp;
              return dataVoList.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            }
            return [];
          }}
          rules={[{ required: true, message: '列类型不能为空!' }]}
        />

        <div style={{ display: 'flex', flexDirection: 'row' }}>
          <ProFormRadio.Group
            name="indexType"
            label={
              <>
                检索方式：
                <Tooltip
                  title={
                    <span>
                      无：不显示检索框;
                      <br />
                      主键检索：需在主键列SQL配置检索条件,最多可配置5个;
                      <br />
                      列检索：需选择要检索的列，只可在已展示数据里检索"
                    </span>
                  }
                >
                  <IconFont type="icon-jinggaotishi" />
                </Tooltip>
              </>
            }
            options={[
              { label: '无', value: 0 },
              { label: '列检索', value: 1 },
              { label: '主键检索', value: 2 },
            ]}
            rules={[{ required: true }]}
          />
        </div>

        <ProFormDependency name={['indexType']}>
          {({ indexType }) => {
            return (
              indexType === 2 && (
                <>
                  {/* 动态添加的行 */}
                  <div
                    className="rowWrap"
                    style={{ maxHeight: 247, overflowY: 'scroll' }}
                  >
                    {rows.map((item, index) => (
                      <div
                        key={index}
                        style={{
                          display: 'flex',
                          flexDirection: 'row',
                          justifyContent: 'space-between',
                          alignItems: 'center',
                        }}
                      >
                        <ProFormText
                          width={140}
                          label="变量名称："
                          name={`varName_${item.id}`} // 绑定唯一的 name 属性
                          placeholder="请输入"
                        />
                        <ProFormText
                          width={140}
                          label="提示文案："
                          name={`tip_${item.id}`} // 绑定唯一的 name 属性
                          placeholder="请输入"
                        />
                        <div
                          className="del"
                          onClick={() =>
                            set_rows((prevItems) =>
                              prevItems.filter((a) => a.id !== item.id),
                            )
                          }
                          style={{
                            display: 'flex',
                            width: 24,
                            height: 24,
                            justifyContent: 'center',
                            position: 'relative',
                            top: 2,
                            alignItems: 'center',
                            border: '1px solid #DAE2F2',
                            borderRadius: 4,
                            background: '#FAFCFF',
                            cursor: 'pointer',
                          }}
                        >
                          <IconFont type={'iconshanchu'} />
                        </div>
                      </div>
                    ))}
                  </div>
                  {rows.length <= 4 && (
                    <div
                      className="addBtn"
                      onClick={() =>
                        set_rows([
                          ...rows,
                          { id: Math.random(), varName: '', tip: '' },
                        ])
                      }
                      style={{
                        height: 40,
                        border: '1px dashed #CFD6E6',
                        borderRadius: 4,
                        color: '#3376FE',
                        display: 'flex',
                        flexDirection: 'row',
                        justifyContent: 'center',
                        alignItems: 'center',
                        cursor: 'pointer',
                      }}
                    >
                      <IconFont
                        style={{ paddingRight: 8 }}
                        type={'icon-zengjia'}
                      />
                      增加一行
                    </div>
                  )}
                </>
              )
            );
          }}
        </ProFormDependency>
      </ModalForm>
    );
  };

  interface DataType {
    key: string;
    title: string;
    description: string;
    disabled: boolean;
    tag: string;
  }

  interface TableTransferProps extends TransferProps<TransferItem> {
    dataSource: DataType[];
    leftColumns: ColumnsType<DataType>;
    rightColumns: ColumnsType<DataType>;
    record: any;
  }

  const moreItems: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <UpDataActBtn
          key={'act'}
          record={currentEditLeftData}
          type="EDIT_LEFTDATA"
        />
      ),
    },
    {
      key: '2',
      label: (
        <a
          onClick={async (e) => {
            e.preventDefault();
            const resp = await delLeftReportData(currentEditLeftData.id);
            if (resp) {
              getPageLeftReports();
            }
          }}
        >
          删除
        </a>
      ),
    },
    {
      key: '3',
      label: (
        <a
          onClick={async (e) => {
            e.preventDefault();
            // 选取要复制的文本
            const textToCopy = currentEditLeftData.code;

            // 创建一个临时的textarea元素
            const tempTextArea = document.createElement('textarea');
            tempTextArea.value = textToCopy;
            document.body.appendChild(tempTextArea);

            // 选中并复制文本
            tempTextArea.select();
            document.execCommand('copy');

            // 移除临时元素
            document.body.removeChild(tempTextArea);
            message.success('复制成功！');
          }}
        >
          复制报表code
        </a>
      ),
    },
  ];

  const onSortEnd = useRefFunction(
    ({ oldIndex, newIndex }: { oldIndex: number; newIndex: number }) => {
      if (oldIndex !== newIndex) {
        const newData = arrayMoveImmutable({
          array: [...dataSource],
          fromIndex: oldIndex,
          toIndex: newIndex,
        }).filter((el) => !!el);

        const updatedSortArr = newData.map((item: any, index: number) => ({
          ...item,
          sort: index,
        }));
        // setDataSource([...updatedSortArr]);
        updateTable(undefined, 'EDIT', updatedSortArr);
      }
    },
  );

  const DraggableContainer = (props: any) => (
    <SortContainer
      useDragHandle
      disableAutoscroll
      helperClass="row-dragging"
      onSortEnd={onSortEnd}
      {...props}
    />
  );

  const DraggableBodyRow = (props: any) => {
    const { className, style, ...restProps } = props;

    // function findIndex base on Table rowKey props and should always be a right array index
    const index = dataSource.findIndex(
      (x) => x.id === restProps['data-row-key'],
    );

    return <SortableItem index={index} {...restProps} />;
  };

  useEffect(() => {
    if (currentSelectedType) {
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        reportCode: currentSelectedType.code,
      });
      getTableData({ reportCode: currentSelectedType.code });
    }
  }, [currentSelectedType]);

  useEffect(() => {
    if (showTypeListArr.length > 0) {
      if (!currentSelectedType) {
        set_currentSelectedType(showTypeListArr[0]);
        _currentSelectedType = showTypeListArr[0];
        set_tableDataFilterParams({
          ...tableDataFilterParams,
          reportCode: showTypeListArr[0].code,
        });
      }
    }
  }, [showTypeListArr]);

  useEffect(() => {
    if (ifEditTable) {
      set_tableColumn([
        {
          dataIndex: 'sort',
          width: 60,
          className: 'drag-visible',
          render: () => <DragHandle />,
        },
        ...column,
      ]);
    } else {
      set_tableColumn(column);
    }
  }, [ifEditTable]);

  useEffect(() => {
    temp_dataSource = [...dataSource];
  }, [dataSource]);

  useEffect(() => {
    getPageLeftReports();
  }, []);

  return (
    <KCIMPagecontainer title={false} className="reportListMana">
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="添加"
        rowKey={'code'}
        defaultSelectedKeys={[]}
        record={_currentSelectedType}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      {selectedRowKeys.length > 0 && (
        <div className="bottomBar">
          <span>
            已选择<a>{selectedRowKeys.length}</a>项
          </span>
          <a onClick={() => batchDelHandle()}>批量删除</a>
        </div>
      )}
      <div className="left">
        <div className="toolbar">
          <Input
            placeholder={'报表名称'}
            allowClear
            autoComplete="off"
            suffix={<IconFont type="iconsousuo" style={{ color: '#99A6BF' }} />}
            style={{ width: 156 }}
            onChange={(e) => {
              const result = typeList.filter(
                (item) => item.name.indexOf(e.target.value) != -1,
              );
              set_showTypeListArr(result);
            }}
          />
          <UpDataActBtn key={'act'} record={undefined} type="ADD_LEFTDATA" />
        </div>

        <div className="wrap">
          {showTypeListArr.map((item, index) => {
            return (
              <div
                className={
                  currentSelectedType
                    ? currentSelectedType.id == item.id
                      ? 'type on'
                      : 'type'
                    : 'type'
                }
                key={index}
                onClick={() => {
                  set_currentSelectedType(item);
                  _currentSelectedType = item;
                }}
              >
                <img
                  className="icon"
                  src={require('../../../../../static/reportIcon.png')}
                  alt=""
                />
                <div className="content">
                  <Tooltip title={item.name}>
                    <div className="name">{item.name}</div>
                    <div className="sub">{item.typeName}</div>
                  </Tooltip>
                </div>

                <Dropdown
                  menu={{ items: moreItems }}
                  placement="bottom"
                  onOpenChange={(bool) => {
                    bool && set_currentEditLeftData(item);
                  }}
                >
                  <div className="more">
                    <img
                      src={require('../../../../../static/more_point_gray.png')}
                      alt=""
                    />
                  </div>
                </Dropdown>
              </div>
            );
          })}
        </div>
      </div>
      <div className="right">
        <div className="toolBar">
          <div className="filter"></div>
          <div className="btnGroup">
            {!ifEditTable && (
              <span className="manaBtn" onClick={() => set_ifEditTable(true)}>
                管理列
              </span>
            )}
            {ifEditTable && (
              <div className="inner">
                {/* <span className='save' onClick={() => updateTable(undefined, 'EDIT')}>保存</span> */}
                <span
                  className="add"
                  onClick={() => set_tableSelecterVisible(true)}
                >
                  添加
                </span>
              </div>
            )}
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          {currentSelectedType && (
            <KCIMTable
              actionRef={tableRef}
              columns={tableColumn}
              scroll={{ y: `calc(100vh - 233px)` }}
              rowKey="id"
              dataSource={dataSource}
              tableAlertRender={false}
              rowSelection={{
                onChange(selectedRowKeys, selectedRows, info) {
                  set_selectedRowKeys(selectedRowKeys);
                },
              }}
              components={{
                body: {
                  wrapper: DraggableContainer,
                  row: DraggableBodyRow,
                },
              }}
            />
          )}
        </div>
      </div>
    </KCIMPagecontainer>
  );
};

export default reportListMana;
