/*
 * @Author: your name
 * @Date: 2022-01-13 15:22:48
 * @LastEditTime: 2025-05-22 15:53:18
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/hospManage/index.tsx
 */

import { FC, Key, useEffect, useMemo, useState } from 'react';
import { hospManageModelState, ConnectProps, Loading, connect, useModel } from 'umi';
import { Button, Checkbox, Divider, Drawer, Dropdown, Input, Popconfirm, Switch, Table, Tree, TreeProps, message } from 'antd';
import KCTable from '@/components/kcTable';
import type { ProColumns } from '@ant-design/pro-table';
import { getAllHosp, getHospOwnSys, getHospYoushuAccounts, getMenuRelaPerm, hospInit, saveHospMenuApiPerm, setIfCheckAll, setReadOnly } from '@/service/hospList';
import { TableRequestParamsType } from '@/typings';
import ActModal from './modals/modal';
import './style.less';
import { TableListItem } from './typings';
import { getSpacifyHospMenu } from '@/service/menu';
import { KCInput } from '@/components/KCInput';
import { createFromIconfontCN, DownOutlined } from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import { DataNode } from 'antd/es/tree';
import { getTableDataRequest, getTreeDataRespType } from '../systemNavMana/service';

import expandedIcon from '../../../../../public/images/treenode_open.png';
import closeIcon from '../../../../../public/images/treenode_collapse.png';
import { getDeepestTreeData, uniqueFunc } from '@/utils';
import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import NavSelecter, { NavSelecterData, NavSelecterItemType } from '@/components/NavSelecter';
import { FastEntryTabType } from '@/pages/index/components/FastEntry';

export enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
  EDITMENU,
  BINDACCOUNT, //绑定有数账号
}

const { DirectoryTree } = Tree;

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

interface PageProps extends ConnectProps {
  hospManageModel: hospManageModelState;
  loading: boolean;
}

interface TreeNode {
  [key: string]: any;
  children?: TreeNode[];
}

export function findParents(nodes: TreeNode[], targetId: string, path: TreeNode[] = []): TreeNode[] | null {
  for (const node of nodes) {
    if (node.menuId == targetId) {
      return path;
    }

    if (node.children) {
      const result = findParents(node.children, targetId, [...path, node]);
      if (result) return result;
    }
  }

  return null;
}

export function extractAttributeValues(tree: TreeNode, attributeName: keyof TreeNode): any[] {
  let values: any[] = [];

  // 提取当前节点的属性值
  values.push(tree[attributeName]);

  // 如果当前节点有子节点，递归处理每个子节点
  if (tree.children) {
    for (const child of tree.children) {
      values = values.concat(extractAttributeValues(child, attributeName));
    }
  }

  return values;
}

