import React, { useState, useImperativeHandle, forwardRef } from 'react';
import { Modal, Form, Input, Select, TreeSelect, Row, Col, message } 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 } from '../../utils/dict';
import { handleTree } from '../../utils/tree';
import { useTranslation } from 'react-i18next';

const { TextArea } = Input;

interface UserFormProps {
  onSuccess?: () => 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();

    // 加载字典数据
    try {
      const sexDict = getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX);
      setSexOptions(sexDict.map(item => ({ label: item.label, value: item.value })));
    } catch (error) {
      console.error('加载性别字典失败:', error);
      setSexOptions([
        { label: '男', value: 1 },
        { label: '女', value: 2 },
      ]);
    }

    // 加载部门列表
    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);
        form.setFieldsValue({
          ...userData,
          workstationIds: userData.workstationIds || [],
          deptId: userData.deptId,
        });
      } catch (error: any) {
        message.error(error.message || t('form.getUserInfoFailed'));
      } finally {
        setFormLoading(false);
      }
    } else {
      // 新增时设置默认值
      setOriginalUserData(null);
      form.setFieldsValue({
        status: 0,
        workstationIds: [],
      });
    }
  };

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

  // 提交表单
  const submitForm = async () => {
    try {
      const values = await form.validateFields();
      
      setFormLoading(true);
      try {
        if (formType === 'create') {
          await userApi.createUser(values as UserVO);
          message.success(t('form.createSuccess'));
        } else {
          // 编辑模式下，合并原始数据和表单数据，确保所有必要字段都被传递
          const updateData: any = {
            // 保留原始数据中的字段（这些字段用户不能编辑但需要传递）
            ...(originalUserData || {}),
            // 用表单数据覆盖可编辑字段
            ...values,
            // 确保 id 存在
            id: originalUserData?.id || values.id,
          };
          
          // 如果密码为空，则移除密码字段
          if (!updateData.password || updateData.password.trim() === '') {
            delete updateData.password;
          }
          
          // 处理字段名映射：workstationIds -> postIds（如果后端需要 postIds）
          // 如果后端需要 postIds，则使用 workstationIds 的值
          if (updateData.workstationIds && !updateData.postIds) {
            updateData.postIds = 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?.();
      } 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[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
                  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.remark')} name="remark">
              <TextArea rows={3} placeholder={t('form.remarkPlaceholder')} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
});

UserForm.displayName = 'UserForm';

export default UserForm;
