import { PageContainer } from '@ant-design/pro-components';
import React, { useEffect, useState } from 'react';
import { Button, Card, Form, Input, message, Modal, Space, Table } from 'antd';
import Icon, { PlusCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import moment from 'moment/moment';
import Edit from '@/pages/MenuManagement/edit';
import IconMap from '@/components/Icon/IconMap';
import Check from '@/pages/MenuManagement/check';
import { delMenu, queryMenu } from '@/services/menu';

interface DataType {
  key: React.ReactNode;
  name: string;
  menu_type: number;
  sequence: number;
  hidden: number;
  icon: string;
  record_id: string;
  children?: DataType[];
}

/**
 * 菜单管理
 * @constructor
 */
const MenuManagement: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [searchData, setSearchData] = useState<object | null>({});
  const [editData, setEditData] = useState(null);
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [dataList, setDataList] = useState([]);
  const [tag] = useState('web');
  const [checkVisible, setCheckVisible] = useState(false);
  const [checkData, setCheckData] = useState<object | null>({});

  // 获取列表数据
  const getList = () => {
    const params: any = {
      q: 'tree',
      query_all: 1,
      ...searchData,
    };
    queryMenu(params).then((res) => {
      if (res && res.code === 0) {
        setDataList(res.data.list);
        setLoading(false);
      }
    });
  };

  // 初始化数据
  useEffect(() => {
    setLoading(true);
    getList();
  }, []);

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

  //  搜索
  const onFinish = () => {
    form.validateFields().then((data) => {
      setLoading(true);
      setSearchData(data);
    });
  };
  // 重置
  const onReset = () => {
    form.resetFields();
    setLoading(true);
    setSearchData(null);
  };
  // 新增弹框
  const onAdd = () => {
    setEditData(null);
    setVisible(true);
  };
  // 打开编辑弹框
  const toEdit = (data: any) => {
    setEditData(data);
    setVisible(true);
  };
  // 删除
  const toDel = (record: any) => {
    Modal.confirm({
      title: '删除',
      content: `确认删除菜单：[${record.name}]`,
      onOk: () => {
        delMenu(record.record_id)
          .then((res) => {
            if (res.data && res.data.status === 'OK') {
              message.success('删除成功');
              getList();
            } else {
              message.error('删除失败');
            }
          })
          .catch((e) => {
            message.error(e?.message);
          });
      },
    });
  };

  // 编辑弹框回调
  const handleEdit = () => {
    setVisible(false);
    getList();
  };

  // 查看
  const toCheck = (record: any) => {
    setCheckVisible(true);
    setCheckData(record);
  };

  // 查看弹框回调
  const checkCallback = () => {
    setCheckVisible(false);
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: 'center',
      key: 'index',
      render: (_: any, row: any, index: number) => index + 1,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '排序值',
      dataIndex: 'sequence',
      key: 'sequence',
    },
    {
      title: '状态',
      dataIndex: 'hidden',
      align: 'center',
      render: (val) =>
        val === 1 ? (
          <span style={{ color: '#f50' }}>隐藏</span>
        ) : (
          <span style={{ color: '#87d068' }}>显示</span>
        ),
    },
    {
      title: '图标',
      dataIndex: 'icon',
      align: 'center',
      render: (val) => {
        return tag === 'api' ? (
          <img src={val} alt="val" style={{ width: 32 }} />
        ) : (
          <Icon component={IconMap[val] as React.ForwardRefExoticComponent<any>} />
        );
      },
    },
    {
      title: '访问路由',
      dataIndex: 'router',
      key: 'router',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (v) => v && <span>{moment(v).format('YYYY-MM-DD HH:mm')}</span>,
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <a
            onClick={() => {
              toCheck(record);
            }}
          >
            查看
          </a>
          <a
            onClick={() => {
              toEdit(record);
            }}
          >
            编辑
          </a>
          <a
            style={{ color: 'red' }}
            onClick={() => {
              toDel(record);
            }}
          >
            删除
          </a>
        </Space>
      ),
    },
  ];
  return (
    <PageContainer>
      <div>
        <Card>
          <Form form={form} layout="inline" onFinish={onFinish}>
            <Form.Item name="name" label="菜单名称">
              <Input placeholder="请输入菜单名称" />
            </Form.Item>
            <Form.Item style={{ marginBottom: '10px' }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  <SearchOutlined />
                  查询
                </Button>
                <Button htmlType="button" onClick={onReset}>
                  <ReloadOutlined />
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Form>
          <Button htmlType="button" type="primary" style={{ margin: '20px 0' }} onClick={onAdd}>
            <PlusCircleOutlined />
            新增菜单
          </Button>
          <Table
            columns={columns}
            dataSource={dataList}
            rowKey={(record) => record.record_id}
            loading={loading}
          />
          {visible && <Edit visible={visible} editCallback={handleEdit} params={editData} />}
          {checkVisible && (
            <Check visible={checkVisible} checkCallback={checkCallback} params={checkData} />
          )}
        </Card>
      </div>
    </PageContainer>
  );
};
export default MenuManagement;