const DrawerActBtn = ({ record }: { record: any }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [treeData, set_treeData] = useState<getTreeDataRespType[]>([]);
  const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<any | undefined>(undefined);
  const [drawerTablereload, set_drawerTablereload] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);
  const [drawerTableDataFilterParams, set_drawerTableDataFilterParams] = useState<any | undefined>();

  const [checkBoxCodes, set_checkBoxCodes] = useState<any[]>([]); //勾选的菜单
  const [drawerTableDataSearchKeywords, set_drawerTableDataSearchKeywords] = useState<string>('');

  const [checkedTableMenuIds, set_checkedTableMenuIds] = useState<any[]>([]);

  const [oldSelectedMenuIds, set_oldSelectedMenuIds] = useState<any[]>([]);

  const [checkedMenuParentsIds, set_checkedMenuParentsIds] = useState<Key[]>([]); //所有需要保存的菜单id

  const [drawerVisible, set_drawerVisible] = useState(false);

  const [ifFrozze, set_ifFrozze] = useState(false); //冻结勾选菜单及功能操作

  const [hospAllMenuTree, set_hospAllMenuTree] = useState<any[]>([]); //医院全量菜单

  const [expandedRowKeys, set_expandedRowKeys] = useState<Key[]>([]);

  const columnsData: ProColumns<TableListItem>[] = [
    {
      title: '名称',
      dataIndex: 'name',
      width: 300,
      ellipsis: true,
    },
    {
      title: '类型',
      width: 50,
      dataIndex: 'contentType',
      key: 'contentType',
      render: (_: any, record: any) => {
        //console.log({ record });
        switch (record.type) {
          case 0:
            return '目录';
          case 1:
            return '菜单';
          case 2:
            return 'api';
          case 3:
            return '系统';
          case 4:
            return '有数bi';
          case 5:
            return '体系';
          case 6:
            return '中心层';
          case 7:
            return '平台层';
          default:
            break;
        }
      },
    },
    {
      title: '功能',
      dataIndex: 'deptName',
      key: 'deptName',
      render: (_: any, record: any) => {
        if (record.functionList) {
          const options = record.functionList.map((item: any, index: number) => ({ label: item.name, value: item.code }));

          const needItem = checkBoxCodes.filter((a) => a.menuId == record.menuId);

          const codes = needItem && needItem.length > 0 && needItem[0].function ? needItem[0].function.map((a: any) => a.code) : [];

          const onCheckGroupChange = (checkedValue: CheckboxValueType[]) => {
            if (checkedValue.length > 0) {
              const _temp = [...checkBoxCodes];
              const index = checkBoxCodes.findIndex((item) => item.menuId == record.menuId);
              const needed = options.filter((item: any) => checkedValue.includes(item.value));
              const transfered = needed.map((item: any) => ({ name: item.label, code: item.value }));

              if (index >= 0) {
                //先去除旧的的对象
                _temp.splice(index, 1);
              }

              _temp.push({
                menuId: record.menuId,
                function: transfered,
              });

              const thisParents = findParents(hospAllMenuTree, record.menuId);

              const ids = (thisParents as TreeNode[]).map((a) => a.menuId);

              set_checkedMenuParentsIds([...checkedMenuParentsIds, ...ids, record.menuId]);

              set_checkedTableMenuIds([...checkedMenuParentsIds, ...ids, record.menuId]);

              set_checkBoxCodes([..._temp]);
            } else {
              //取消选择
              const _temp = checkBoxCodes;
              const index = checkBoxCodes.findIndex((item) => item.menuId == record.menuId);

              _temp.splice(index, 1);

              // const menuIdsArr = _temp.map((item: any) => item.menuId);
              // set_checkedTableMenuIds([...menuIdsArr])
              set_checkBoxCodes([..._temp]);
            }
          };

          return <Checkbox.Group options={options} value={codes} disabled={ifFrozze} onChange={(checkedValue) => onCheckGroupChange(checkedValue)} />;
        }
        return '-';
      },
    },
  ];

  const getTreeReqFunc = async (hospId: string) => {
    if (hospId) {
      const resp = await getHospOwnSys(hospId);
      set_treeData(resp);
    }
  };

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

  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 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 onExpand = (newExpandedKeys: React.Key[]) => {
    setExpandedKeys(newExpandedKeys);
    setAutoExpandParent(false);
  };

  const generateList = (data: getTreeDataRespType[]) => {
    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 setInitCheckData = async () => {
    set_drawerTablereload(false);
    if (currentSelectedTreeNode) {
      const resp = await getMenuRelaPerm({ hospId: record.id, systemId: currentSelectedTreeNode.code });
      if (resp) {
        const { checkAll = 0, menuList = [] } = resp;
        let temp: { menuId: any; function: any }[] = [];

        const setTreeRecursion = (data: any) => {
          data.map((item: any, index: number) => {
            if (item.type == 1) {
              //菜单
              temp.push({
                menuId: item.menuId,
                function: item.functionCheckList,
              });
            }

            if (item.children && item.children.length != 0) {
              setTreeRecursion(item.children);
            }
          });
        };

        let initCheckedMenuIds: any[] = [];

        menuList.forEach((item: any) => {
          const ids = extractAttributeValues(item, 'menuId');
          initCheckedMenuIds = initCheckedMenuIds.concat(ids);
        });

        set_checkedMenuParentsIds(initCheckedMenuIds);

        setTreeRecursion(menuList);
        set_ifFrozze(checkAll ? true : false);

        set_checkBoxCodes(temp);
        set_checkedTableMenuIds(temp.map((a: any) => a.menuId));
        set_oldSelectedMenuIds(temp.map((a: any) => a.menuId));

        return {
          data: resp,
          success: true,
        };
      }
      return {
        data: [],
        success: true,
      };
    }

    return [];
  };

  const getTableData = async (params: any, sort: any, filter: any) => {
    console.log({ params });
    set_drawerTablereload(false);
    if (currentSelectedTreeNode) {
      const resp = await getTableDataRequest({ ...params, systemId: currentSelectedTreeNode.code });
      if (resp) {
        let expandKeys: Key[] = [];
        set_hospAllMenuTree(resp);

        const getParentsIds = (data: any) => {
          data.map((item: any, index: number) => {
            if (item.type == 0) {
              expandKeys.push(item.menuId);
            }

            if (item.children && item.children.length != 0) {
              getParentsIds(item.children);
            }
          });
        };

        getParentsIds(resp);
        set_expandedRowKeys(expandKeys);

        return {
          data: resp,
          success: true,
        };
      }
      return {
        data: [],
        success: true,
      };
    }

    return [];
  };

  const saveResult = async () => {
    let old = [...oldSelectedMenuIds];

    const result = checkBoxCodes.map((item: any) => {
      old.splice(
        old.findIndex((a) => a == item.menuId),
        1,
      );

      return { ...item, hospId: record.id, systemId: currentSelectedTreeNode.code };
    });

    const needCancelMenus = old.map((a) => ({ hospId: record.id, systemId: currentSelectedTreeNode.code, function: [], menuId: a }));

    const data = {
      hospId: record.id,
      systemId: currentSelectedTreeNode.code,
      menuIds: [...new Set([...checkedMenuParentsIds])],
      functionRequestList: checkedMenuParentsIds.length == 0 ? [] : [...result, ...needCancelMenus],
    };

    const resp = await saveHospMenuApiPerm(data);

    if (resp) {
      set_drawerTablereload(true);
      set_checkBoxCodes([]);
      set_checkedTableMenuIds([]);
    }
  };

  const onCancel = () => {
    set_drawerVisible(false);
  };

  const drawerTableDataSearchHandle = (paramName: string) => {
    set_drawerTableDataFilterParams({
      ...drawerTableDataFilterParams,
      current: 1,
      [`${paramName}`]: drawerTableDataSearchKeywords,
    });
  };

  const clearFunction = () => {
    if (ifFrozze) return;
    let emptyFunc = checkBoxCodes.map((a) => ({ ...a, function: [] }));
    set_checkBoxCodes(emptyFunc);
  };

  const oneKeySetAll = async (bool: boolean) => {
    set_ifFrozze(bool);

    const data = {
      hospId: record.id,
      systemId: currentSelectedTreeNode.code,
      type: bool ? '1' : '0',
    };
    const resp = await setIfCheckAll(data);
    // if (resp) {
    //   set_drawerTablereload(true);
    //   set_checkBoxCodes([]);
    //   set_checkedTableMenuIds([]);
    // }
  };

  useEffect(() => {
    if (currentSelectedTreeNode && !currentSelectedTreeNode.children) {
      set_drawerTableDataFilterParams({ ...drawerTableDataFilterParams, systemId: currentSelectedTreeNode.code });
      //切换系统清空数据
      set_checkBoxCodes([]);
      set_checkedTableMenuIds([]);
    }
  }, [currentSelectedTreeNode]);

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

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

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

  useEffect(() => {
    if (drawerVisible) {
      getTreeReqFunc(record.id);
    } else {
      set_drawerVisible(false);
      set_currentSelectedTreeNode(undefined);
      set_treeData([]);
      setExpandedKeys([]);
    }
  }, [drawerVisible]);

  return (
    <DrawerForm
      trigger={
        <a
          key="link3"
          onClick={(e) => {
            set_drawerVisible(true);
          }}
        >
          菜单
        </a>
      }
      width={908}
      // visible={drawerVisible}
      drawerProps={{
        open: drawerVisible,
        closable: false,
        destroyOnClose: true,
        extra: <div>anniu</div>,
      }}
      submitter={false}
    >
      <div className="setApiPermDrawer">
        <div className="topbar">
          <div className="title">{initialState?.customerType == '2' ? `园区菜单权限设置（${record.hospName}）` : `院区菜单权限设置（${record.hospName}）`}</div>
          <div className="btnGroup">
            <span className={ifFrozze ? 'clearBtn disabled' : 'clearBtn'} onClick={() => clearFunction()}>
              清除功能权限
            </span>
            <span className="cancel" onClick={() => onCancel()}>
              取消
            </span>
            <span className="save" onClick={() => saveResult()}>
              保存
            </span>
          </div>
        </div>
        <div className="content">
          <div className="leftTree">
            <div className="search">
              <Input className="searchInput" placeholder="请输入" size="small" allowClear style={{ marginBottom: 16 }} onChange={onTreeSearchKeyChange} suffix={<SearchIcon type="iconsousuo" />} />
            </div>
            {treeData && treeData.length > 0 && (
              <DirectoryTree
                fieldNames={{ title: 'name', key: 'code' }}
                rootStyle={{ height: '100%', paddingBottom: 50, overflowY: 'scroll', overflowX: 'hidden' }}
                onSelect={onSelect}
                key={'code'}
                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[]}
                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 style={{width:16,height:'92vh',background:'#F5F7FA'}}></div> */}
          <div className="rightContent">
            <div className="tableToolbar">
              <div className="filter">
                <div className="filterItem">
                  <span className="label">检索：</span>
                  <KCInput
                    placeholder={'请输入'}
                    style={{ width: 160 }}
                    search
                    allowClear
                    onChange={(e) => {
                      set_drawerTableDataSearchKeywords(e.target.value);
                      if (e.target.value.length == 0) {
                        set_drawerTableDataFilterParams({
                          ...drawerTableDataFilterParams,
                          name: '',
                        });
                      }
                    }}
                    onSearch={() => drawerTableDataSearchHandle('name')}
                  />
                </div>
              </div>

              <div className={'btnGroup'}>
                {currentSelectedTreeNode && currentSelectedTreeNode.type != 1 && (
                  <a style={{ color: '#17181A' }}>
                    <Switch checked={ifFrozze} style={{ position: 'relative', marginRight: 4 }} size="small" onChange={(bool) => oneKeySetAll(bool)} />
                    全部
                  </a>
                )}
                {/* <UpDataActBtn key={'act'} record={undefined} type='ADD' /> */}
              </div>
            </div>
            {currentSelectedTreeNode && (
              <KCTable
                tableAlertRender={false}
                scroll={{ y: `calc(100vh - 150px)` }}
                onLoad={() => setInitCheckData()}
                expandable={{
                  expandedRowKeys: expandedRowKeys,
                  onExpandedRowsChange(expandedKeys) {
                    set_expandedRowKeys(expandedKeys as Key[]);
                  },
                }}
                rowSelection={{
                  // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
                  // 注释该行则默认不显示下拉选项
                  checkStrictly: false,
                  hideSelectAll: true,
                  onChange(selectedRowKeys, selectedRows, info) {
                    //console.log({selectedRowKeys, selectedRows, info});
                    if (selectedRowKeys.length == 0) {
                      set_checkedTableMenuIds([]);
                    }
                    if (selectedRows.length == 0) {
                      set_checkBoxCodes([]);
                    }
                  },
                  selectedRowKeys: checkedTableMenuIds,
                  onSelect: (record, selected, selectedRows, nativeEvent) => {
                    // console.log({ record, selected, selectedRows, nativeEvent });

                    if (ifFrozze) return;

                    let checkedData = [...checkBoxCodes];

                    if (selected) {
                      //选中

                      const parents = findParents(hospAllMenuTree, record.menuId);
                      const ids = (parents as TreeNode[]).map((a) => a.menuId);

                      if (record.children) {
                        const childIds = extractAttributeValues(record, 'menuId');
                        set_checkedMenuParentsIds([...checkedMenuParentsIds, ...ids, ...childIds, record.menuId]);
                      } else {
                        set_checkedMenuParentsIds([...checkedMenuParentsIds, ...ids, record.menuId]);
                      }

                      selectedRows.forEach((a) => {
                        if (a.functionList) {
                          checkedData.push({
                            menuId: a.menuId,
                            function: a.functionList,
                          });
                        } else {
                          checkedData.push({
                            menuId: a.menuId,
                            function: [],
                          });
                        }
                      });

                      //更新表格row选中状态
                      if (record.type == 0) {
                        //选中的是目录
                        const ids = record.children ? record.children.map((item: any) => item.menuId) : [record.menuId];
                        const totalData = Array.from(new Set([...checkedTableMenuIds, ...ids]));

                        set_checkedTableMenuIds([...totalData]);
                      }
                      if (record.type == 1) {
                        //菜单
                        set_checkedTableMenuIds([...checkedTableMenuIds, record.menuId]);
                      }

                      set_checkBoxCodes([...uniqueFunc(checkedData, 'menuId')]);
                    } else {
                      const ids = extractAttributeValues(record, 'menuId');

                      const filtedMenuIds = checkedMenuParentsIds.filter((a) => !ids.includes(a));
                      set_checkedMenuParentsIds(filtedMenuIds);

                      let _tempCheckedCodes = [...checkBoxCodes];

                      const leftCheckedMenuIds = selectedRows.map((a) => a.menuId);

                      const filtedCheckCodes = _tempCheckedCodes.filter((a) => leftCheckedMenuIds.includes(a.menuId));

                      set_checkedTableMenuIds([...leftCheckedMenuIds]);
                      set_checkBoxCodes([...uniqueFunc(filtedCheckCodes, 'menuId')]);
                    }
                  },
                }}
                pagination={false}
                reload={drawerTablereload}
                newVer
                params={drawerTableDataFilterParams}
                rowKey="menuId"
                columns={columnsData as ProColumns[]}
                request={(params: any, sort: any, filter: any) => getTableData(params, sort, filter)}
              />
            )}
          </div>
        </div>
      </div>
    </DrawerForm>
  );
};

