import Icon from '@ant-design/icons';
import {
  Col,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Radio,
  Row,
  Select,
  TreeSelect,
} from 'antd';
import React, { useEffect, useState } from 'react';
import IconSelector from '@/components/IconSelecter';
import { createMenu, editMenu, queryMenu } from '@/services/menu';

interface editProps {
  visible: boolean;
  editCallback: () => void;
  params: any;
}

/**
 * 菜单管理 - 编辑
 * @param props
 * @constructor
 */
const Edit: React.FC<editProps> = (props) => {
  const { params, visible, editCallback } = props;
  const [iconSelectorVisible, setIconSelectorVisible] = useState(false);
  const [form] = Form.useForm();
  const { getFieldValue, setFieldsValue } = form;
  const iconType = getFieldValue('icon') || (params ? params.icon : '');
  // 菜单树列表数据
  const [treeData, setTreeData] = useState([]);

  useEffect(() => {
    // 获取树结构的菜单列表数据
    queryMenu({ q: 'tree', query_all: 1 }).then((res) => {
      if (res && res.code === 0) {
        setTreeData(res.data.list);
      }
    });
  }, []);

  // 确认弹框
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        if (params) {
          data.record_id = params.record_id;
          editMenu(data)
            .then((res) => {
              if (res.code === 0) {
                message.success('编辑成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        } else {
          createMenu(data)
            .then((res) => {
              if (res.code === 0) {
                message.success('新增成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        }
      }
    });
  };

  // 取消
  const onCancel = () => {
    editCallback();
  };

  // 打开图标选择框
  const openIconSelector = () => {
    setIconSelectorVisible(true);
  };

  // 上级菜单 树选择
  const toTreeSelect = (data: any) => {
    if (!data) {
      return [];
    }
    const newData = [];
    for (let i = 0; i < data.length; i += 1) {
      const item = {
        ...data[i],
        title: data[i].name,
        value: data[i].record_id,
      };
      if (item.children && item.children.length > 0) {
        item.children = toTreeSelect(item.children);
      }
      newData.push(item);
    }
    return newData;
  };

  // 选中图标后
  const onIconSelected = (item: any) => {
    if (item && typeof item === 'string') {
      setFieldsValue({ icon: item });
    }
    setIconSelectorVisible(false);
  };

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 18,
    },
  };

  const formItemLayout24 = {
    labelCol: { span: 3 },
    wrapperCol: { span: 21 },
  };

  return (
    <Modal
      title={`${params ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="name"
              label="菜单名称"
              rules={[{ required: true, message: '请输入菜单名称' }]}
              initialValue={params?.name}
            >
              <Input placeholder="请输入菜单名称" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="parent_id"
              label="上级菜单"
              rules={[{ required: false, message: '请选择上级菜单' }]}
              initialValue={params?.parent_id}
            >
              <TreeSelect
                allowClear
                showSearch
                treeNodeFilterProp="title"
                style={{ width: '100%' }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={toTreeSelect(treeData)}
                placeholder="请选择"
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="tag"
              label="菜单标签"
              rules={[{ required: true, message: '请选择菜单标签' }]}
              initialValue={params?.tag}
            >
              <Select placeholder="请选择菜单标签">
                <Select.Option key="api" value="api">
                  api
                </Select.Option>
                <Select.Option key="web" value="web">
                  web
                </Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="sequence"
              label="排序值"
              rules={[{ required: true, message: '请输入排序值' }]}
              initialValue={params?.sequence}
            >
              <InputNumber placeholder="请输入排序值" style={{ width: '280px' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="icon"
              label="图标"
              rules={[{ required: true, message: '请选择图标' }]}
              initialValue={params?.icon}
            >
              <Input
                placeholder="请输入"
                readOnly
                onClick={openIconSelector}
                suffix={iconType ? <Icon type={iconType} /> : null}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="hidden"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
              initialValue={params?.hidden}
            >
              <Radio.Group>
                <Radio value={0}>显示</Radio>
                <Radio value={1}>隐藏</Radio>
              </Radio.Group>
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayout24}
              name="router"
              label="访问路由"
              rules={[{ required: true, message: '请输入访问路由' }]}
              initialValue={params?.router}
            >
              <Input placeholder="请输入访问路由" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      {iconSelectorVisible && (
        <IconSelector visible={iconSelectorVisible} onSelected={onIconSelected} />
      )}
    </Modal>
  );
};
export default Edit;
