import { protocolUpdate, protocolPage, protocolAdd, protocolDelete, protocolInfo } from '@/services/config/agreement';


import React, { useState, useRef, useEffect } from 'react';
import { useIntl, FormattedMessage, useAccess } from '@umijs/max';
import { Button, message, Modal, Image } 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) => {
  const hide = message.loading('正在添加');
  try {
    await protocolAdd({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: API.System.Menu) => {
  const hide = message.loading('正在修改');
  try {
    await protocolUpdate(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

const handleRemoveOne = async (selectedRow: API.System.Menu) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    const params = [selectedRow.id];
    await protocolDelete(params);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};


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

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


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

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

  useEffect(() => {
  }, []);

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      search: false,
    },
    {
      title: '协议名称',
      dataIndex: 'protocolName',
      valueType: 'text',
      search: true,
    },
    {
      title: '修改时间',
      dataIndex: 'updateTime',
      valueType: 'text',
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'text',
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record) => [
        <Button
          type="link"
          size="small"
          // hidden={!access.hasPerms('/api/protocol/update')}
          onClick={async () => {
            let { data } = await protocolInfo({ id: record.id })
            setCurrentRow(data);
            setModalVisible(true);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          // hidden={!access.hasPerms('/api/protocol/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/protocol/add')}
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ]}
          request={async (params, sorter, filter) => {
            let { data } = await protocolPage(params)
            return {
              data: data?.records || [],
              total: data?.total,
            };
          }}
          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 || {}}
      />
    </PageContainer>
  );
};

export default MenuTableList;
