import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Modal, Form, Input, Select, Row, Col, message } from 'antd';
import { segregationPointApi, SegregationPointVO } from '../api/spm/index';
import { postApi, PostVO } from '../api/Post';
import { dictDataApi } from '../api/DictData';
import { loginApi } from '../api/Login';
import { getStrDictOptions, getDictOptions, setDictOptions, DICT_TYPE } from '../utils/dict';
import { toast } from 'sonner';
import { useTranslation } from 'react-i18next';
import UploadImg from './lockCabinet/UploadImg';

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

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

const SegregationPointForm = forwardRef<SegregationPointFormRef, SegregationPointFormProps>(
  ({ 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 [currentPointId, setCurrentPointId] = useState<number | undefined>(); // 保存当前编辑的隔离点ID
    const [detailData, setDetailData] = useState<SegregationPointVO | null>(null); // 保存详情接口返回的完整数据
    const [form] = Form.useForm();
    const [selectedImageIndex, setSelectedImageIndex] = useState(-1);
    const [imageMap, setImageMap] = useState<Record<number, string>>({});

    // 下拉选项数据
    const [postOptions, setPostOptions] = useState<Array<{ label: string; value: number }>>([]);
    const [pointGroupOptions, setPointGroupOptions] = useState<Array<{ label: string; value: number }>>([]);
    const [powerSourceOptions, setPowerSourceOptions] = useState<Array<{ label: string; value: string }>>([]);

    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 open = async (type: string, id?: number) => {
      setDialogVisible(true);
      setDialogTitle(type === 'create' ? t('form.addSegregationPoint') : t('form.editSegregationPoint'));
      setFormType(type as 'create' | 'update');
      form.resetFields();
      setSelectedImageIndex(-1);
      setImageMap({});
      
      // 保存当前编辑的ID
      setCurrentPointId(id);

      // 加载下拉选项数据
      await loadOptionsData();

      // 修改时，调用详情接口获取数据
      if (id) {
        setFormLoading(true);
        try {
          console.log('SegregationPointForm: 开始获取隔离点详情, id =', id);
          const response = await segregationPointApi.selectIsIsolationPointById(id);
          console.log('SegregationPointForm: 接口响应', response);
          
          // 处理响应数据格式
          const data = (response as any)?.data || response;
          console.log('SegregationPointForm: 处理后的数据', data);
          
          // 保存详情接口返回的完整数据
          setDetailData(data as SegregationPointVO);
          
          // 确保 id 存在（从详情接口返回的数据或传入的 id）
          const currentId = data.id || id;
          
          // 更新当前编辑的ID（确保使用详情接口返回的ID）
          setCurrentPointId(currentId);
          
          // 设置表单值（用于回显）- 使用详情接口返回的完整数据
          const formValues = {
            pointName: data.pointName ?? '',
            pointIcon: data.pointIcon ?? '',
            pointPicture: data.pointPicture ?? '',
            // pointNfc: 如果是空字符串或 null，设置为 undefined（表单中不显示）；如果有值则使用值
            pointNfc: data.pointNfc && data.pointNfc.trim() !== '' ? data.pointNfc : undefined,
            workstationId: normalizeId((data as any).workstationId),
            // lotoId 可能为 null，需要保留 null 值（不要转换为 undefined）
            // 如果为 null 则设置为 undefined（表单 Select 组件需要 undefined 而不是 null）
            lotoId: data.lotoId !== undefined && data.lotoId !== null ? data.lotoId : undefined,
            powerType: data.powerType ?? '',
            // pointSerialNumber: 如果是空字符串或 null，设置为 undefined（表单中不显示）；如果有值则使用值
            pointSerialNumber: data.pointSerialNumber && data.pointSerialNumber.trim() !== '' ? data.pointSerialNumber : undefined,
            remark: data.remark ?? '',
          };
          
          console.log('SegregationPointForm: 设置表单值（从详情接口获取）', formValues);
          console.log('SegregationPointForm: 详情接口返回的原始数据', data);
          
          // 使用 setTimeout 确保表单已渲染
          setTimeout(() => {
            form.setFieldsValue(formValues);
          }, 0);

          // 获取隔离点图标
          await loadIsolationIcons(data.pointIcon);
        } catch (error: any) {
          console.error('SegregationPointForm: 获取隔离点详情失败', error);
          toast.error(error.message || t('form.getSegregationPointDetailFailed'));
        } finally {
          setFormLoading(false);
        }
      } else {
        // 新增时清空ID和详情数据
        setCurrentPointId(undefined);
        setDetailData(null);
        // 新增时也加载图标
        await loadIsolationIcons();
      }
    };

    // 加载下拉选项数据
    const loadOptionsData = async () => {
      try {
        // 获取岗位数据
        const postRes = await postApi.getPostPage({ pageNo: 1, pageSize: -1 });
        const data = (postRes as any)?.data || postRes;
        const postList = data?.list || [];
        const options = postList
          .filter((item: PostVO) => item.id !== undefined)
          .map((item: PostVO) => ({
            label: item.name,
            value: item.id!,
          }));
        setPostOptions(options);

        // 获取点位分组数据（从字典 point_group）
        try {
          const dictRes = await dictDataApi.getDictDataPage({ pageNo: 1, pageSize: -1, dictType: DICT_TYPE.POINT_GROUP });
          const data = (dictRes as any)?.list ?? (dictRes as any)?.data?.list ?? (Array.isArray(dictRes) ? dictRes : []);
          const list = Array.isArray(data) ? data : [];
          setDictOptions(DICT_TYPE.POINT_GROUP, list.map((item: any) => ({
            dictType: DICT_TYPE.POINT_GROUP,
            label: item.label,
            value: item.value,
            colorType: item.colorType || '',
            cssClass: item.cssClass || '',
          })));
          const options = getDictOptions(DICT_TYPE.POINT_GROUP).map((item) => ({
            label: item.label,
            value: Number(item.value),
          }));
          setPointGroupOptions(options);
        } catch (dictError) {
          console.error('获取点位分组字典失败:', dictError);
          setPointGroupOptions([]);
        }

        // 获取能量源数据（从字典 power_source）
        try {
          const powerRes = await dictDataApi.getDictDataPage({ pageNo: 1, pageSize: -1, dictType: DICT_TYPE.POWER_SOURCE });
          const powerData = (powerRes as any)?.list ?? (powerRes as any)?.data?.list ?? (Array.isArray(powerRes) ? powerRes : []);
          const powerList = Array.isArray(powerData) ? powerData : [];
          setDictOptions(DICT_TYPE.POWER_SOURCE, powerList.map((item: any) => ({
            dictType: DICT_TYPE.POWER_SOURCE,
            label: item.label,
            value: item.value,
            colorType: item.colorType || '',
            cssClass: item.cssClass || '',
          })));
          setPowerSourceOptions(getStrDictOptions(DICT_TYPE.POWER_SOURCE));
        } catch (powerError) {
          console.error('获取能量源字典失败:', powerError);
          setPowerSourceOptions([]);
        }
      } catch (error) {
        console.error('加载选项数据失败:', error);
        toast.error('加载选项数据失败');
      }
    };

    // 加载隔离点图标
    const loadIsolationIcons = async (selectedIcon?: string) => {
      try {
        const sysAttrKey1 = 'sys.icon_set.isolation';
        const iconRes = await loginApi.getSystemAttributeByKey(sysAttrKey1);
        const values = (iconRes as any).sysAttrValue?.split(',').map((v: string) => v.trim()) || [];
        
        const iconPromises = values.map((value: string) => 
          loginApi.getSystemAttributeByKey(value)
        );
        const iconResponses = await Promise.all(iconPromises);
        
        const newImageMap: Record<number, string> = {};
        iconResponses.forEach((response: any, index: number) => {
          newImageMap[index] = response.sysAttrValue || '';
        });
        setImageMap(newImageMap);

        // 确定选中的图片索引
        if (selectedIcon) {
          const index = getImageIndexByIcon(selectedIcon, newImageMap);
          setSelectedImageIndex(index);
        }
      } catch (error) {
        console.error('加载隔离点图标失败:', error);
      }
    };

    // 获取图片索引
    const getImageIndexByIcon = (iconUrl: string, imageMap: Record<number, string>): number => {
      for (const [index, imageUrl] of Object.entries(imageMap)) {
        if (imageUrl === iconUrl) {
          return Number(index);
        }
      }
      return -1;
    };


    // 选择隔离点图标
    const selectIcon = (imageUrl: string, index: number) => {
      form.setFieldsValue({ pointIcon: imageUrl });
      setSelectedImageIndex(index);
    };

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

    // 提交表单
    const submitForm = async () => {
      try {
        const values = await form.validateFields();
        
        setFormLoading(true);
        try {
          if (formType === 'create') {
            // 新增时，使用表单数据
            const data: SegregationPointVO = {
              pointCode: '', // 新增时 pointCode 为空，由后端生成
              pointName: values.pointName,
              pointIcon: values.pointIcon,
              pointPicture: values.pointPicture,
              // pointNfc: 如果为空字符串或 undefined，设置为 null；否则使用填入的值
              pointNfc: values.pointNfc && values.pointNfc.trim() !== '' ? values.pointNfc : null as any,
              workstationId: normalizeId(values.workstationId),
              lotoId: values.lotoId != null && values.lotoId !== '' ? Number(values.lotoId) : null,
              powerType: values.powerType != null && values.powerType !== '' ? Number(values.powerType) : undefined,
              // pointSerialNumber: 如果为空字符串或 undefined，设置为 null；否则使用填入的值
              pointSerialNumber: values.pointSerialNumber && values.pointSerialNumber.trim() !== '' ? values.pointSerialNumber : null as any,
              remark: values.remark,
            };
            await segregationPointApi.addinsertIsIsolationPoint(data);
            toast.success(t('common.addSuccess'));
          } else {
            // 编辑时，确保有详情数据
            if (!detailData) {
              toast.error('缺少详情数据，无法更新');
              setFormLoading(false);
              return;
            }
            
            // 直接使用详情接口返回的完整数据作为基础，然后用表单中修改的值覆盖
            // 这样确保所有字段都来自详情接口，而不是写死的值
            const updateData: any = {
              // 先复制详情接口返回的所有字段（包括 id、lotoId: null 等所有字段）
              ...detailData,
              // 确保使用 id（详情接口返回的是 id，不是 pointId）
              id: detailData.id || currentPointId,
              // 然后用表单中用户修改的值覆盖（只覆盖表单中存在的字段）
              pointName: values.pointName !== undefined ? values.pointName : detailData.pointName,
              pointIcon: values.pointIcon !== undefined ? values.pointIcon : detailData.pointIcon,
              pointPicture: values.pointPicture !== undefined ? values.pointPicture : detailData.pointPicture,
              // pointNfc: 如果表单中有值且不为空字符串，使用表单值；如果为空字符串，设置为 null；如果为 undefined，使用详情数据中的原值（可能是 null）
              pointNfc: values.pointNfc !== undefined 
                ? (values.pointNfc && values.pointNfc.trim() !== '' ? values.pointNfc : null)
                : detailData.pointNfc,
              workstationId: values.workstationId !== undefined ? normalizeId(values.workstationId) : normalizeId((detailData as any).workstationId),
              // lotoId 处理：接口要求数字类型；表单中有值时转为 Number，清空时为 null
              lotoId: values.lotoId !== undefined
                ? (values.lotoId != null && values.lotoId !== '' ? Number(values.lotoId) : null)
                : detailData.lotoId,
              powerType: values.powerType !== undefined
                ? (values.powerType != null && values.powerType !== '' ? Number(values.powerType) : undefined)
                : detailData.powerType,
              // pointSerialNumber: 如果表单中有值且不为空字符串，使用表单值；如果为空字符串，设置为 null；如果为 undefined，使用详情数据中的原值（可能是 null）
              pointSerialNumber: values.pointSerialNumber !== undefined 
                ? (values.pointSerialNumber && values.pointSerialNumber.trim() !== '' ? values.pointSerialNumber : null)
                : detailData.pointSerialNumber,
              remark: values.remark !== undefined ? values.remark : detailData.remark,
            };
            
            // 如果详情数据中有 pointId 字段，删除它（因为详情接口返回的是 id，不是 pointId）
            if ('pointId' in updateData) {
              delete updateData.pointId;
            }
            
            console.log('SegregationPointForm: 详情接口返回的完整数据', detailData);
            console.log('SegregationPointForm: 表单值', values);
            console.log('SegregationPointForm: 提交更新数据（基于详情接口完整数据）', updateData);
            await segregationPointApi.updateIsIsolationPoint(updateData);
            toast.success(t('common.updateSuccess'));
          }
          setDialogVisible(false);
          onSuccess?.();
        } catch (error: any) {
          console.error('SegregationPointForm: 提交失败', error);
          toast.error(error.message || t('common.operationFailed'));
        } finally {
          setFormLoading(false);
        }
      } catch (error) {
        // 表单验证失败
        console.error('SegregationPointForm: 表单验证失败', error);
      }
    };

    // 图片上传：使用通用上传组件（内部会调用 /infra/file/upload）

    return (
      <Modal
        title={dialogTitle}
        open={dialogVisible}
        onCancel={() => setDialogVisible(false)}
        onOk={submitForm}
        confirmLoading={formLoading}
        okText={t('common.confirm')}
        cancelText={t('common.cancel')}
        width={960}
        destroyOnClose
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          layout="horizontal"
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('form.segregationPointName')}
                name="pointName"
                rules={[{ required: true, message: t('form.segregationPointNameRequired') }]}
              >
                <Input placeholder={t('form.segregationPointNamePlaceholder')} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('table.segregationPointNfc')}
                name="pointNfc"
              >
                <Input placeholder={t('form.segregationPointNfcPlaceholder')} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('form.pointGroup')}
                name="lotoId"
              >
                <Select placeholder={t('form.pointGroupPlaceholder')} options={pointGroupOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('form.workstation')}
                name="workstationId"
                rules={[{ required: true, message: t('form.workstationRequired') }]}
              >
                <Select
                  placeholder={t('form.workstationPlaceholder')}
                  allowClear
                  options={postOptions}
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('form.energySource')}
                name="powerType"
              >
                <Select placeholder={t('form.energySourcePlaceholder')} options={powerSourceOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('table.segregationPointSerial')}
                name="pointSerialNumber"
              >
                <Input placeholder={t('form.segregationPointSerialPlaceholder')} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('table.function')}
                name="remark"
              >
                <Input placeholder={t('form.functionPlaceholder')} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label={t('form.segregationPointIcon')}
                name="pointIcon"
              >
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                  {Object.entries(imageMap).map(([index, imageUrl]) => (
                    <div
                      key={index}
                      onClick={() => selectIcon(imageUrl, Number(index))}
                      style={{
                        width: '55px',
                        height: '55px',
                        cursor: 'pointer',
                        border: selectedImageIndex === Number(index) ? '2px solid rgb(2, 86, 255)' : '2px solid transparent',
                        padding: '2px',
                        transition: 'border-color 0.3s',
                      }}
                    >
                      <img src={imageUrl} alt={t('form.isolationIconAlt')} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    </div>
                  ))}
                </div>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label={t('form.segregationPointImage')}
                name="pointPicture"
              >
                <UploadImg width="100px" height="100px" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    );
  }
);

SegregationPointForm.displayName = 'SegregationPointForm';

export default SegregationPointForm;