const HospManage: FC<PageProps> = ({ hospManageModel: state, dispatch }) => {
  const { reloadTable } = state;
  const { initialState, setInitialState } = useModel('@@initialState');
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<TableRequestParamsType>({
    current: 1,
    pageSize: 10,
    name: '',
    hospName: ''
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [tabIds, set_tabIds] = useState<Key[]>([]);
  const [open, set_open] = useState(false);
  const [currentEditHosp, set_currentEditHosp] = useState<undefined | any>(undefined);
  const [navSelecterData, set_navSelecterData] = useState<NavSelecterData[]>([]);

  const columns: ProColumns<TableListItem>[] = [
    {
      title: initialState?.customerType == '2' ? '园区ID' : '院区ID',
      dataIndex: 'id',
      width: 70,
    },
    {
      title: initialState?.customerType == '2' ? '园区名称' : '院区名称',
      dataIndex: 'hospName',
      hideInSearch: false,
      ellipsis: true,
      width: 200,
    },
    // {
    //   title: '是否主院',
    //   dataIndex: 'isHospital',
    //   render: (text) => {
    //     return text == 0 ? '是' : '否';
    //   },
    // },
    {
      title: initialState?.customerType == '2' ? '园区标识' : '医院标识',
      dataIndex: 'hospSign',
      ellipsis: true,
    },
    // {
    //   title: '简称',
    //   dataIndex: 'hospAbbreviation',
    // },
    {
      title: initialState?.customerType == '2' ? '主园区名称' : '主院名称',
      dataIndex: 'parentName',
      ellipsis: true,
    },
    {
      title: initialState?.customerType == '2' ? '园区等级' : '医院等级',
      dataIndex: 'hospitalLevelName',
      ellipsis: true,
      width: 90,
    },
    // {
    //   title: '医院类型',
    //   dataIndex: 'hospitalType',
    // },
    {
      title: initialState?.customerType == '2' ? '园区性质' : '医院性质',
      dataIndex: 'hospitalNatureName',
      ellipsis: true,
      width: 90,
    },
    // {
    //   title: '医院编码',
    //   dataIndex: 'hospitalCode',
    // },
    {
      title: '系统名称',
      dataIndex: 'systemName',
      ellipsis: true,
    },
    // {
    //   title: '互通',
    //   dataIndex: 'dataShare',
    // },
    // {
    //   title: '变更日期',
    //   dataIndex: 'updateTime',
    // },
    {
      title: '操作',
      width: 230,
      key: 'option',
      valueType: 'option',
      render: (text, record) => [
        // <a key="link" onClick={() => editHandle(record)}>
        //   编辑
        // </a>,
        // <Divider key="1" type="vertical" style={{ margin: '0 1px' }} />,
        // <Popconfirm
        //   title="是否确定删除?"
        //   onConfirm={() => delHandle(record)}
        //   // onCancel={cancel}
        //   okText="确定"
        //   cancelText="取消"
        //   key="link2"
        // >
        //   <a>删除</a>
        // </Popconfirm>,
        <a
          onClick={() => {
            editHospSystemPermissions(record);
            set_open(true);
          }}
        >
          系统
        </a>,
        <Divider key="2" type="vertical" style={{ margin: '0 1px' }} />,
        <DrawerActBtn record={record} />,
        <Divider key="3" type="vertical" style={{ margin: '0 1px' }} />,
        <Popconfirm
          title="是否确定删除?"
          onConfirm={() => delHandle(record)}
          // onCancel={cancel}
          okText="确定"
          cancelText="取消"
          key="link2"
        >
          <a>删除</a>
        </Popconfirm>,
        <Divider key="10" type="vertical" style={{ margin: '0 1px' }} />,
        <Dropdown
          key="4"
          menu={{
            items: [
              {
                key: '1',
                label: (
                  <a key="link4" onClick={() => youshuAccountBind(record)}>
                    报告
                  </a>
                ),
              },
              // { key: '2', label: <DrawerActBtn record={record} /> },
              // { key: '3', label: <a key="link5" onClick={() => initHospData(record)}>初始化</a> },
              {
                key: '4',
                label: (
                  <a key="link6" onClick={() => setOnlyRead(record)}>
                    按系统初始化
                  </a>
                ),
              },
              {
                key: '6',
                label: (
                  <a key="link5" onClick={() => initHospData(record)}>
                    按菜单初始化
                  </a>
                ),
              },
              {
                key: '5',
                label: (
                  <a key="link7" onClick={() => editHandle(record)}>
                    编辑
                  </a>
                ),
              },
            ],
          }}
        >
          <a>
            更多 <DownOutlined />
          </a>
        </Dropdown>,
      ],
    },
  ];

  const getHospData = async (params: TableRequestParamsType) => {
    const { current = 1, pageSize = 10, hospName: hospitalName } = params;
    const resp = await getAllHosp({
      current,
      pageSize,
      hospitalName: hospitalName ? hospitalName : null,
    });

    if (resp) {
      const { list = [], totalCount = 0 } = resp;
      //获取万最新数据取消重置reload
      dispatch &&
        dispatch({
          type: 'hospManageModel/reloadTable',
          payload: false,
        });

      return {
        data: list,
        success: true,
        total: resp.totalCount,
      };
    } else {
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const addHandle = () => {
    dispatch &&
      dispatch({
        type: 'hospManageModel/add',
        payload: {
          tableAct: TableActType.ADD,
          isShowModal: true,
        },
      });
  };

  const editHandle = (record: TableListItem) => {
    dispatch &&
      dispatch({
        type: 'hospManageModel/edit',
        payload: {
          data: record,
          act: TableActType.EDIT,
          isShowModal: true,
        },
      });
  };

  const delHandle = (record: TableListItem) => {
    dispatch &&
      dispatch({
        type: 'hospManageModel/delRequest',
        payload: [record.id],
      });
  };

  //编辑系统权限
  const editHospSystemPermissions = async (record: TableListItem) => {
    const { selectedMenuIds, allMenuVO } = await getSpacifyHospMenu({ hospId: record.id });
    set_navSelecterData(allMenuVO);
    set_tabIds(selectedMenuIds);
    set_currentEditHosp(record);

    dispatch &&
      dispatch({
        type: 'hospManageModel/edit',
        payload: {
          data: { ...record, bindMenuIds: selectedMenuIds },
          act: TableActType.EDITMENU,
        },
      });
  };

  const editMenuBind = async (record: TableListItem) => {
    //编辑菜单绑定关系
    const { selectedMenuIds } = await getSpacifyHospMenu({ hospId: record.id });
    dispatch &&
      dispatch({
        type: 'hospManageModel/edit',
        payload: {
          data: { ...record, bindMenuIds: selectedMenuIds },
          act: TableActType.EDITMENU,
          isShowModal: true,
        },
      });
  };

  const youshuAccountBind = async (record: TableListItem) => {
    const { id } = record;
    const resp = await getHospYoushuAccounts({ hospId: id });

    if (resp) {
      const { reportId, reportUrl, youshuUsers } = resp;
      dispatch &&
        dispatch({
          type: 'hospManageModel/edit',
          payload: {
            data: { ...record, reportId, reportUrl, youshuUsers },
            act: TableActType.BINDACCOUNT,
            isShowModal: true,
          },
        });
    }
  };

  const setOnlyRead = async (record: any) => {
    const resp = await setReadOnly(record.id);
    if (resp) {
      dispatch &&
        dispatch({
          type: 'hospManageModel/reloadTable',
        });
    }
  };

  const initHospData = async (record: TableListItem) => {
    const resp = await hospInit(record.id);
  };

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

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

  const onCheckedHandle = async (data: NavSelecterItemType[]) => {
    dispatch &&
      dispatch({
        type: 'hospManageModel/postEditData',
        payload: { bindMenuIds: data.map((a) => a.menuId) },
      });
  };

  return (
    <div className="HospManage">
      <ActModal {...state} dispatch={dispatch} />
      {open && <NavSelecter title={`系统权限设置(${currentEditHosp?.hospName})`} data={navSelecterData} onVisibleChange={(bool) => set_open(bool)} value={tabIds} onChecked={onCheckedHandle} />}
      <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({
                    ...tableDataFilterParams,
                    current: 1,
                    hospName: ''
                  });
                }
              }}
              onSearch={() => tableDataSearchHandle('hospName')}
            />
          </div>
        </div>
        <div className="btnGroup">
          <span className="add" onClick={addHandle}>
            新增
          </span>
        </div>
      </div>
      <div style={{ marginTop: 16 }}>
        <KCTable
          columns={columns}
          scroll={{ y: `calc(100vh - 250px)` }}
          reload={reloadTable}
          rowKey="id"
          newVer
          params={tableDataFilterParams}
          request={(params) => getHospData(params)}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
};

export default connect(({ hospManageModel, loading }: { hospManageModel: hospManageModelState; loading: Loading }) => {
  //  console.log({userManageModel});
  return {
    hospManageModel,
    loading: loading.models.hospManageModel,
  };
})(HospManage);
