import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, DatePicker, Button, Tree, Select, message, Spin, Upload } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { categoryTree, uploadFile, superiorLockList, getDeptList, library, libraryData } from '../services';
import type { UploadFile } from 'antd/es/upload/interface';
const areaOptions = [
  { label: '全球', value: 'global' },
  { label: '新加坡', value: 'singapore' },
  { label: '香港', value: 'hongkong' },
];
const approveTypeOptions = [
  { label: '是', value: 'online' },
  { label: '否', value: 'offline' },
];

// TS 类型定义
interface TreeNodeType {
  id: string;
  key: string;
  categoryName: string;
  lockType?: number;
  children?: TreeNodeType[];
  [key: string]: any;
}

interface Props {
  visible: boolean;
  onCancel: () => void;
  onSuccess?: () => void;
}
interface DeptOption {
  userDept: string;
  userDeptId: string;
}

const convertToTreeData = (data: any[] = []): TreeNodeType[] => {
  return (data || []).map(item => ({
    ...item,
    key: item.id,
    title: item.categoryName,
    lockType: item.lockType || 0,
    children: item.children ? convertToTreeData(item.children) : [],
  }));
};

// 递归更新lockType字段
const updateLockType = (nodes: TreeNodeType[], key: string, val: number) => {
  nodes.forEach(n => {
    if (n.key === key) n.lockType = val;
    if (n.children) updateLockType(n.children, key, val);
  });
};


