import { findAllSysRole, roleAdd, roleDelete, roleUpdate, roleInfo } from '@/services/system/role';
import { roleMenuTreeSelect } from '@/services/user/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';
/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields: API.System.Menu) => {
  const hide = message.loading('正在添加');
  try {
    await roleAdd({ ...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 roleUpdate(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 roleDelete(params);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    return false;
  }
};



const RoleTableList: React.FC = () => {
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState();
  const [menuTree, setMenuTree] = useState([]);

  const access = useAccess()



  const actionRef = useRef<ActionType>();
  /** 国际化配置 */
  const intl = useIntl();

  useEffect(() => {
    roleMenuTreeSelect().then((res) => {
      const { data } = res
      setMenuTree(data)
    })
  }, []);

  const columns = [
    {
      title: '角色编号',
      dataIndex: 'id',
      valueType: 'text',
      search: false,
    },
    {
      title: '角色名称',
      dataIndex: 'roleName',
      valueType: 'text',
    },
    {
      title: '权限字符',
      dataIndex: 'roleKey',
      valueType: 'text',
    },
    {
      title: '显示顺序',
      dataIndex: 'roleSort',
      valueType: 'text',
      search: false,
    },
    {
      title: '角色状态',
      dataIndex: 'statusName',
      valueType: 'text',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      search: false,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record: any) => [
        <Button
          type="link"
          size="small"
          key="edit"
          hidden={!access.hasPerms('/api/sys/role/update')}
          onClick={async () => {
            setModalVisible(true);
            const { data } = await roleInfo({
              id: record.id
            })
            setCurrentRow(data);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          hidden={!access.hasPerms('/api/sys/role/deleteRoleBatchByIds')}
          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
          actionRef={actionRef}
          rowKey="id"
          key="roleList"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              hidden={!access.hasPerms('/api/sys/role/add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ]}
          request={findAllSysRole}
          columns={columns}
        />
      </div>
      <UpdateForm
        onSubmit={async (values) => {
          let success = false;
          if (values.id) {
            success = await handleUpdate({ ...values });
          } else {
            success = await handleAdd({ ...values });
          }
          if (success) {
            setModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setModalVisible(false);
          setCurrentRow(undefined);
        }}
        open={modalVisible}
        values={currentRow || {}}
        menuTree={menuTree}
      />
    </PageContainer>
  );
};

export default RoleTableList;
