import { roleMenuTreeSelect, menuDele, menuUpdate, menuAdd } from '@/services/user/menu';
import { getMenuList } from '@/services/system/menu';


import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess } from '@umijs/max';
import { Button, message, Modal } from 'antd';
import { ActionType, FooterToolbar, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components';
import { PlusOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import UpdateForm from './edit';
import { DataNode } from 'antd/es/tree';

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.System.Menu) => {
  const hide = message.loading('正在添加');
  try {
    if (!fields.parentId) {
      fields.parentId = 0
    }
    await menuAdd({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.System.Menu) => {
  const hide = message.loading('正在配置');
  try {
    await menuUpdate(fields);
    hide();
    message.success('配置成功');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.System.Menu) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.id];
    await menuDele(params);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};


const MenuTableList: React.FC = () => {

  const [modalVisible, setModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState();
  const [selectedRows, setSelectedRows] = useState([]);

  const [menuTree, setMenuTree] = useState<DataNode[]>([]);
  const [visibleOptions, setVisibleOptions] = useState<any>([]);
  const [statusOptions, setStatusOptions] = useState<any>([]);

  const access = useAccess();

  /** 国际化配置 */
  const intl = useIntl();

  useEffect(() => {
    getMenuList().then((res) => {
      const { data } = res
      setMenuTree(data)
    })

    // getDictValueEnum('sys_show_hide').then((data) => {  
    //   setVisibleOptions(data);
    // });
    // getDictValueEnum('sys_normal_disable').then((data) => {
    //   setStatusOptions(data);
    // });
  }, []);

  const columns: ProColumns<API.System.Menu>[] = [
    {
      title: '菜单名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '菜单图标',
      dataIndex: 'icon',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '排序',
      dataIndex: 'orderNum',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '组件路径',
      dataIndex: 'path',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '权限标识',
      dataIndex: 'perms',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '菜单状态',
      dataIndex: 'statusName',
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record:any) => [
        <Button
          type="link"
          size="small"
          hidden={!access.hasPerms('/api/sys/menu/add')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow({
              parentId: record.id
            });
          }}
        >
          添加下级
        </Button>,
        <Button
          type="link"
          size="small"
          hidden={!access.hasPerms('/api/sys/menu/update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          hidden={!access.hasPerms('/api/sys/menu/deleteBatchByIds')}
          onClick={async () => {
            Modal.confirm({
              title: '删除',
              content: '确定删除该项吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const success = await handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}
        >
          删除
        </Button>,
      ],
    },

  ];

  return (
    <PageContainer>
      <div style={{ width: '100%', float: 'right' }}>
        <ProTable<API.System.Menu>
          headerTitle={'菜单管理'}
          actionRef={actionRef}
          rowKey="id"
          key="menuList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="add"
              hidden={!access.hasPerms('/api/sys/menu/add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ]}
          request={async () => {
            let { data } = await getMenuList()
            function childrenRemove(item: []) {
              let data = item.map((i: any) => {
                if (i?.children.length === 0) {
                  delete i.children
                } else {
                  childrenRemove(i.children)
                }
                return i
              })
              return data
            }

            return {
              data: childrenRemove(data)
            }
          }}
          columns={columns}
          rowSelection={{
            onChange: (_, selectedRows) => {
              setSelectedRows(selectedRows);
            },
          }}
        />
      </div>
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;
          if (values.id) {
            success = await handleUpdate({ ...values } as API.System.Menu);
          } else {
            success = await handleAdd({ ...values } as API.System.Menu);
          }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
        visibleOptions={visibleOptions}
        statusOptions={statusOptions}
        menuTree={menuTree}
      />
    </PageContainer>
  );
};

export default MenuTableList;
