import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Modal, Form, Input, Select, Radio, Spin, InputNumber } from 'antd';
import { slotApi, LockCabinetSlotVO } from '../../api/lockCabinet/slots';
import { lockCabinetApi } from '../../api/lockCabinet';
import { hardwareApi } from '../../api/Hardware';
import { toast } from 'sonner';
import { DICT_TYPE, getStrDictOptions } from '../../utils/dict';

interface SlotFormProps {
  onSuccess?: () => void;
  cabinetId?: string;
}

export interface SlotFormRef {
  open: (type: string, id?: number) => void;
}

const SlotForm = forwardRef<SlotFormRef, SlotFormProps>(({ onSuccess, cabinetId }, ref) => {
  const [dialogVisible, setDialogVisible] = useState(false);
  const [dialogTitle, setDialogTitle] = useState('');
  const [formLoading, setFormLoading] = useState(false);
  const [formType, setFormType] = useState<'create' | 'update'>('create');
  const [currentId, setCurrentId] = useState<number | undefined>();
  const [form] = Form.useForm();
  const [cabinetOptions, setCabinetOptions] = useState<{ label: string; value: number }[]>([]);
  const [hardwareOptions, setHardwareOptions] = useState<{ label: string; value: number }[]>([]);
  const [slotTypeOptions] = useState(() => getStrDictOptions(DICT_TYPE.SLOT_TYPE));
  const [isOccupiedOptions] = useState(() => getStrDictOptions(DICT_TYPE.ISOCCUPIED_STATUS));
  const [statusOptions] = useState(() => getStrDictOptions(DICT_TYPE.SLOT_STATUS));

  // 获取机柜列表
  const getCabinetList = async () => {
    try {
      const response = await lockCabinetApi.getIsLockCabinetPage({ pageNo: 1, pageSize: -1 });
      const options = response.list.map(item => ({
        label: item.cabinetName,
        value: (item as any).id || item.cabinetId!,
      }));
      setCabinetOptions(options);
    } catch (error) {
      console.error('获取机柜列表失败:', error);
    }
  };

  // 获取硬件列表
  const getHardwareList = async () => {
    try {
      const response = await hardwareApi.listHardware({ pageNo: 1, pageSize: -1 });
      const options = response.list.map(item => ({
        label: item.hardwareName,
        value: item.id!,
      }));
      setHardwareOptions(options);
    } catch (error) {
      console.error('获取硬件列表失败:', error);
    }
  };

  // 当弹窗打开时重置表单
  useEffect(() => {
    if (dialogVisible) {
      const timer = setTimeout(() => {
        form.resetFields();
      }, 0);
      return () => clearTimeout(timer);
    }
  }, [dialogVisible, form]);

  // 打开弹窗
  const open = async (type: string, id?: number) => {
    setDialogVisible(true);
    setDialogTitle(type === 'create' ? '新增仓位' : '编辑仓位');
    setFormType(type as 'create' | 'update');
    setCurrentId(id);

    // 加载选项数据
    await Promise.all([getCabinetList(), getHardwareList()]);

    // 修改时，先调详情接口获取数据详情
    if (id) {
      setFormLoading(true);
      try {
        const data = await slotApi.selectIsLockCabinetSlotsById(id);
        // 从返回的数据中获取 id
        const slotId = (data as any).id || data.slotId || id;
        setCurrentId(slotId);
        // 使用 setTimeout 确保 Form 组件已经渲染完成
        setTimeout(() => {
          form.setFieldsValue({
            slotId: slotId,
            cabinetId: data.cabinetId || (cabinetId ? Number(cabinetId) : undefined),
            slotType: data.slotType,
            row: data.row,
            col: data.col,
            isOccupied: data.isOccupied || '0',
            hardwareId: data.hardwareId,
            status: data.status || '0',
            remark: data.remark || '',
          });
        }, 0);
      } catch (error: any) {
        toast.error(error.message || '获取仓位信息失败');
      } finally {
        setFormLoading(false);
      }
    } else {
      // 新增时，如果传入了 cabinetId，自动设置
      setTimeout(() => {
        form.setFieldsValue({
          cabinetId: cabinetId ? Number(cabinetId) : undefined,
          isOccupied: '0',
          status: '0',
        });
      }, 0);
    }
  };

  useImperativeHandle(ref, () => ({
    open,
  }));

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      setFormLoading(true);
      
      const data: LockCabinetSlotVO = {
        ...values,
      };

      if (formType === 'create') {
        // 创建时移除 slotId
        delete data.slotId;
        await slotApi.insertIsLockCabinetSlots(data);
        toast.success('创建成功');
        setDialogVisible(false);
        setTimeout(() => {
          onSuccess?.();
        }, 100);
      } else {
        // 编辑时，必须使用从详情接口获取的 currentId
        if (!currentId) {
          toast.error('缺少仓位ID，无法更新');
          setFormLoading(false);
          return;
        }
        // 接口需要的是 id 而不是 slotId
        delete data.slotId;
        (data as any).id = currentId;
        await slotApi.updateIsLockCabinetSlots(data);
        toast.success('更新成功');
        setDialogVisible(false);
        setTimeout(() => {
          onSuccess?.();
        }, 100);
      }
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      toast.error(error.message || '操作失败');
    } finally {
      setFormLoading(false);
    }
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      width={650}
      destroyOnHidden
    >
      <Spin spinning={formLoading && formType === 'update'}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          initialValues={{
            isOccupied: '0',
            status: '0',
          }}
        >
          <Form.Item
            label="锁柜序号"
            name="cabinetId"
            rules={[{ required: true, message: '锁柜序号不能为空' }]}
          >
            <Select
              placeholder="请选择锁柜"
              options={cabinetOptions}
              disabled={!!cabinetId}
            />
          </Form.Item>

          <Form.Item
            label="仓位类型"
            name="slotType"
            rules={[{ required: true, message: '仓位类型不能为空' }]}
          >
            <Radio.Group>
              {slotTypeOptions.map(dict => (
                <Radio key={dict.value} value={dict.value}>
                  {dict.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="行"
            name="row"
          >
            <InputNumber placeholder="请输入行" style={{ width: '100%' }} min={0} />
          </Form.Item>

          <Form.Item
            label="列"
            name="col"
          >
            <InputNumber placeholder="请输入列" style={{ width: '100%' }} min={0} />
          </Form.Item>

          <Form.Item
            label="是否被占用"
            name="isOccupied"
          >
            <Radio.Group>
              {isOccupiedOptions.map(dict => (
                <Radio key={dict.value} value={dict.value}>
                  {dict.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => prevValues.isOccupied !== currentValues.isOccupied}
          >
            {({ getFieldValue }) =>
              getFieldValue('isOccupied') === '1' ? (
                <Form.Item
                  label="占用仓位的硬件ID"
                  name="hardwareId"
                >
                  <Select
                    placeholder="请选择硬件ID"
                    allowClear
                    options={hardwareOptions}
                  />
                </Form.Item>
              ) : null
            }
          </Form.Item>

          <Form.Item
            label="状态"
            name="status"
          >
            <Radio.Group>
              {statusOptions.map(dict => (
                <Radio key={dict.value} value={dict.value}>
                  {dict.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

          <Form.Item
            label="备注"
            name="remark"
          >
            <Input.TextArea placeholder="请输入备注" rows={4} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
});

SlotForm.displayName = 'SlotForm';

export default SlotForm;

