import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Modal, Form, Input, Select, Radio, Spin, Row, Col } from 'antd';
import { lockCabinetApi, LockCabinetVO } from '../../api/lockCabinet';
import { postApi, PostVO } from '../../api/Post';
import { toast } from 'sonner';
import { DICT_TYPE, getStrDictOptions } from '../../utils/dict';
import UploadImg from './UploadImg';
import { useTranslation } from 'react-i18next';

interface LockCabinetFormProps {
  onSuccess?: () => void;
}

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

const LockCabinetForm = forwardRef<LockCabinetFormRef, LockCabinetFormProps>(({ onSuccess }, ref) => {
  const { t } = useTranslation();
  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 [postOptions, setPostOptions] = useState<{ label: string; value: number }[]>([]);
  const [isOnlineOptions] = useState(() => getStrDictOptions(DICT_TYPE.ISONLINE_STATUS));
  const [statusOptions] = useState(() => getStrDictOptions(DICT_TYPE.CANBINET_STATUS));

  const normalizeId = (val: unknown): number | undefined => {
    if (val === null || val === undefined || val === '') return undefined;
    const n = typeof val === 'number' ? val : Number(val);
    return Number.isFinite(n) ? n : undefined;
  };

  // 获取岗位列表
  const getPostList = async () => {
    try {
      const response = await postApi.getPostPage({ pageNo: 1, pageSize: -1 });
      const data = (response as any)?.data || response;
      const postList = data?.list || [];
      // 转换为选项格式
      const options = postList
        .filter((item: PostVO) => item.id !== undefined)
        .map((item: PostVO) => ({
          label: item.name,
          value: item.id!,
        }));
      setPostOptions(options);
    } catch (error) {
      console.error('获取岗位列表失败:', error);
      toast.error('获取岗位列表失败');
    }
  };

  // 当弹窗打开时重置表单（确保 Form 组件已经渲染）
  useEffect(() => {
    if (dialogVisible) {
      // 使用 setTimeout 确保 Form 组件已经渲染完成
      const timer = setTimeout(() => {
        form.resetFields();
      }, 0);
      return () => clearTimeout(timer);
    }
  }, [dialogVisible, form]);

  // 打开弹窗
  const open = async (type: string, id?: number) => {
    setDialogVisible(true);
    setDialogTitle(type === 'create' ? t('form.addLockCabinet') : t('form.editLockCabinet'));
    setFormType(type as 'create' | 'update');
    setCurrentId(id);

    // 加载选项数据
    await getPostList();

    // 修改时，先调详情接口获取数据详情
    if (id) {
      setFormLoading(true);
      try {
        const data = await lockCabinetApi.selectIsLockCabinetById(id);
        // 从返回的数据中获取 id（后端可能返回 id 而不是 cabinetId）
        const cabinetId = (data as any).id || data.cabinetId || id;
        // 更新 currentId，确保使用从接口返回的 id
        setCurrentId(cabinetId);
        // 使用 setTimeout 确保 Form 组件已经渲染完成
        setTimeout(() => {
          form.setFieldsValue({
            cabinetId: cabinetId,
            cabinetName: data.cabinetName,
            workstationId: normalizeId((data as any).workstationId),
            hardwareId: data.hardwareId,
            serialNumber: data.serialNumber || '',
            isOnline: data.isOnline || '1',
            status: data.status || '1',
            cabinetIcon: data.cabinetIcon || '',
            cabinetPicture: data.cabinetPicture || '',
            remark: data.remark || '',
          });
        }, 0);
      } catch (error: any) {
        toast.error(error.message || t('form.getLockCabinetDetailFailed'));
      } finally {
        setFormLoading(false);
      }
    } else {
      // 使用 setTimeout 确保 Form 组件已经渲染完成
      setTimeout(() => {
        form.setFieldsValue({
          cabinetName: '',
          workstationId: undefined,
          hardwareId: undefined,
          serialNumber: '',
          isOnline: '1',
          status: '1',
          cabinetIcon: '',
          cabinetPicture: '',
          remark: '',
        });
      }, 0);
    }
  };

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

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

      if (formType === 'create') {
        // 创建时移除 cabinetId
        delete data.cabinetId;
        await lockCabinetApi.insertIsLockCabinet(data);
        toast.success(t('form.createSuccess'));
        setDialogVisible(false);
        // 延迟调用 onSuccess，确保对话框已关闭
        setTimeout(() => {
          onSuccess?.();
        }, 100);
      } else {
        // 编辑时，必须使用从详情接口获取的 currentId
        if (!currentId) {
          toast.error(t('form.missingLockCabinetId'));
          setFormLoading(false);
          return;
        }
        // 接口需要的是 id 而不是 cabinetId
        delete data.cabinetId;
        (data as any).id = currentId;
        await lockCabinetApi.updateIsLockCabinet(data);
        toast.success(t('form.updateSuccess'));
        setDialogVisible(false);
        // 延迟调用 onSuccess，确保对话框已关闭
        setTimeout(() => {
          onSuccess?.();
        }, 100);
      }
    } catch (error: any) {
      if (error.errorFields) {
        // 表单验证错误
        return;
      }
      toast.error(error.message || t('form.operationFailed'));
    } finally {
      setFormLoading(false);
    }
  };


  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={740}
      destroyOnHidden
    >
      <Spin spinning={formLoading && formType === 'update'}>
        <Form
          form={form}
          layout="horizontal"
          labelCol={{ flex: '190px' }}
          wrapperCol={{ flex: '1 1 0' }}
          labelWrap
          initialValues={{
            isOnline: '1',
            status: '1',
          }}
        >
          <Form.Item
            label={t('form.cabinetName')}
            name="cabinetName"
            rules={[{ required: true, message: t('form.lockCabinetNameRequired') }]}
          >
            <Input placeholder={t('form.cabinetNamePlaceholder')} />
          </Form.Item>

          <Form.Item
            label={t('form.workstation')}
            name="workstationId"
            rules={[{ required: true, message: t('form.workstationIdRequired') }]}
          >
            <Select
              placeholder={t('form.workstationPlaceholder')}
              allowClear
              options={postOptions}
            />
          </Form.Item>

          <Form.Item
            label={t('table.hardwareSerial')}
            name="serialNumber"
          >
            <Input placeholder={t('form.serialNumberPlaceholder')} />
          </Form.Item>

          <Form.Item
            label={t('common.onlineStatus')}
            name="isOnline"
          >
            <Radio.Group>
              {isOnlineOptions.map(dict => (
                <Radio key={dict.value} value={dict.value}>
                  {dict.label}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>

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

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('table.icon')}
                name="cabinetIcon"
                valuePropName="value"
                getValueFromEvent={(value) => value}
                labelCol={{ span: 12 }}
                wrapperCol={{ span: 10 }}
              >
                <UploadImg
                  height="64px"
                  width="64px"
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('table.image')}
                name="cabinetPicture"
                valuePropName="value"
                getValueFromEvent={(value) => value}
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 18 }}
              >
                <UploadImg
                  height="64px"
                  width="64px"
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            label={t('table.remark')}
            name="remark"
          >
            <Input.TextArea placeholder={t('form.remarkPlaceholder')} rows={4} />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
});

LockCabinetForm.displayName = 'LockCabinetForm';

export default LockCabinetForm;

