/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-18 15:10:18
 * @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 { KCInput } from '@/components/KCInput';
import KCTable from '@/components/kcTable';
import { getAllHosp } from '@/service/hospList';
import { ModalForm, ProFormDigit, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Popconfirm, TreeProps } from 'antd';
import { useEffect, useState } from 'react';
import { getData, PubDicTypeData } from '../pubDicTypeMana/service';
import { addPubDicRelaTbaleData, delData, editPubDicRelaTbaleData, getLeftData, getPubDicRelaTbaleData, initReq } from './service';

import { useLocation } from 'umi';
import './style.less';
import { getDeepestTreeData } from '@/utils';

import expandedIcon from '../../../../../public/images/treenode_open.png';
import closeIcon from '../../../../../public/images/treenode_collapse.png';
import { createFromIconfontCN } from '@ant-design/icons';
import { DataNode } from 'antd/lib/tree';
import DirectoryTree from 'antd/es/tree/DirectoryTree';

const SearchIcon = createFromIconfontCN({
  scriptUrl: '',
});

let systemId = '';
const currentSelectedTab = localStorage.getItem('currentSelectedTab');
if (currentSelectedTab) {
  const { systemId: id } = JSON.parse(currentSelectedTab as string);
  systemId = id;
}

const PubDicMana = () => {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<{
    current: number;
    pageSize: number;
    name?: string;
  }>({
    current: 1,
    pageSize: 10
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [reload, set_reload] = useState(false);

  const [treeData, set_treeData] = useState<any[]>([]);
  const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<any | undefined>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [pageType, set_pageType] = useState<undefined | number>(undefined); // 1 公用字典 2 院区公用字典
  const location = useLocation();

  const defaultColumns = [
    {
      title: '项目名称',
      dataIndex: 'name',
    },
    {
      title: '项目代码',
      dataIndex: 'code',
    },
    {
      title: '项目值',
      dataIndex: 'value',
    },
    {
      title: '默认',
      dataIndex: 'data.0.dictDefault',
      render: (_: any, record: any) => {
        return record.dictDefault == 1 ? '是' : '否';
      },
    },
    {
      title: '序号',
      dataIndex: pageType == 1 ? 'dictSort' : 'sort',
    },
    {
      title: '扩展1',
      dataIndex: 'expandOne',
    },
    {
      title: '扩展2',
      dataIndex: 'expandTwo',
    },
  ];

  const options = [
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm title="是否确认删除？" key="del" onConfirm={() => delTableData(record)}>
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const [columns, set_columns] = useState<any[]>([]);

  const getTableData = async (params: any) => {
    const { dictType, systemId } = currentSelectedTreeNode;

    if (dictType && pageType) {
      const resp = await getPubDicRelaTbaleData({ ...params, dictType: params.dictType ? params.dictType : currentSelectedTreeNode.dictType, systemId }, pageType);
      set_reload(false);
      if (resp) {
        return {
          data: resp.list,
          success: true,
          total: resp.totalCount,
        };
      }
    }
    return [];
  };

  const delTableData = async (record: any) => {
    if (pageType) {
      const resp = await delData(pageType == 1 ? record.dictDataId : record.id, pageType);
      if (resp) {
        set_reload(true);
      }
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const currentSelectedHop = localStorage.getItem('currentSelectedSubHop');
    const { systemId: parentId } = currentSelectedTreeNode;
    let hospId = '0';
    if (currentSelectedHop && pageType == 2) {
      const { id } = JSON.parse(currentSelectedHop);
      hospId = id;
    }
    if (type == 'EDIT' && pageType) {
      const resp = await editPubDicRelaTbaleData(
        pageType == 1 ? { ...formVal, systemId: parentId, hospId, dictType: currentSelectedTreeNode?.dictType } : { ...formVal, systemId: parentId, hospId, type: currentSelectedTreeNode?.dictType },
        pageType,
      );
      if (resp) {
        set_reload(true);
      }
    }
    if (type == 'ADD' && pageType) {
      const resp = await addPubDicRelaTbaleData(
        pageType == 1 ? { ...formVal, systemId: parentId, hospId, dictType: currentSelectedTreeNode?.dictType } : { ...formVal, systemId: parentId, hospId, type: currentSelectedTreeNode?.dictType },
        pageType,
      );
      if (resp) {
        set_reload(true);
      }
    }

    return true;
  };

  const UpDataActBtn = ({ record, type }: { record: any; type: 'EDIT' | 'ADD' }) => {
    let tableFileNames = [];
    if (currentSelectedTreeNode) {
      const { topic = '' } = currentSelectedTreeNode;
      const titles = topic.split('|');
      if (topic && titles.length == 7) {
        tableFileNames = titles;
      }
    }
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}公用字典(${currentSelectedTreeNode?.dictName})`}
        width={352}
        initialValues={type == 'EDIT' ? { ...record } : {}}
        trigger={type == 'EDIT' ? <a key="edit">编辑</a> : <span className="add">新增</span>}
        onFinish={(val) => {
          return updateTable(type == 'EDIT' ? (pageType == 1 ? { ...val, dictDataId: record.dictDataId } : { ...val, id: record.id }) : val, type);
        }}
      >
        <ProFormText name="name" label={tableFileNames.length == 7 ? `${tableFileNames[0]}：` : '名称：'} placeholder="请输入" rules={[{ required: true, message: '名称不能为空!' }]} />
        <ProFormText name="code" label={tableFileNames.length == 7 ? `${tableFileNames[1]}：` : '代码：'} placeholder="请输入" rules={[{ required: true, message: '代码不能为空!' }]} />
        <ProFormText name="value" label={tableFileNames.length == 7 ? `${tableFileNames[2]}：` : '对应值：'} placeholder="请输入" />
        <ProFormRadio.Group
          name={pageType == 1 ? 'dictDefault' : 'defaultFlag'}
          label={tableFileNames.length == 7 ? `${tableFileNames[3]}：` : '默认：'}
          fieldProps={{
            buttonStyle: 'solid',
          }}
          options={[
            {
              label: '是',
              value: 1,
            },
            {
              label: '否',
              value: 0,
            },
          ]}
          rules={[{ required: true, message: '默认不能为空!' }]}
        />
        <ProFormDigit label={tableFileNames.length == 7 ? `${tableFileNames[4]}：` : '顺序号：'} name={pageType == 1 ? 'dictSort' : 'sort'} rules={[{ required: true, message: '顺序号不能为空!' }]} />

        {true && (
          <>
            <ProFormText name="expandOne" label={tableFileNames.length == 7 ? `${tableFileNames[5]}：` : '扩展一：'} placeholder="请输入" />
            <ProFormText name="expandTwo" label={tableFileNames.length == 7 ? `${tableFileNames[6]}：` : '扩展二：'} placeholder="请输入" />
          </>
        )}
      </ModalForm>
    );
  };

  const handleTableChange = (pagination: any) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: pagination.current,
      pageSize: pagination.pageSize
    });
  }

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: 1,
      [`${paramName}`]: tableDataSearchKeywords
    });
  }

  const getTreeReqFunc = async (type: number) => {
    const resp = await getLeftData(type);
    const transformResp = resp.map((a: any, index: number) => {
      return {
        code: Math.random(),
        name: a.systemName,
        systemId: a.systemId,
        children: a.dictTypeList.map((b: any, num: number) => ({ ...b, name: b.dictName, code: Math.random() })),
      };
    });
    set_treeData(transformResp);
  };

  const dataList: any[] = [];

  const getParentKey = (key: React.Key, tree: any[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item: { code: React.Key }) => item.code === key)) {
          parentKey = node.code;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey!;
  };

  const generateList = (data: any[]) => {
    if (!data) return;
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const { code, name } = node;
      dataList.push({ code, name: name });
      if (node.children) {
        generateList(node.children);
      }
    }
  };
  generateList(treeData as any);

  const onTreeSearchKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    const newExpandedKeys = dataList.map((item) => {
      if (item.name.indexOf(value) > -1) {
        return getParentKey(item.code, treeData);
      }
      return null;
    });

    const b = newExpandedKeys.filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    //console.log('selected', selectedKeys, info);
    const { node } = info;
    if (!node.children) {
      set_currentSelectedTreeNode(node);
    }
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const initFunction = () => {
    Modal.confirm({
      title: '注意',
      content: '初始化操作会覆盖已有的字典数据并根据默认数据生成字典数据，确定继续操作？',
      onOk: async (...args) => {
        if (currentSelectedTreeNode) {
          const { systemId, dictType } = currentSelectedTreeNode;
          const resp = await initReq(systemId, dictType);
          if (resp) {
            set_reload(true);
            message.success('初始化成功！');
          }
        }
      },
    });
  };

  useEffect(() => {
    if (currentSelectedTreeNode) {
      const { topic = '' } = currentSelectedTreeNode;
      const titles = topic.split('|');
      if (topic && titles.length == 7) {
        const newColumns = defaultColumns.map((a, index) => ({
          ...a,
          title: titles[index],
        }));
        set_columns([...newColumns, ...options]);
      } else {
        set_columns([...defaultColumns, ...options]);
      }
      set_reload(true);
    }
  }, [currentSelectedTreeNode]);

  useEffect(() => {
    //初始化左侧树结构数据后

    if (treeData?.length > 0) {
      if (treeData[0].children && treeData[0].children.length > 0) {
        const [node, nodeParent] = getDeepestTreeData(treeData[0], 'children');

        set_currentSelectedTreeNode(node);
        setExpandedKeys([nodeParent.code]);
      }
    }
  }, [treeData]);

  useEffect(() => {
    const { pathname } = location;
    if (pathname == '/platform/setting/pubDicMana/1') set_pageType(1);
    if (pathname == '/platform/setting/pubDicMana/2') set_pageType(2);
  }, [location]);

  useEffect(() => {
    if (pageType) getTreeReqFunc(pageType);
  }, [pageType]);

  return (
    <div className="PubDicMana">
      <div className="left">
        <div className="search">
          <Input className="searchInput" placeholder="请输入" size="small" allowClear style={{ marginBottom: 16 }} onChange={onTreeSearchKeyChange} suffix={<SearchIcon type="iconsousuo" />} />
        </div>
        <div className="wrap">
          {treeData && treeData.length > 0 && (
            <DirectoryTree
              fieldNames={{ title: 'name', key: 'code' }}
              rootStyle={{ height: '100%', paddingBottom: 50 }}
              onSelect={onSelect}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              selectedKeys={currentSelectedTreeNode ? [currentSelectedTreeNode.code] : []}
              blockNode={true}
              icon={() => null}
              titleRender={(nodeData: any) => {
                const strTitle = nodeData.name as string;
                const index = strTitle.indexOf(searchValue);
                const beforeStr = strTitle.substring(0, index);
                const afterStr = strTitle.slice(index + searchValue.length);

                const title =
                  index > -1 ? (
                    <span>
                      {beforeStr}
                      <span className="site-tree-search-value" style={{ color: 'red', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                        {searchValue}
                      </span>
                      {afterStr}
                    </span>
                  ) : (
                    <span className="strTitle">{strTitle}</span>
                  );
                return (
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'row',
                      width: '100%',
                      justifyContent: 'flex-start',
                      alignItems: 'center',
                      height: 32,
                      borderRadius: '4px',
                      overflow: 'hidden',
                      color: '#17181A',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {title}
                  </div>
                );
              }}
              defaultSelectedKeys={[treeData[0].children[0].code]}
              treeData={treeData as unknown as DataNode[]}
              // treeData={treeDataNew}

              switcherIcon={(props: any) => {
                const { expanded } = props;
                //return <button className='site-table-row-expand-icon site-table-row-expand-icon-expanded'></button>
                return !expanded ? (
                  <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={expandedIcon} />
                ) : (
                  <img style={{ width: 20, height: 20, position: 'relative', top: 5 }} src={closeIcon} />
                );
              }}
            />
          )}
        </div>
      </div>
      <div className="right">
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem">
              <span className="label">检索：</span>
              <KCInput
                placeholder={'请输入项目名称'}
                style={{ width: 160 }}
                search
                allowClear
                onChange={(e) => {
                  set_tableDataSearchKeywords(e.target.value);
                  if (e.target.value.length == 0) {
                    set_tableDataFilterParams(
                      pageType == 1
                        ? {
                            ...tableDataFilterParams,
                            current: 1,
                            typeName: '',
                          }
                        : { ...tableDataFilterParams, current: 1, dictName: '' },
                    );
                  }
                }}
                onSearch={() => tableDataSearchHandle(pageType == 1 ? 'typeName' : 'dictName')}
              />
            </div>
          </div>
          <div className="btnGroup">
            {pageType == 2 && (
              <span className="initBtn" onClick={() => initFunction()}>
                初始化
              </span>
            )}
            <UpDataActBtn record type="ADD" />
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          {currentSelectedTreeNode && (
            <KCTable
              columns={columns}
              scroll={{ y: `calc(100vh - 250px)` }}
              reload={reload}
              rowKey="id"
              newVer
              params={tableDataFilterParams}
              request={(params) => getTableData(params)}
              onChange={handleTableChange}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default PubDicMana;
