/*
 * @Author: your name
 * @Date: 2022-01-13 15:22:48
 * @LastEditTime: 2022-07-28 14:49:55
 * @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 } from 'react';
import { menuManageModelState, ConnectProps, Loading, connect } from 'umi';
import { Button, Divider, Popconfirm } from 'antd';
import KCTable from '@/components/kcTable';
import type { ProColumns } from '@ant-design/pro-table';
import { getAllMenus } from '@/service/menu';
import { TableRequestParamsType } from '@/typings';
import ActModal from './modals/modal';
import './style.less';
import { DownOutlined, FileOutlined, RightOutlined } from '@ant-design/icons';
import type { MenuItemDataType } from '@/service/menu';
import { MenuTypes } from '@/constant';

export enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
  SET,
  MOVEANDCOPY,//复制移动
}

interface PageProps extends ConnectProps {
  menuManageModel: menuManageModelState;
  loading: boolean;
}

const MenuManage: FC<PageProps> = ({ menuManageModel: state, dispatch }) => {
  const { reloadTable } = state;

  const columns: ProColumns<MenuItemDataType>[] = [
    {
      title: 'ID',
      dataIndex: 'menuId',
      hideInTable: true,
    },
    {
      title: 'parentId',
      dataIndex: 'parentId',
      hideInTable: true,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
      hideInSearch: false,
      render: (text, record) => {
        if (record.children && record.children.length > 0) {
          return text;
        } else {
          //叶子节点
          return record.parentId != '0' ? (
            //非第一级
            <div>
              <FileOutlined style={{ marginRight: 10 }} />
              {text}
            </div>
          ) : (
            text
          );
        }
      },
    },
    {
      title: '类型',
      dataIndex: 'isHospital',
      render: (number, record) => {
        const findType = MenuTypes.filter((t) => t.value == record.type);
        return findType[0].label;
      },
    },
    // {
    //   title: 'URL',
    //   dataIndex: 'url',
    // },
    {
      title: 'Path',
      dataIndex: 'path',
    },
    // {
    //   title: '变更人',
    //   dataIndex: 'mainHospName',
    // },
    // {
    //   title: '变更日期',
    //   dataIndex: 'modifyTime',
    // },
    {
      title: '操作',
      width: 400,
      key: 'option',
      valueType: 'option',
      render: (text, record) => {

           return record.type == 1?[
            <a key="link" onClick={() => setHomePage(record)}>
              设为首页
            </a>,
            <Divider key="1" type="vertical" style={{ margin: '0 1px'}} />,
            <a key="link0" onClick={() => editHandle(record)}>
              编辑
            </a>,
            <Divider key="11" type="vertical" style={{ margin: '0 1px'}} />,
            <Popconfirm
              title="是否确定删除?"
              onConfirm={() => delHandle(record)}
              // onCancel={cancel}
              okText="确定"
              cancelText="取消"
              key="link2"
            >
              <a>删除</a>
            </Popconfirm>,

            <Divider key="2" type="vertical" style={{ margin: '0 1px',display:record.type != 1?'inline':'none' }}  />,
            <a key="link3" onClick={() => addHandle(record.menuId, record)} style={{display:record.type != 1?'inline':'none'}}>
              添加
            </a>,
            <Divider key="100" type="vertical" style={{ margin: '0 1px' }} />,
             <a key="link4" onClick={() => moveAndCopy(record)}>
               复制/移动
             </a>,
          ]:[
            <a key="link12" onClick={() => editHandle(record)}>
              编辑
            </a>,
            <Divider key="10" type="vertical" style={{ margin: '0 1px' }} />,
            <Popconfirm
              title="是否确定删除?"
              onConfirm={() => delHandle(record)}
              // onCancel={cancel}
              okText="确定"
              cancelText="取消"
              key="link23"
            >
              <a>删除</a>
            </Popconfirm>,
            <Divider key="2" type="vertical" style={{ margin: '0 1px' }} />,
            <a key="link5" onClick={() => addHandle(record.menuId, record)}>
              添加
            </a>,
          ]
      }

    },
  ];

  const setHomePage = (record:MenuItemDataType)=>{
    dispatch &&
    dispatch({
      type: 'menuManageModel/edit',
      payload: {
        data: record,
        act: TableActType.SET,
        isShowModal: true,
      },
    });
  }

  const getData = async (params: { name?: string } & TableRequestParamsType) => {
    const { current = 1, pageSize = 1000, name } = params;
    const resp = await getAllMenus();

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

    if (name) {
      //搜索菜单
      let deeper = (data: MenuItemDataType[], keyword: string) => {
        let newarr:MenuItemDataType[] = [];
        data.forEach(element => {
          if (element.name.indexOf(keyword) > -1) { // 判断条件
            newarr.push(element);
          } else {
            if (element.children && element.children.length > 0) {
            
            
              let redata = deeper(element.children,keyword);
              if (redata && redata.length > 0) {
                let obj = {
                  ...element,
                  children: redata
                };
                newarr.push(obj);
              }
            }
          }
        });
        return newarr;
      };

      return {
        data: resp.list ? deeper(resp.list, name) : [],
        success: true,
        total: (deeper(resp.list, name)).length,
      };
    }

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

  const moveAndCopy = (record:MenuItemDataType)=>{
  
    dispatch &&
    dispatch({
      type: 'menuManageModel/edit',
      payload: {
        act: TableActType.MOVEANDCOPY,
        isShowModal: true,
        data: record ? record : null,
      },
    });
  }

  const addHandle = (parentId?: string, record?: MenuItemDataType) => {
    dispatch &&
      dispatch({
        type: 'menuManageModel/add',
        payload: {
          tableAct: TableActType.ADD,
          isShowModal: true,
          parentId: parentId ? parentId : 0, //考虑新增子集菜单的情况
          record: record ? record : null,
        },
      });
  };

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

  const delHandle = (record: MenuItemDataType) => {
    dispatch &&
      dispatch({
        type: 'menuManageModel/delRequest',
        payload: [record.menuId],
      });
  };

  //  console.log({state});

  return (
    <div className="MenuManage">
      <ActModal {...state} dispatch={dispatch} />
      <KCTable
        rowKey="menuId"
        headerTitle="查询表格"
        columns={columns}
        reload={reloadTable}
        toolBarRender={() => [
          <Button key="3" type="primary" onClick={() => addHandle()}>
            新增中心
          </Button>,
        ]}
        request={(params) => getData(params)}
        expandable={{
          expandIcon: ({ expanded, onExpand, record }) => {
            // console.log({expanded, onExpand, record});
            return expanded
              ? record.children.length > 0 && (
                  <DownOutlined onClick={(e) => onExpand(record, e)} style={{ marginRight: 10 }} />
                )
              : record.children.length > 0 && (
                  <RightOutlined onClick={(e) => onExpand(record, e)} style={{ marginRight: 10 }} />
                );
          },
        }}
      />
    </div>
  );
};

export default connect(
  ({ menuManageModel, loading }: { menuManageModel: menuManageModelState; loading: Loading }) => {
    //  console.log({userManageModel});
    return {
      menuManageModel,
      loading: loading.models.menuManageModel,
    };
  },
)(MenuManage);
