import React, { useEffect, useState } from 'react';
import { Tree, Button, Modal, Form, Input, Select, message, Popconfirm, Spin } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { categoryTree, add, edit, del } from './services';

interface CategoryNode {
  id: string;
  categoryName: string;
  parentId: string;
  type: string; // "0" 分类, "1" 品类
  orderBy: string;
  children?: CategoryNode[] | null;
}
interface CategoryFormFields {
  id?: string;
  categoryName: string;
  parentId: string;
  type: string;
  orderBy: string;
}

const CategoryManage: React.FC = () => {
  const [treeData, setTreeData] = useState<CategoryNode[]>([]);
  const [loading, setLoading] = useState(false);

  // 弹窗相关
  const [modalOpen, setModalOpen] = useState(false);
  const [modalType, setModalType] = useState<'add' | 'edit'>('add');
  const [currentNode, setCurrentNode] = useState<CategoryNode | null>(null);
  const [form] = Form.useForm<CategoryFormFields>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);

  // 加载树数据
  const fetchTree = async () => {
    setLoading(true);
    const res = await categoryTree();
    setLoading(false);
    if (res.code === 200) {
      setTreeData(res.data || []);
    } else {
      message.error(res.message || '加载失败');
    }
  };

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

  useEffect(() => {
    if (treeData && treeData.length) {
      const allKeys: React.Key[] = [];
      const collectKeys = (nodes: any[]) => {
        nodes.forEach(node => {
          allKeys.push(node.id);
          if (node.children && node.children.length) {
            collectKeys(node.children);
          }
        });
      };
      collectKeys(treeData);
      setExpandedKeys(allKeys);
    }
  }, [treeData]);

const convertToTreeData = (data?: CategoryNode[]): any[] =>
  (data || []).map(item => ({
    key: item.id,
    title: (
      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          minWidth: 600,
        }}
      >
        <span style={{ flexShrink: 0, fontWeight: 500 }}>{item.categoryName}</span>
        {/* 横线，从名字右 5px 到按钮左 8px */}
        <div
          style={{
            flex: 1,
            height: 0,
            borderBottom: '1px dashed #e5e5e5',
            margin: '0 8px 0 5px',
          }}
        />
        {/* 按钮组整体贴右 */}
        <span style={{ flexShrink: 0, display: 'flex', gap: 4 }}>
          <Button
            size="small"
            icon={<PlusOutlined />}
            type="link"
            disabled={item.type === '1'}
            onClick={e => {
              e.stopPropagation();
              setModalType('add');
              setCurrentNode(item);
              form.resetFields();
              form.setFieldsValue({
                categoryName: '',
                parentId: item.id,
                type: '1',
                orderBy: '',
              });
              setModalOpen(true);
            }}
          >添加</Button>
          <Button
            size="small"
            icon={<EditOutlined />}
            type="link"
            onClick={e => {
              e.stopPropagation();
              setModalType('edit');
              setCurrentNode(item);
              form.setFieldsValue({
                id: item.id,
                categoryName: item.categoryName,
                parentId: item.parentId,
                type: item.type,
                orderBy: item.orderBy,
              });
              setModalOpen(true);
            }}
          >修改</Button>
          {/* <Popconfirm
            title="确定要删除该节点吗？"
            onConfirm={() => handleDelete(item.id)}
            disabled={!!(item.children && item.children.length > 0)}
          >
            <Button
              size="small"
              danger
              icon={<DeleteOutlined />}
              type="link"
              disabled={!!(item.children && item.children.length > 0)}
              onClick={e => e.stopPropagation()}
            >删除</Button>
          </Popconfirm> */}
        </span>
      </div>
    ),
    children: item.children ? convertToTreeData(item.children) : [],
  }));


  // 添加/修改提交
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      console.log(values);
      
      let res;
      if (modalType === 'add') {
        res = await add(values);
      } else {
        res = await edit({ ...values, id: currentNode?.id });
      }
      if (res.code === 200) {
        message.success(modalType === 'add' ? '添加成功' : '修改成功');
        setModalOpen(false);
        fetchTree();
      } else {
        message.error(res.message || '操作失败');
      }
    } catch (err) { }
  };

  // 删除
  const handleDelete = async (id: string) => {
    const res = await del(id);
    if (res.code === 200) {
      message.success('删除成功');
      fetchTree();
    } else {
      message.error(res.message || '删除失败');
    }
  };

  // 新增顶级
  const handleAddRoot = () => {
    setModalType('add');
    setCurrentNode(null);
    form.resetFields();
    form.setFieldsValue({
      categoryName: '',
      parentId: '0',
      type: '0',
      orderBy: '',
    });
    setModalOpen(true);
  };

  return (
    <div style={{ padding: 24 }}>
      <h2>品类管理</h2>
      <Button
        type="primary"
        style={{ marginBottom: 16 }}
        onClick={handleAddRoot}
      >
        新增顶级分类
      </Button>
      <Spin spinning={loading}>
        <Tree
          treeData={convertToTreeData(treeData)}
          expandedKeys={expandedKeys}
          onExpand={keys => setExpandedKeys(keys as React.Key[])}
          style={{ background: '#fff', padding: 16, borderRadius: 6 }}
        />
      </Spin>

      {/* 弹窗 */}
      <Modal
        visible={modalOpen}
        title={modalType === 'add' ? '新增品类' : '修改品类'}
        onCancel={() => setModalOpen(false)}
        onOk={handleOk}
        destroyOnClose
      >
        <Form
          form={form}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ parentId: currentNode?.id || '0', type: '1' }}
        >
          <Form.Item
            name="categoryName"
            label="品类名称"
            rules={[{ required: true, message: '请输入品类名称' }]}
          >
            <Input placeholder="请输入品类名称" />
          </Form.Item>
          {/* <Form.Item name="parentId" label="上级ID">
            <Input disabled value={currentNode?.id || '0'} />
          </Form.Item> */}
          <Form.Item
            name="type"
            label="类型"
            rules={[{ required: true }]}
          >
            <Select disabled={modalType === 'edit'}>
              <Select.Option value="0">分类</Select.Option>
              <Select.Option value="1">品类</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="orderBy"
            label="排序"
            rules={[{ required: true, message: '请输入排序' }]}
          >
            <Input placeholder="数字越小越靠前" type="number" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManage;