const CategoryAddModal: React.FC<Props> = ({ visible, onCancel, onSuccess }) => {
  const [form] = Form.useForm();
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [treeData, setTreeData] = useState<TreeNodeType[]>([]);
  const [loading, setLoading] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);
  //供应商符合性审查
  const [fileList, setFileList] = useState<UploadFile<any>[]>([]);

  const [deptOptions, setDeptOptions] = useState<DeptOption[]>([]);
  // 自定义上传
  const handleCustomRequest = async (options: any) => {
    const { file, onSuccess, onError } = options;
    try {
      // 1. 调用你自己写的上传接口
      const res = await uploadFile(file);
      // 2. 可根据后端返回结构，给 fileList 项增加 url 或其他字段
      const uploadedFile: UploadFile = {
        ...file,
        status: 'done',
        url: res?.data?.url || res?.url, // 按后端返回实际字段
        name: res?.data?.name || file.name,
        coscoAccessWorkAttachments: res
      };
      setFileList([uploadedFile]);
      // 同步到 Form
      form.setFieldsValue({ supplierCompliance: [uploadedFile] });

      onSuccess && onSuccess(res, file);
      message.success('上传成功');
    } catch (e) {
      onError && onError(e);
      message.error('上传失败');
    }
  };

  const init = async (visible: boolean) => {
    if (visible) {
      setLoading(true);
      await superiorLockList();
      await getDeptList().then(res => {
        if (res.code === 200) {
          setDeptOptions(res.data);
        }
      });

      await categoryTree()
        .then(res => {
          if (res.code === 200 && Array.isArray(res.data)) {
            const tData = convertToTreeData(res.data);
            setTreeData(tData);
            // 展开所有节点（防止不显示）
            const keys: string[] = [];
            const collect = (nodes: TreeNodeType[]) => {
              nodes.forEach(n => {
                keys.push(n.key);
                if (n.children && n.children.length) collect(n.children);
              });
            };
            collect(tData);
            setExpandedKeys(keys);
          } else {
            setTreeData([]);
            setExpandedKeys([]);
          }
        })
        .finally(() => setLoading(false));
    }
    // eslint-disable-next-line
  };

  // 清空选项
  useEffect(() => {
    if (!visible) {
      setCheckedKeys([]);
      setExpandedKeys([]);
      form.resetFields();
    }
    init(visible)
  }, [visible, form]);

  const handleTreeCheck = (checkedKeysValue: any) => {
    const onlyOneEachLevel = checkedKeysValue;
    setCheckedKeys(onlyOneEachLevel);
    form.setFieldsValue({ categoryKeys: onlyOneEachLevel });
  };


  // 提交校验
  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const submitData = {
        name: values.name,
        termOfValidity: values.termOfValidity.format('YYYY-MM-DD'),
        approveType: values.approveType,
        deptId: values.deptId,
        area: values.area,
        categoryIds: checkedKeys.map(id => ({ id, lockType: 0 })),
      } as libraryData

      if (values.attachments && values.attachments.length != 0) {
        const file = values.attachments[0].response;
        submitData.coscoCategoryLibrarAttachments = {
          attachmentsType: values.approveType,
          fileName: file.fileName,
          fileType: file.fileType,
          fileSize: file.fileSize,
          filePath: file.filePath,
          fileUrl: file.url,
        }
      }

      library(submitData).then((res) => {
        if (res.code == 200) {
          form.resetFields();
          message.success('提交成功');
          onSuccess && onSuccess();
        }
      })
    } catch { }
  };
  return (
    <Modal
      visible={visible}
      title="新增品类库"
      onCancel={onCancel}
      footer={null}
      width={700}
      destroyOnClose
    >
      <Spin spinning={loading}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          colon={false}
          style={{ marginTop: 10 }}
          onValuesChange={(changedValues) => {
            if ('approveType' in changedValues) {
              form.validateFields(['attachments']); // 手动校验附件
            }
          }}
        >
          <Form.Item
            label="品类库名称"
            name="name"
            rules={[{ required: true, message: '请输入品类库名称' }]}
          >
            <Input placeholder="请输入品类库名称" />
          </Form.Item>
          <Form.Item
            label="有效期至"
            name="termOfValidity"
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <DatePicker style={{ width: '100%' }} placeholder="年/月/日" />
          </Form.Item>
          <Form.Item
            label="负责部门"
            name="deptId"
            rules={[{ required: true, message: '请选择品类库负责人' }]}
          >
            <Select
              placeholder="请选择品类库负责人"
              style={{ width: 260 }}
              options={deptOptions.map(item => ({
                label: item.userDept,
                value: item.userDeptId,
              }))}
            />
          </Form.Item>
          <Form.Item
            label="选择品类"
            name="categoryKeys"
            required
            rules={[{ required: true, message: '请选择品类' }]}
          >
            <Tree
              checkable
              selectable={false}
              treeData={treeData}
              checkedKeys={checkedKeys}
              expandedKeys={expandedKeys}
              onExpand={setExpandedKeys as any}
              onCheck={handleTreeCheck}
            />
            <span style={{ color: '#888', marginLeft: 4, fontWeight: 400, fontSize: 12 }}>
              （注：同一级品类不可多选）
            </span>
          </Form.Item>
          <Form.Item
            label="区域选择（仅燃油品）"
            name="area"
            rules={[{ required: true, message: '请选择区域' }]}
            required
          >
            <Select
              placeholder="请选择区域"
              style={{ width: 260 }}
              options={areaOptions}
            />
          </Form.Item>
          <Form.Item
            label="是否已走OA签报"
            name="approveType"
            rules={[{ required: true, message: '请选择否已走OA签报' }]}
            required
          >
            <Select
              placeholder="请选择否已走OA签报"
              style={{ width: 260 }}
              options={approveTypeOptions}
            />
          </Form.Item>
          <Form.Item
            label="备注"
            name="remark"
          >
            <Input placeholder="请输入备注" />
          </Form.Item>

          <Form.Item shouldUpdate={(prev, curr) => prev.approveType !== curr.approveType}>
            {() => {
              const isAttachmentRequired = form.getFieldValue('approveType') === 'offline';

              return (
                <Form.Item
                  label={
                    <span>
                      {isAttachmentRequired && <span style={{ color: 'red' }}>*</span>}
                      附件（OA签报证明文件）
                    </span>
                  }
                  name="attachments"
                  rules={[
                    {
                      validator: (_, value) => {
                        if (isAttachmentRequired && (!value || value.length === 0)) {
                          return Promise.reject('请上传OA签报附件');
                        }
                        return Promise.resolve();
                      },
                    },
                  ]}
                  valuePropName="fileList"
                  getValueFromEvent={(e) => (Array.isArray(e) ? e : e?.fileList)}
                >
                  <Upload
                    fileList={fileList}
                    customRequest={handleCustomRequest}
                    beforeUpload={(file) => {
                      if (fileList.length >= 1) {
                        message.error('只能上传一个文件');
                        return Upload.LIST_IGNORE;
                      }
                      return true;
                    }}
                    onChange={({ fileList: newFileList }) => {
                      setFileList(newFileList);
                      form.setFieldsValue({
                        supplierCompliance: newFileList,
                        attachments: newFileList,
                      });
                    }}
                    onRemove={(file) => {
                      const newList = fileList.filter(item => item.uid !== file.uid);
                      setFileList(newList);
                      form.setFieldsValue({
                        supplierCompliance: newList,
                        attachments: newList,
                      });
                    }}
                    accept=".pdf,.doc,.docx"
                    maxCount={1}
                  >
                    <Button icon={<UploadOutlined />}>点击上传文件</Button>
                  </Upload>
                </Form.Item>
              );
            }}
          </Form.Item>  {/* ✅ 外层 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>
      </Spin>
    </Modal>
  );
};

export default CategoryAddModal;
