import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, DatePicker, Button, Tree, Select, message } from 'antd';

const treeData = [
  {
    title: '货物',
    key: 'goods',
    children: [
      { title: '燃油', key: 'fuel' },
      { title: '润滑油', key: 'oil' },
      { title: '船用物料', key: 'marine' },
    ],
  },
  {
    title: '工程',
    key: 'project',
    children: [
      { title: '土建', key: 'civil' },
      { title: '机电', key: 'me' },
    ],
  },
  {
    title: '服务',
    key: 'service',
    children: [
      { title: '运输', key: 'transport' },
      { title: '维修', key: 'maintenance' },
    ],
  },
];

const regionOptions = [
  { label: '全球', value: 'global' },
  { label: '新加坡', value: 'singapore' },
  { label: '香港', value: 'hongkong' },
];

interface Props {
  visible: boolean;
  onCancel: () => void;
  onSuccess?: () => void;
}
const CategoryAddModal: React.FC<Props> = ({ visible, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  // 受控 checkedKeys
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  // 切换“选择品类”时，自动清除“区域选择”
  useEffect(() => {
    if (!visible) {
      setCheckedKeys([]);
      form.resetFields();
    }
  }, [visible]);
  // 只能同一级单选
  const handleTreeCheck = (checkedKeysValue: any, info: any) => {
    console.log(checkedKeysValue);

    let checked = Array.isArray(checkedKeysValue) ? checkedKeysValue : checkedKeysValue.checked;
    // 记录每个一级key的选中（只保留同级最后一次点击）
    const map: Record<string, string> = {};
    checked.forEach(k => {
      const parent = treeData.find(node =>
        node.key === k || node.children?.some(c => c.key === k)
      );
      if (parent) map[parent.key] = k;
    });
    const onlyOneEachLevel = Object.values(map);
    console.log(onlyOneEachLevel,'onlyOneEachLevel');
    

    setCheckedKeys(onlyOneEachLevel); // 实时刷新
    form.setFieldsValue({ categoryKeys: onlyOneEachLevel });
  };

  // 提交校验
  const handleOk = async () => {
    try {
      await form.validateFields();
      message.success('提交成功（模拟）');
      onSuccess && onSuccess();
      onCancel();
      form.resetFields();
    } catch { }
  };

  return (
    <Modal
      visible={visible}
      title="新增品类库"
      onCancel={onCancel}
      footer={null}
      width={700}
      destroyOnClose
    >
      <Form
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        colon={false}
        style={{ marginTop: 10 }}
      >
        <Form.Item
          label={<span>品类库名称</span>}
          name="storeName"
          rules={[{ required: true, message: '请输入品类库名称' }]}
        >
          <Input placeholder="请输入品类库名称" />
        </Form.Item>
        <Form.Item
          label={<span>有效期至</span>}
          name="validTo"
          rules={[{ required: true, message: '请选择有效期' }]}
        >
          <DatePicker style={{ width: '100%' }} placeholder="年/月/日" />
        </Form.Item>
        <Form.Item
          label={<span>负责部门</span>}
          name="ownerDept"
          rules={[{ required: true, message: '请输入品类库负责人' }]}
        >
          <Input placeholder="请输入品类库负责人" />
        </Form.Item>
        <Form.Item
          label={<span>选择品类 </span>}
          name="categoryKeys"
          required
          rules={[ { required: true, message: '请选择品类' },
          ]}
        >
           <Tree
            checkable
            selectable={false}
            treeData={treeData}
            checkedKeys={checkedKeys}
            onCheck={handleTreeCheck}
          />
          <span style={{ color: '#888', marginLeft: 4, fontWeight: 400, fontSize: 12 }}>
            （注：同一级品类不可多选）
          </span>
        </Form.Item>
        <Form.Item
          label={<span>区域选择（仅燃油品）</span>}
          name="region"
          rules={[{ required: true, message: '请选择区域' }]}
          required
        >
          <Select
            placeholder="请选择区域"
            style={{ width: 260 }}
            options={regionOptions}
          />
        </Form.Item>
        <Form.Item wrapperCol={{ span: 24 }} style={{ textAlign: 'center', marginTop: 30 }}>
          <Button type="primary" style={{ width: 160 }} onClick={handleOk}>
            提交审批
          </Button>
          <Button style={{ width: 120, marginLeft: 32 }} onClick={onCancel}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CategoryAddModal;
