import { bannerUpdate, bannerPage, bannerAdd, bannerDelete } from '@/services/config/banner';


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 {
    fields.status = fields.status ? 0 : 1
    await bannerAdd({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields) => {
  fields.status = fields.status ? 1 : 0

  const hide = message.loading('正在修改');
  try {
    await bannerUpdate(fields);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};

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


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

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

  const intRow = {
    "id": 1,
    "imageUrl": "",
    "sortOrder": 0,
    "status": 0,
    "title": "",
    "jumpUrl": ""
  }


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

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

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

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'text',
      search: false,
    },
    {
      title: '标题',
      dataIndex: 'title',
      valueType: 'text',
      search: false,
    },
    {
      title: '图片',
      dataIndex: 'imageUrl',
      valueType: 'text',
      search: false,
      render: (_, record) => {
        return <Image src={record.imageUrl} width={60}  height={60}></Image>
      }
    },
    {
      title: '排序',
      dataIndex: 'orderNum',
      valueType: 'text',
      search: false,
    },
    {
      title: '跳转路径',
      dataIndex: 'jumpUrl',
      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('admin/banner/update')}
          onClick={() => {
            setModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </Button>,
        <Button
          type="link"
          size="small"
          danger
          // hidden={!access.hasPerms('admin:banner:update')}
          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"
              onClick={async () => {
                setCurrentRow(undefined);
                setModalVisible(true);
              }}
            >
              <PlusOutlined /> 新建
            </Button>
          ]}
          request={async (params, sorter, filter) => {
            let { data } = await bannerPage(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;
