/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-08-16 10:29:24
 * @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,
  ProFormInstance,
  useRefFunction,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import {
  Dropdown,
  Input,
  MenuProps,
  message,
  Modal,
  Switch,
  Tooltip,
  Popconfirm,
} from 'antd';
import { ColumnsType } from 'antd/es/table/interface';
import { TransferItem, TransferProps } from 'antd/es/transfer';
import { Key } from 'react';
import { useEffect, useRef, useState } from 'react';

import {
  getLeftList,
  getClolumnTableData,
  addLeftList,
  editLeftList,
  editReportTbaleData,
  delLeftReportData,
  batchDelTableData,
  addReportTbaleData,
  delData,
  getEmpCostTypeDict,
  updateEmpInfo,
  importDataPost,
  generateTableData,
} from './service';
import FormItem from 'antd/es/form/FormItem';

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 TableSelecter from './tableSelector';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq } from '@/utils/tooljs';
const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

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

const PersonnelClassificationMana = () => {
  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 [currentEditLeftData, set_currentEditLeftData] = useState<
    any | undefined
  >(undefined);

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

  const tableRef = useRef<ActionType>();

  const column: ProColumns[] = [
    {
      title: '工号',
      ellipsis: true,
      dataIndex: 'account',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '科室代码',
      dataIndex: 'departmentCode',
    },
    {
      title: '科室名称',
      dataIndex: 'departmentName',
    },
    {
      title: '岗位',
      dataIndex: 'positionName',
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <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 { costTypeCode } = params;
    if (costTypeCode) {
      const resp = await getClolumnTableData({ ...params });
      if (resp) {
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
          pageSize: resp.pageSize,
          totalPage: resp.totalPage,
        };
      }
    }
    return [];
  };

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

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

  const delTableData = async (id: number) => {
    const resp = await delData(id);
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const batchDelHandle = async () => {
    const resp = await batchDelTableData(selectedRowKeys);
    if (resp) {
      message.success('操作成功！');
      set_selectedRowKeys([]);
      tableRef.current?.reload();
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any[]) => {
    const result = rows.map((a, index) => ({
      costTypeCode: _currentSelectedType.costTypeCode,
      userId: a.id,
      account: a.account,
      name: a.name,
      departmentCode: a.departmentCode,
      departmentName: a.departmentName,
      position: a.position,
      positionName: a.positionName,
    }));
    const resp = await addReportTbaleData(result);
    if (resp) {
      message.success('操作成功');
      set_tableSelecterVisible(false);
      tableRef.current?.reload();
    }
  };

  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 addLeftList({
        //costTypeCode: formVal.costTypeCode,
        costTypeName: formVal.costTypeName,
        computeType: formVal.computeType.value,
        computeTypeName: formVal.computeType.label,
        description: formVal.description,
      });
      if (resp) {
        getPageLeftReports();
      }
    }

    if (type == 'EDIT_LEFTDATA') {
      const resp = await editLeftList({
        id: formVal.id,
        costTypeName: formVal.costTypeName,
        computeType: formVal.computeType.value,
        computeTypeName: formVal.computeType.label,
        description: formVal.description,
      });
      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) {
        tableRef.current?.reload();
      }
    }

    return true;
  };

  const downloadTemplate = async () => {
    await downloadTemplateReq('/costAccount/setting/exportEmpType');
  };

  const importData = () => {
    return (
      <ModalForm
        width={360}
        title={`导入数据`}
        trigger={
          <a className="import" key="3">
            导入
          </a>
        }
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [...needBtn];
          },
        }}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          const resp = await importDataPost(formData);

          if (resp) {
            getPageLeftReports();
            return true;
          }
        }}
      >
        <FormItem name={'importFile'}>
          <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
        </FormItem>
      </ModalForm>
    );
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADD_LEFTDATA' | 'EDIT_LEFTDATA';
  }) => {
    const formRef = useRef<ProFormInstance>();
    const getTrriger = () => {
      if (type == 'ADD') {
        return <span className="add">新增</span>;
      }
      if (type == 'EDIT') {
        return <a key="edit">编辑</a>;
      }
      if (type == 'ADD_LEFTDATA') {
        return <span className="add">新增</span>;
      }
      if (type == 'EDIT_LEFTDATA') {
        return <a key="edit">编辑</a>;
      }
    };

    return (
      <ModalForm
        formRef={formRef}
        title={type == 'ADD_LEFTDATA' ? `新增人事分类` : `编辑人事分类`}
        width={352}
        initialValues={
          type == 'EDIT_LEFTDATA' ? { ...record } : { computeTypeName: '' }
        }
        trigger={getTrriger()}
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT_LEFTDATA' ? { ...record, ...val } : val,
            type,
          );
        }}
      >
        <ProFormText
          label="人事分类名称："
          name="costTypeName"
          rules={[{ required: true, message: '人事分类名称不能为空!' }]}
        />
        {/* <ProFormText
                    label='人事分类代码：'
                    name='costTypeCode'
                    rules={[{ required: true, message: '人事分类代码不能为空!' }]}
                /> */}
        <ProFormSelect
          name="computeType"
          label="子级类型："
          placeholder="请选择"
          request={async () => {
            const resp = await getEmpCostTypeDict();
            if (resp) {
              return resp.map((a: any) => ({ label: a.name, value: a.code }));
            }
            return [];
          }}
          fieldProps={{
            labelInValue: true,
            onChange(value, option: any) {
              // console.log({value,option})
              // const {label} = option;
              // console.log({label});
              // formRef.current?.setFieldValue('computeTypeName',label);
            },
          }}
          rules={[{ required: true, message: '子集类型不能为空!' }]}
        />
        <ProFormTextArea label="说明：" name="description" />
      </ModalForm>
    );
  };

  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>
      ),
    },
  ];

  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 tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      [`${paramName}`]: tableDataSearchKeywords,
    });
  };

  const updateEmpInfoHandle = async () => {
    const resp = await updateEmpInfo();
    if (resp) {
      message.success('更新成功！');
      tableRef.current?.reload();
    }
  };

  const generateEmpHandle = () => {
    Modal.confirm({
      title: '注意',
      content: '生成操作会覆盖现有的人事分类及对应人员信息，确定要继续操作?',
      onOk: async (...args) => {
        const resp = await generateTableData();
        if (resp) {
          getPageLeftReports();
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      },
    });
  };

  const items: MenuProps['items'] = [
    {
      key: '1',
      label: (
        <UpDataActBtn key={'act'} record={undefined} type="ADD_LEFTDATA" />
      ),
    },
    {
      key: '2',
      label: importData(),
    },
  ];

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

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

  useEffect(() => {
    if (ifEditTable) {
      set_tableColumn([...column]);
    } else {
      set_tableColumn(column);
    }
  }, [ifEditTable]);

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

  return (
    <KCIMPagecontainer title={false} className="PersonnelClassificationMana">
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="添加单元人员信息"
        rowKey={'id'}
        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={{ width: 156 }}
            onChange={(e) => {
              const result = typeList.filter(
                (item) => item.costTypeName.indexOf(e.target.value) != -1,
              );
              set_showTypeListArr(result);
            }}
          />
          <Dropdown menu={{ items }} placement="bottomLeft">
            <div className="add">
              <img
                src={require('../../../../../static/addIcon_black.png')}
                alt=""
              />
            </div>
          </Dropdown>
        </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.costTypeName}>
                    <div className="name">{item.costTypeName}</div>
                    <div className="sub">{item.computeTypeName}</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 className="filterItem" style={{ marginLeft: 16, width: 205 }}>
              <span className="label" style={{ whiteSpace: 'nowrap' }}>
                {' '}
                检索：
              </span>
              <Input
                placeholder={'输入工号,姓名'}
                allowClear
                autoComplete="off"
                suffix={
                  <IconFont
                    type="iconsousuo"
                    style={{ color: '#99A6BF' }}
                    onClick={() => tableDataSearchHandle('filter')}
                  />
                }
                onChange={(e) => {
                  set_tableDataSearchKeywords(e.target.value);
                  if (e.target.value.length == 0) {
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      filter: '',
                    });
                  }
                }}
                onPressEnter={(e) => {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    filter: (e.target as HTMLInputElement).value,
                  });
                }}
              />
            </div>
          </div>
          <div className="btnGroup">
            <span className="update" onClick={() => generateEmpHandle()}>
              按人员类别生成
            </span>
            <span className="update" onClick={() => updateEmpInfoHandle()}>
              更新人员信息
            </span>
            <span
              className="add"
              onClick={() => set_tableSelecterVisible(true)}
            >
              添加
            </span>
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          {currentSelectedType && (
            <KCIMTable
              actionRef={tableRef}
              columns={tableColumn}
              scroll={{ y: `calc(100vh - 233px)` }}
              rowKey="id"
              request={(params) => getTableData(params)}
              tableAlertRender={false}
              params={tableDataFilterParams}
              rowSelection={{
                onChange(selectedRowKeys, selectedRows, info) {
                  set_selectedRowKeys(selectedRowKeys);
                },
              }}
            />
          )}
        </div>
      </div>
    </KCIMPagecontainer>
  );
};

export default PersonnelClassificationMana;
