import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Form, Input, Select, TreeSelect, Row, Col, message, DatePicker } from 'antd';
import { userApi } from '../../api/user';
import { deptApi } from '../../api/dept';
import { postApi, PostVO } from '../../api/Post';
import { UserVO, WorkstationNode } from '../../types';
import { getIntDictOptions, DICT_TYPE, setDictOptions, DictDataType } from '../../utils/dict';
import { handleTree } from '../../utils/tree';
import { useTranslation } from 'react-i18next';
import { dictDataApi } from '../../api/DictData';
import dayjs, { Dayjs } from 'dayjs';

const { TextArea } = Input;
const LONG_TERM_EXPIRE_TIME = '2099-12-31 00:00:00';

const toDayjsValue = (value?: Date | string | number): Dayjs | undefined => {
  if (!value && value !== 0) {
    return undefined;
  }

  const normalizedValue =
    typeof value === 'string' && /^\d+$/.test(value.trim())
      ? Number(value)
      : value;

  const dayjsValue = dayjs(normalizedValue);
  return dayjsValue.isValid() ? dayjsValue : undefined;
};

interface UserFormProps {
  onSuccess?: (type: 'create' | 'update') => void;
}

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

const UserForm = forwardRef<UserFormRef, UserFormProps>(({ 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 [form] = Form.useForm();
  const [workstationList, setWorkstationList] = useState<WorkstationNode[]>([]);
  const [deptList, setDeptList] = useState<any[]>([]);
  const [postList, setPostList] = useState<PostVO[]>([]);
  const [sexOptions, setSexOptions] = useState<Array<{ label: string; value: number }>>([]);
  const [originalUserData, setOriginalUserData] = useState<UserVO | null>(null); // 保存原始用户数据

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

    // 加载性别字典数据
    let sexDictOptions: Array<{ label: string; value: number }> = [];
    
    try {
      // 先从缓存获取
      const cachedOptions = getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX);
      if (cachedOptions && cachedOptions.length > 0) {
        sexDictOptions = cachedOptions.map(item => ({ label: item.label, value: item.value }));
        setSexOptions(sexDictOptions);
      } else {
        // 如果缓存中没有，从 API 获取
        const response = await dictDataApi.getDictDataPage({
          pageNo: 1,
          pageSize: -1,
          dictType: DICT_TYPE.SYSTEM_USER_SEX,
        });
        
        const data = (response as any)?.data || response;
        const dictList = data?.list || [];
        
        if (Array.isArray(dictList) && dictList.length > 0) {
          const dictOptions: DictDataType[] = dictList.map((item: any) => ({
            dictType: item.dictType,
            label: item.label,
            value: item.value,
            colorType: item.colorType || '',
            cssClass: item.cssClass || '',
          }));
          
          // 缓存字典数据
          setDictOptions(DICT_TYPE.SYSTEM_USER_SEX, dictOptions);
          
          // 转换为选项格式
          sexDictOptions = getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX).map(item => ({
            label: item.label,
            value: item.value,
          }));
          
          setSexOptions(sexDictOptions);
          console.log('UserForm: 获取性别字典成功', sexDictOptions);
        } else {
          // 如果 API 没有数据，使用默认选项
          throw new Error('API 返回空数据');
        }
      }
    } catch (error) {
      console.error('加载性别字典失败:', error);
      // 使用默认选项
      sexDictOptions = [
        { label: '男', value: 1 },
        { label: '女', value: 2 },
      ];
      setSexOptions(sexDictOptions);
    }

    // 加载部门列表
    try {
      const deptData = await deptApi.getSimpleDeptList();
      const deptTreeData = deptData.map(dept => ({
        id: dept.id!,
        name: dept.name,
        parentId: dept.parentId,
      }));
      const treeData = handleTree(deptTreeData, 'id', 'parentId', 'children');
      setDeptList(treeData);
    } catch (error) {
      console.error('加载部门列表失败:', error);
      setDeptList([]);
    }

    // 加载岗位列表（使用真正的岗位接口）
    try {
      const posts = await postApi.getSimplePostList();
      setPostList(posts || []);
    } catch (error) {
      console.error('加载岗位列表失败:', error);
      setPostList([]);
    }

    // 修改时，设置数据
    if (id) {
      setFormLoading(true);
      try {
        const userData = await userApi.getUser(id);
        // 保存原始用户数据，以便提交时包含所有字段
        setOriginalUserData(userData);
        
        // 处理性别字段：确保转换为数字类型，并且值在字典选项中存在
        let sexValue: number | undefined = undefined;
        if (userData.sex !== undefined && userData.sex !== null) {
          const sexNum = typeof userData.sex === 'string' ? parseInt(userData.sex, 10) : Number(userData.sex);
          // 检查值是否在字典选项中
          const isValidSex = sexDictOptions.some(option => option.value === sexNum);
          if (isValidSex && !isNaN(sexNum)) {
            sexValue = sexNum;
          }
        }
        
        // 处理字段名映射：后端返回 postIds，表单字段名是 workstationIds
        form.setFieldsValue({
          ...userData,
          workstationIds: userData.postIds || userData.workstationIds || [],
          deptId: userData.deptId,
          sex: sexValue, // 使用处理后的性别值
          expireTime: toDayjsValue(userData.expireTime),
        });
        
        console.log('设置表单值 - 性别:', { 
          original: userData.sex, 
          converted: sexValue,
          sexOptions: sexDictOptions 
        });
      } catch (error: any) {
        message.error(error.message || t('form.getUserInfoFailed'));
      } finally {
        setFormLoading(false);
      }
    } else {
      // 新增时设置默认值
      setOriginalUserData(null);
      form.setFieldsValue({
        status: 0,
        workstationIds: [],
        // 默认过期时间：2099-12-31 00:00:00
        expireTime: dayjs(LONG_TERM_EXPIRE_TIME),
      });
    }
  };

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

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      const normalizedValues = {
        ...values,
        expireTime: values.expireTime ? values.expireTime.format('YYYY-MM-DD HH:mm:ss') : undefined,
      };
      
      setFormLoading(true);
      try {
        if (formType === 'create') {
          // 新增模式下，处理字段名映射：workstationIds -> postIds
          const createData: any = {
            ...normalizedValues,
          };
          // 将 workstationIds 映射为 postIds
          if (createData.workstationIds) {
            createData.postIds = createData.workstationIds;
            // 删除 workstationIds 字段，避免传递错误的字段名
            delete createData.workstationIds;
          }
          console.log('新增用户数据:', createData); // 调试用
          await userApi.createUser(createData as UserVO);
          message.success(t('form.createSuccess'));
        } else {
          // 编辑模式下，合并原始数据和表单数据，确保所有必要字段都被传递
          const updateData: any = {
            // 保留原始数据中的字段（这些字段用户不能编辑但需要传递）
            ...(originalUserData || {}),
            // 用表单数据覆盖可编辑字段
            ...normalizedValues,
            // 确保 id 存在
            id: originalUserData?.id || normalizedValues.id,
          };
          
          // 如果密码为空，则移除密码字段
          if (!updateData.password || updateData.password.trim() === '') {
            delete updateData.password;
          }
          
          // 处理字段名映射：workstationIds -> postIds（后端需要 postIds）
          if (updateData.workstationIds) {
            updateData.postIds = updateData.workstationIds;
            // 删除 workstationIds 字段，避免传递错误的字段名
            delete updateData.workstationIds;
          }
          
          // 确保必要字段存在
          if (!updateData.avatar && originalUserData?.avatar) {
            updateData.avatar = originalUserData.avatar;
          }
          if (!updateData.createTime && originalUserData?.createTime) {
            updateData.createTime = originalUserData.createTime;
          }
          if (!updateData.loginDate && originalUserData?.loginDate) {
            updateData.loginDate = originalUserData.loginDate;
          }
          if (!updateData.loginIp && originalUserData?.loginIp) {
            updateData.loginIp = originalUserData.loginIp;
          }
          if (updateData.status === undefined && originalUserData?.status !== undefined) {
            updateData.status = originalUserData.status;
          }
          
          console.log('提交的用户数据:', updateData); // 调试用
          await userApi.updateUser(updateData as UserVO);
          message.success(t('form.updateSuccess'));
        }
        setDialogVisible(false);
        onSuccess?.(formType);
      } catch (error: any) {
        message.error(error.message || t('form.operationFailed'));
      } finally {
        setFormLoading(false);
      }
    } catch (error) {
      // 表单验证失败
    }
  };

  // 将部门树形数据转换为 TreeSelect 需要的格式
  const convertDeptToTreeSelectData = (nodes: any[]): any[] => {
    return nodes.map(node => ({
      title: node.name,
      value: node.id,
      key: node.id,
      children: node.children ? convertDeptToTreeSelectData(node.children) : undefined,
    }));
  };

  return (
    <Modal
      title={dialogTitle}
      open={dialogVisible}
      onCancel={() => setDialogVisible(false)}
      onOk={submitForm}
      confirmLoading={formLoading}
      okText={t('common.confirm')}
      cancelText={t('common.cancel')}
      width={800}
      destroyOnClose
    >
      <Form
        form={form}
        labelCol={{ span: 7 }}
        wrapperCol={{ span: 17 }}
        initialValues={{
          status: 0,
          workstationIds: [],
        }}
      >
        {formType === 'create' ? (
          <>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label={t('form.account')}
                  name="username"
                  rules={[{ required: true, message: t('form.accountRequired') }]}
                >
                  <Input placeholder={t('form.accountPlaceholder')} />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  label={t('form.userPassword')}
                  name="password"
                  rules={[{ required: true, message: t('form.userPasswordRequired') }]}
                >
                  <Input.Password placeholder={t('form.userPasswordPlaceholder')} />
                </Form.Item>
              </Col>
            </Row>
          </>
        ) : (
          // 编辑模式下，隐藏必要字段以确保提交时包含这些字段
          <>
            <Form.Item name="id" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="username" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="password" hidden>
              <Input.Password />
            </Form.Item>
            <Form.Item name="avatar" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="createTime" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="loginDate" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="loginIp" hidden>
              <Input />
            </Form.Item>
            <Form.Item name="status" hidden>
              <Input />
            </Form.Item>
          </>
        )}

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={t('form.nickname')}
              name="nickname"
              rules={[{ required: true, message: t('form.nicknameRequired') }]}
            >
              <Input placeholder={t('form.nicknamePlaceholder')} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={t('form.departmentName')} name="deptId">
              <TreeSelect
                treeData={convertDeptToTreeSelectData(deptList)}
                placeholder={t('form.selectDept')}
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item label={t('form.workstation')} name="workstationIds">
              <Select
                mode="multiple"
                placeholder={t('form.selectPosition')}
                options={postList.map(post => ({
                  label: post.name,
                  value: post.id,
                }))}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t('form.mobile')}
              name="mobile"
              rules={[
                {
                  pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
                  message: t('form.mobilePhoneError') || '请输入正确的手机号码',
                },
              ]}
            >
              <Input maxLength={11} placeholder={t('form.mobilePlaceholder')} />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={t('form.deptEmail')}
              name="email"
              rules={[
                {
                  type: 'email',
                  message: t('form.emailError') || '请输入正确的邮箱地址',
                },
              ]}
            >
              <Input maxLength={50} placeholder={t('form.deptEmailPlaceholder')} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label={t('form.userSex')} name="sex">
              <Select placeholder={t('common.pleaseSelect')}>
                {sexOptions.map(option => (
                  <Select.Option key={option.value} value={option.value}>
                    {option.label}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              label={t('form.cardNumber')}
              name="cardNfc"
            >
              <Input placeholder={t('form.cardNumberPlaceholder')} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              label={t('form.expireTime')}
              name="expireTime"
              rules={[{ required: true, message: t('form.expireTimeRequired') }]}
            >
              <DatePicker
                style={{ width: '100%' }}
                format="YYYY-MM-DD HH:mm:ss"
                showTime={{ format: 'HH:mm:ss' }}
                placeholder={t('form.expireTimePlaceholder')}
                renderExtraFooter={() => (
                  <div
                    style={{ color: '#1677ff', cursor: 'pointer' }}
                    onClick={() => form.setFieldValue('expireTime', dayjs(LONG_TERM_EXPIRE_TIME))}
                  >
                    {t('form.longTermValid')}
                  </div>
                )}
              />
            </Form.Item>
          </Col>
        </Row>

        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              label={t('form.remark')}
              name="remark"
              labelCol={{ span: 3 }}
              wrapperCol={{ span: 21 }}
            >
              <TextArea rows={3} placeholder={t('form.remarkPlaceholder')} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

UserForm.displayName = 'UserForm';

export default UserForm;
