/*
 * @Author: your name
 * @Date: 2022-01-13 15:22:48
 * @LastEditTime: 2025-05-21 17:50:49
 * @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, useState } from 'react';
import { roleManageModelState, ConnectProps, Loading, connect, useModel } from 'umi';
import { Checkbox, Divider, Dropdown, Input, Popconfirm, Switch, Transfer, TreeProps, Modal } from 'antd';
import KCTable from '@/components/kcTable';
import type { ProColumns } from '@ant-design/pro-table';
import { getAllRoles, getRoleHasBindMenus, getRoleHasBindUsers, getRolePermRelaMenu, initRoleFunc, initRoleReadOnlyFunc, saveRoleRelaApiPerm } from '@/service/role';
import { TableRequestParamsType } from '@/typings';
import ActModal from './modals/modal';
import './style.less';
import type { RoleItemType as TableListItem } from '@/service/role';
import { KCInput } from '@/components/KCInput';
import { createFromIconfontCN, DownOutlined } from '@ant-design/icons';

import { CheckboxValueType } from 'antd/lib/checkbox/Group';
import { getDeepestTreeData, uniqueFunc } from '@/utils';
import { DrawerForm } from '@ant-design/pro-form';
import { DataNode } from 'antd/es/tree';

import expandedIcon from '../../../../../public/images/treenode_open.png';
import closeIcon from '../../../../../public/images/treenode_collapse.png';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getTreeDataRespType } from '../systemNavMana/service';
import { getHospOwnSys, getMenuRelaPerm } from '@/service/hospList';
import { extractAttributeValues, findParents } from '../hospManage';
import React from 'react';

export enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
  EDITMENU, //编辑菜单绑定
  EDITRELAUSER, //编辑人员绑定
}

interface PageProps extends ConnectProps {
  roleManageModel: roleManageModelState;
  loading: boolean;
}

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

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

const selectSystem: { systemId: string; type: number }[] = [];

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 [checkedMenuParentsIds, set_checkedMenuParentsIds] = useState<Key[]>([]); //所有需要保存的菜单id

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

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

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

  const [hospAllMenuTree, set_hospAllMenuTree] = useState<any[]>([]); //角色可选的全量菜单

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

  const [selectSystem, set_selectSystem] = useState<{ systemId: string; type: number }[]>([]); //角色已绑定的系统

  const [ifTixiMenu, set_ifTixiMenu] = useState(false);
  const [ifTixiMenuAuth, set_ifTixiMenuAuth] = useState(false);

  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.map((a: any) => a.code) : [];

          const onCheckGroupChange = (checkedValue: CheckboxValueType[]) => {
            if (checkedValue.length > 0) {
              // 1. 处理功能权限数据
              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,
              });

              // 2. 获取并添加父级菜单ID
              const parents = findParents(hospAllMenuTree, record.menuId);
              const parentsIds = parents ? parents.map((a) => a.menuId) : [];

              // 3. 更新所有相关状态
              set_checkedMenuParentsIds([...checkedMenuParentsIds, record.menuId, ...parentsIds]);
              set_checkedTableMenuIds([...checkedTableMenuIds, record.menuId]);
              set_checkBoxCodes([..._temp]);
            } else {
              // 取消选择时的处理
              const _temp = checkBoxCodes;
              const index = checkBoxCodes.findIndex((item) => item.menuId == record.menuId);
              
              if (index >= 0) {
                _temp.splice(index, 1);
                set_checkBoxCodes([..._temp]);
                
                // 检查是否还有其他功能被选中
                const hasOtherFunctions = _temp.some(item => item.menuId === record.menuId);
                if (!hasOtherFunctions) {
                  // 如果没有其他功能被选中，从选中列表中移除
                  set_checkedTableMenuIds(checkedTableMenuIds.filter(id => id !== record.menuId));
                }
              }
            }
          };

          return <Checkbox.Group options={options} value={codes} onChange={(checkedValue: CheckboxValueType[]) => 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 }: { node: any } = 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 getTableData = async (params: any, sort: any, filter: any) => {
  //   set_drawerTablereload(false);
  //   if (currentSelectedTreeNode && record.hospId && record.roleId) {

  //   }
  //   return []
  // }

  const getTableData = async (params: any, sort: any, filter: any) => {
    set_drawerTablereload(false);
    const currentHosp = localStorage.getItem('currentSelectedSubHop');

    if (currentSelectedTreeNode && currentHosp) {
      const { id } = JSON.parse(currentHosp);
      const resp = await getMenuRelaPerm({ hospId: id, systemId: currentSelectedTreeNode.code });
      if (resp) {
        const { menuList } = resp;
        let expandKeys: Key[] = [];
        set_hospAllMenuTree(menuList);

        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(menuList);
        set_expandedRowKeys(expandKeys);

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

    return [];
  };

  const setInitCheckData = async () => {
    set_drawerTablereload(false);
    if (currentSelectedTreeNode && record.hospId && record.roleId) {
      // console.log({params,record});
      const resp = await getRolePermRelaMenu({ hospId: record.hospId, roleId: record.roleId, systemId: currentSelectedTreeNode.code });
      if (resp) {
        let temp: { menuId: any; function: any }[] = [];
        let expandKeys: Key[] = [];
        let selectedMenuIds: Key[] = [];
        const { menuList = [], selectSystem = [] } = resp;
        set_selectSystem(selectSystem);

        if (currentSelectedTreeNode.type == 1) {
          //判断体系菜单是否授权
          const needItem = selectSystem.filter((a: any) => a.systemId == currentSelectedTreeNode.code);
          if (needItem.length > 0) {
            set_ifTixiMenuAuth(true);
          } else {
            set_ifTixiMenuAuth(false);
          }
        }

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

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

        setTreeRecursion(menuList);

        set_checkedMenuParentsIds([...expandKeys, ...selectedMenuIds]);
        set_checkBoxCodes(temp);
        set_checkedTableMenuIds(selectedMenuIds);
        set_oldSelectedMenuIds(selectedMenuIds);

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

  const saveResult = async () => {
    try {
      // 1. 收集所有需要保存的菜单ID
      const allMenuIds = new Set<string>();

      // 2. 添加当前选中的菜单ID（类型转换为string）
      checkedMenuParentsIds.forEach(id => allMenuIds.add(String(id)));

      // 3. 添加系统ID
      if (currentSelectedTreeNode?.code) {
        allMenuIds.add(String(currentSelectedTreeNode.code));
      }

      // 4. 确保父级ID存在
      const finalMenuIds = Array.from(allMenuIds).filter(id => {
        const parents = findParents(hospAllMenuTree, id);
        if (parents) {
          return parents.every(parent => allMenuIds.has(String(parent.menuId)));
        }
        return true;
      });

      // 5. 生成 result 和 needCancelMenus
      let old = [...oldSelectedMenuIds];
      const result = checkBoxCodes.map((item: any) => {
        const index = old.findIndex((a) => a == item.menuId);
        if (index !== -1) {
          old.splice(index, 1);
        }
        return { ...item, hospId: record.hospId, roleId: record.roleId, systemId: currentSelectedTreeNode.code };
      });

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

      const data = {
        hospId: record.hospId,
        roleId: record.roleId,
        systemId: currentSelectedTreeNode.code,
        menuIds: ifTixiMenu
          ? (ifTixiMenuAuth ? [currentSelectedTreeNode.code] : [])
          : finalMenuIds,
        functionList: [...result, ...needCancelMenus],
      };

      // 6. 数据验证
      if (!validateMenuIds(data.menuIds, hospAllMenuTree)) {
        console.warn('菜单ID数据不完整，请检查');
        return;
      }

      const resp = await saveRoleRelaApiPerm(data);
      if (resp) {
        set_drawerTablereload(true);
        set_checkBoxCodes([]);
        set_checkedTableMenuIds([]);
        await setInitCheckData();
      }
    } catch (error) {
      console.error('保存角色权限失败:', error);
    }
  };

  // 添加数据验证函数
  const validateMenuIds = (menuIds: string[], tree: any[]) => {
    // 检查是否所有父级ID都存在
    const missingParents = menuIds.filter(id => {
      const parents = findParents(tree, id);
      if (parents) {
        return parents.some(parent => !menuIds.includes(parent.menuId));
      }
      return false;
    });

    if (missingParents.length > 0) {
      console.warn('发现缺失的父级菜单ID:', missingParents);
      return false;
    }

    return true;
  };

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

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

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

  useEffect(() => {
    if (currentSelectedTreeNode && !currentSelectedTreeNode.children) {
      // setInitCheckData();

      set_ifTixiMenu(currentSelectedTreeNode.type == 1);

      setInitCheckData();

      set_drawerTableDataFilterParams({ ...drawerTableDataFilterParams, current: 1, 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(() => {}, [checkedMenuParentsIds]);

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

  return (
    <DrawerForm
      trigger={
        <a key="link3" onClick={() => set_drawerVisible(true)}>
          菜单
        </a>
      }
      drawerProps={{
        open: drawerVisible,
        afterOpenChange(open) {
          set_drawerVisible(open);
        },
        closable: false,
        extra: null,
      }}
      width={908}
      submitter={false}
    >
      <div className="setApiPermDrawer_roleMana">
        <div className="topbar">
          <div className="title">{`角色功能权限设置（${record.roleName}）`}</div>
          <div className="btnGroup">
            {currentSelectedTreeNode && currentSelectedTreeNode.type == 5 && (
              <span className={'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}
                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">
            {!ifTixiMenu && (
              <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,
                            current: 1,
                            name: '',
                          });
                        }
                      }}
                      onSearch={() => drawerTableDataSearchHandle('name')}
                    />
                  </div>
                </div>

                <div className={'btnGroup'}>
                  {/* <a style={{color: '#17181A'}}><Switch style={{position:'relative',marginRight:4}} size='small'  onChange={(bool)=>oneKeySetReadOnly(bool)} />只读</a> */}
                  {/* <UpDataActBtn key={'act'} record={undefined} type='ADD' /> */}
                </div>
              </div>
            )}

            {ifTixiMenu && (
              <div className="tixiMenuSet">
                <img src={require('../../../../../public/images/zanwuneirong.png')} style={{ width: 100, height: 88 }} alt="" />
                <div className="despcrip">当前所选系统没有可管理的菜单/功能权限</div>
                <div>
                  授予系统权限：
                  <Switch size="small" checked={ifTixiMenuAuth} onChange={(bool) => set_ifTixiMenuAuth(bool)} />
                </div>
              </div>
            )}
            {!ifTixiMenu && (
              <KCTable
                scroll={{ y: `calc(100vh - 150px)` }}
                tableAlertRender={false}
                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,
                  onChange(selectedRowKeys, selectedRows, info) {
                    // console.log({selectedRowKeys, selectedRows, info});
                    if (selectedRowKeys.length == 0) {
                      set_checkedTableMenuIds([]);
                    }
                    if (selectedRows.length == 0) {
                      set_checkBoxCodes([]);
                    }
                  },

                  selectedRowKeys: checkedTableMenuIds,
                  hideSelectAll: true,
                  onSelect: (record, selected, selectedRows, nativeEvent) => {
                    //console.log({ record, selected, selectedRows, nativeEvent });

                    let checkedData = [...checkBoxCodes];

                    if (selected) {
                      //选中
                      const parents = findParents(hospAllMenuTree, record.menuId);
                      const parentsIds = parents ? parents.map((a) => a.menuId) : [];

                      if (record.children) {
                        const childIds = extractAttributeValues(record, 'menuId');

                        set_checkedMenuParentsIds([...checkedMenuParentsIds, ...childIds, ...parentsIds]);
                      } else {
                        set_checkedMenuParentsIds([...checkedMenuParentsIds, record.menuId, ...parentsIds]);
                      }

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

                      //更新表格row选中状态
                      if (record.type == 0) {
                        //选中的是目录
                        const ids = record.children.map((item: any) => item.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 {
                      //取消勾选\
                      let _tempCheckedCodes = [...checkBoxCodes];

                      const ids = extractAttributeValues(record, 'menuId');

                      const filtedMenuIds = checkedMenuParentsIds.filter((a) => ![...ids, record.menuId].includes(a));

                      set_checkedMenuParentsIds(filtedMenuIds);

                      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 RoleManage: FC<PageProps> = ({ roleManageModel: state, dispatch }) => {
  const { reloadTable } = state;
  const { initialState, setInitialState } = useModel('@@initialState');
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<TableRequestParamsType>({
    current: 1,
    pageSize: 10,
    roleName: '',
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [reload, set_reload] = useState(false);

  const columns: ProColumns<TableListItem>[] = [
    {
      title: 'ID',
      dataIndex: 'roleId',
      hideInTable: true,
    },
    {
      title: initialState?.customerType == '2' ? '园区名称' : '院区名称',
      dataIndex: 'hospName',
      ellipsis: true,
      width: 200,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      hideInSearch: false,
    },
    {
      title: '角色编码',
      dataIndex: 'roleCode',
      hideInSearch: false,
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '有数账号',
      dataIndex: 'account',
    },
    {
      title: '数据权限',
      dataIndex: 'dataPermissionName',
    },
    {
      title: '角色标签',
      renderText(text, record: any) {
        const { roleTags = [] } = record;
        return (
          <>
            {roleTags.map((a: any, i: number) => (
              <span
                style={{
                  display: 'inline-flex',
                  padding: '2px 5px',
                  fontSize: 12,
                  background: '#EEF3FA',
                  borderRadius: 4,
                  color: '#525866',
                  marginRight: 4,
                }}
              >
                {a.labelName}
              </span>
            ))}
          </>
        );
      },
    },
    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      render: (text, record) => [
        <a key="link4" onClick={() => editUserBind(record)}>
          用户
        </a>,
        <Divider key="9" type="vertical" style={{ margin: '0 1px' }} />,
        <DrawerActBtn key="link7" 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: '5',
                label: (
                  <a key="link" onClick={() => editHandle(record)}>
                    编辑
                  </a>
                ),
              },
              {
                key: '2',
                label: (
                  <a key="link4" onClick={() => initRoleData('func', record)}>
                    初始化权限
                  </a>
                ),
              },
              //{ key: '6', label: <a key="link6" onClick={() => initRoleData('read',record)}>初始化只读</a> },
            ],
          }}
        >
          <a>
            更多 <DownOutlined />
          </a>
        </Dropdown>,
      ],
    },
  ];

  const getData = async (params: TableRequestParamsType) => {
    const { current = 1, pageSize = 10, roleName } = params;
    const resp = await getAllRoles({
      current,
      pageSize,
      roleName: roleName ? roleName : null,
    });

    //获取万最新数据取消重置reload
    dispatch &&
      dispatch({
        type: 'roleManageModel/reloadTable',
        payload: false,
      });

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

  const addHandle = () => {
    dispatch &&
      dispatch({
        type: 'roleManageModel/addEffect',
      });
  };

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

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

  const editMenuBind = async (record: TableListItem) => {
    //编辑菜单绑定关系
    const { menuIds = [] } = await getRoleHasBindMenus({
      hospId: record.hospId,
      roleId: record.roleId,
    });
    dispatch &&
      dispatch({
        type: 'roleManageModel/edit',
        payload: {
          data: { ...record, bindMenuIds: menuIds },
          act: TableActType.EDITMENU,
          isShowModal: true,
        },
      });
  };

  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 editUserBind = async (record: TableListItem) => {
    //编辑角色与人员的绑定关系
    const { userIds = [], users = [] } = await getRoleHasBindUsers({
      hospId: record.hospId,
      roleId: record.roleId,
    });
    dispatch &&
      dispatch({
        type: 'roleManageModel/edit',
        payload: {
          data: { ...record, bindUserIds: userIds, allUsers: users },
          act: TableActType.EDITRELAUSER,
          isShowModal: true,
        },
      });
  };

  const initRoleData = async (type: string, record: any) => {
    if (type == 'func') {
      const resp = await initRoleFunc({ roleId: record.roleId, hospId: record.hospId });
      if (resp) {
        dispatch &&
          dispatch({
            type: 'roleManageModel/reloadTable',
          });
      }
    }
    if (type == 'read') {
      const resp = await initRoleReadOnlyFunc({ roleId: record.roleId, hospId: record.hospId });
      if (resp) {
        dispatch &&
          dispatch({
            type: 'roleManageModel/reloadTable',
          });
      }
    }
  };

  //  console.log({state});

  return (
    <div className="RoleManage">
      <ActModal {...state} dispatch={dispatch} />

      <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,
                    roleName: ''
                  });
                }
              }}
              onSearch={() => tableDataSearchHandle('roleName')}
            />
          </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={reload}
          rowKey="id"
          newVer
          params={tableDataFilterParams}
          request={(params) => getData(params)}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
};

export default connect(({ roleManageModel, loading }: { roleManageModel: roleManageModelState; loading: Loading }) => {
  //  console.log({userManageModel});
  return {
    roleManageModel,
    loading: loading.models.roleManageModel,
  };
})(RoleManage);
