import React, { useState, useEffect, useCallback } from 'react';
import { Modal, Form, Input, DatePicker, InputNumber, message, Spin, Divider, Space, Checkbox, Button, Select, Alert } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';
import API_BASE_URL from '../config';
import UserSearchSelect from './UserSearchSelect';
import { maskPhone } from '../utils/phoneMask';
import { 
  nameLabels, 
  dateLabels, 
  roleOptions,
  contributorAddButtonLabels,
  contributorMainLabels,
  contributorSectionTitles,
  nameTips,
  sourceTips
} from '../constants/achievements';

const { Option } = Select;

const AchievementEdit = ({ id, open, onClose, onSave }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [dicts, setDicts] = useState({
    organizations: [],
    'award-types': [],
    'award-levels': [],
    'paper-types': [],
    'standard-types': [],
    'project-categories': []
  });

  const fetchDicts = useCallback(async () => {
    const types = ['organizations', 'award-types', 'award-levels', 'paper-types', 'standard-types', 'project-categories'];
    const token = localStorage.getItem('token');
    try {
      const results = await Promise.all(
        types.map(t => axios.get(`${API_BASE_URL}/api/dictionaries/${t}`, {
          headers: { Authorization: `Bearer ${token}` }
        }))
      );
      const newDicts = {};
      types.forEach((t, index) => {
        newDicts[t] = results[index].data;
      });
      setDicts(newDicts);
    } catch (error) {
      console.error('获取字典失败', error);
    }
  }, []);

  const fetchDetails = useCallback(async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/achievements/${id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      const achievement = response.data;
      setData(achievement);
      
      // 处理日期字段
      const formData = { 
        ...achievement.details,
        name: achievement.name,
        achievement_date: achievement.achievement_date ? dayjs(achievement.achievement_date) : null,
        remarks: achievement.remarks
      };

      // 统一处理完成人数据，适配 UserSearchSelect
      const contributors = achievement.contributors || [];
      formData.contributors = contributors.map(c => ({
        user: JSON.stringify({ real_name: c.name, phone: c.phone }),
        role: c.role,
        isMain: c.isMain,
        ranking: c.ranking
      }));

      Object.keys(formData).forEach(key => {
        if (key.includes('date') && formData[key] && key !== 'achievement_date') {
          formData[key] = dayjs(formData[key]);
        }
      });
      
      form.setFieldsValue(formData);
    } catch (error) {
      message.error('获取详情失败');
    } finally {
      setLoading(false);
    }
  }, [id, form]);

  useEffect(() => {
    if (open && id) {
      fetchDetails();
      fetchDicts();
    }
  }, [open, id, fetchDetails, fetchDicts]);

  const handleOk = async () => {
    try {
      const values = await form.validateFields();

      // 前端去重校验
      const contributors = values.contributors || [];
      const phoneSet = new Set();
      for (const c of contributors) {
        if (c.user) {
          const u = JSON.parse(c.user);
          if (phoneSet.has(u.phone)) {
            message.error(`完成人列表中存在重复的员工：${u.real_name} (${maskPhone(u.phone)})。请删除重复项。`);
            return;
          }
          phoneSet.add(u.phone);
        }
      }

      // 排名去重校验
      if (!['project', 'transformation'].includes(data.type)) {
        const rankingSet = new Set();
        for (const c of contributors) {
          if (c.ranking) {
            if (rankingSet.has(c.ranking)) {
              message.error(`完成人排名不能重复：第 ${c.ranking} 名出现了多次。`);
              return;
            }
            rankingSet.add(c.ranking);
          }
        }
      }

      const token = localStorage.getItem('token');

      const finalContributors = (values.contributors || []).map(c => {
        const u = c.user ? JSON.parse(c.user) : {};
        return { 
          name: u.real_name, 
          phone: u.phone, 
          role: c.role,
          isMain: c.isMain,
          ranking: c.ranking
        };
      }).filter(c => c.name);

      const { name, achievement_date, remarks, contributors: _ignoredContributors, ...details } = values;

      await axios.put(`${API_BASE_URL}/api/achievements/${id}`, {
        name,
        contributors: finalContributors,
        achievement_date: achievement_date ? achievement_date.format('YYYY-MM-DD') : null,
        remarks,
        details
      }, {
        headers: { Authorization: `Bearer ${token}` }
      });
      message.success('修改成功');
      onSave();
      onClose();
    } catch (error) {
      if (error.response) {
        message.error(error.response.data.message || '修改失败');
      }
    }
  };

  const renderFields = () => {
    if (!data) return null;
    const type = data.type;
    const hasRanking = !['project', 'transformation'].includes(type);
    const useCheckbox = ['project', 'transformation'].includes(type);
    const isPaper = type === 'paper';

    const commonFields = (
      <>
        {nameTips[type] && (
          <Alert
            message={nameTips[type]}
            type="info"
            showIcon
            style={{ marginBottom: 16, width: 'fit-content' }}
          />
        )}
        <Form.Item 
          name="name" 
          label={nameLabels[type] || "成果名称"} 
          rules={[{ required: true }]}
        >
          <Input />
        </Form.Item>
        
        <Divider orientation="center" style={{ fontWeight: 'bold', fontSize: '16px', margin: '24px 0', color: '#1890ff' }}>
          {contributorSectionTitles[type] || contributorSectionTitles.default}
        </Divider>
        <Form.List name="contributors">
          {(fields, { add, remove }) => (
            <>
              {fields.length > 0 && (
                <Space style={{ display: 'flex', marginBottom: 4 }} align="baseline">
                  <span style={{ display: 'inline-block', width: 250 }}>
                    <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>姓名
                  </span>
                  
                  {hasRanking && (
                    <span style={{ display: 'inline-block', width: 80 }}>
                      <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>排名
                    </span>
                  )}

                  {isPaper && (
                    <span style={{ display: 'inline-block', width: 150 }}>
                      <span style={{ color: '#ff4d4f', marginRight: 4 }}>*</span>角色
                    </span>
                  )}

                  {useCheckbox && (
                    <span>
                      {contributorMainLabels[type] || contributorMainLabels.default}
                    </span>
                  )}
                </Space>
              )}
              {fields.map(({ key, name, ...restField }) => (
                <Space key={key} style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                  <Form.Item
                    {...restField}
                    name={[name, 'user']}
                    rules={[{ required: true, message: '请搜索并选择员工' }]}
                  >
                    <UserSearchSelect placeholder="搜索姓名/手机号" style={{ width: 250 }} />
                  </Form.Item>
                  
                  {hasRanking && (
                    <Form.Item
                      {...restField}
                      name={[name, 'ranking']}
                      rules={[{ required: true, message: '请输入排名' }]}
                    >
                      <InputNumber min={1} placeholder="排名" style={{ width: 80 }} />
                    </Form.Item>
                  )}

                  {isPaper && (
                    <Form.Item
                      {...restField}
                      name={[name, 'role']}
                      rules={[{ required: true, message: '请选择角色' }]}
                    >
                      <Select placeholder="角色" style={{ width: 150 }}>
                        {roleOptions.map(r => <Option key={r} value={r}>{r}</Option>)}
                      </Select>
                    </Form.Item>
                  )}

                  {useCheckbox && (
                    <Form.Item
                      {...restField}
                      name={[name, 'isMain']}
                      valuePropName="checked"
                    >
                      <Checkbox>
                        {contributorMainLabels[type] || contributorMainLabels.default}
                      </Checkbox>
                    </Form.Item>
                  )}

                  {fields.length > 1 && (
                    <MinusCircleOutlined onClick={() => remove(name)} />
                  )}
                </Space>
              ))}
              <Form.Item>
                <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                  {contributorAddButtonLabels[type] || contributorAddButtonLabels.default}
                </Button>
              </Form.Item>
            </>
          )}
        </Form.List>
        <Divider />

        <Form.Item 
          name="achievement_date" 
          label={dateLabels[type] || "成果时间"} 
          rules={[{ required: true }]}
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item name="remarks" label="备注"><Input.TextArea rows={3} /></Form.Item>
      </>
    );

    switch (type) {
      case 'paper':
        return (
          <>
            {commonFields}
            <Form.Item name="first_unit" label="第一完成单位" rules={[{ required: true }]}>
              <Select placeholder="请选择第一完成单位" showSearch>
                {dicts['organizations'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>

            <Form.Item name="paper_type" label="论文水平" rules={[{ required: true }]}>
              <Select placeholder="请选择论文水平">
                {dicts['paper-types'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            
            <Form.Item name="journal_name" label="期刊名称"><Input /></Form.Item>
            <Form.Item name="doi" label="DOI"><Input /></Form.Item>
          </>
        );
      case 'project':
        return (
          <>
            {commonFields}
            <Form.Item name="project_category" label="项目分类">
              <Select placeholder="请选择项目分类">
                {dicts['project-categories'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            {sourceTips[type] && (
              <Alert
                message={sourceTips[type]}
                type="info"
                showIcon
                style={{ marginBottom: 16, width: 'fit-content' }}
              />
            )}
            <Form.Item name="source" label="项目来源"><Input /></Form.Item>
          </>
        );
      case 'award':
        return (
          <>
            {commonFields}
            <Form.Item name="award_type" label="奖励种类">
              <Select placeholder="请选择奖励种类">
                {dicts['award-types'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            <Form.Item name="award_level" label="奖励等级">
              <Select placeholder="请选择奖励等级">
                {dicts['award-levels'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            <Form.Item name="award_unit" label="授奖单位">
              <Input placeholder="请输入授奖单位" />
            </Form.Item>
          </>
        );
      case 'standard':
        return (
          <>
            {commonFields}
            <Form.Item name="standard_type" label="标准种类">
              <Select placeholder="请选择标准种类">
                {dicts['standard-types'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            <Form.Item name="standard_no" label="标准编号" rules={[{ required: true }]}><Input /></Form.Item>
            <Form.Item name="implement_date" label="实施日期"><DatePicker style={{ width: '100%' }} /></Form.Item>
          </>
        );
      case 'monograph':
        return (
          <>
            {commonFields}
            <Form.Item name="publisher" label="出版社"><Input /></Form.Item>
            <Form.Item name="isbn" label="ISBN"><Input /></Form.Item>
          </>
        );
      case 'report':
        return (
          <>
            {commonFields}
            <Form.Item name="report_type" label="技术报告类型" rules={[{ required: true }]}><Input /></Form.Item>
            <Form.Item name="recipient" label="发布（提报）对象" rules={[{ required: true }]}><Input /></Form.Item>
          </>
        );
      case 'plan':
        return (
          <>
            {commonFields}
          </>
        );
      case 'patent':
        return (
          <>
            {commonFields}
            <Form.Item name="patent_no" label="专利号" rules={[{ required: true }]}><Input /></Form.Item>
            <Form.Item name="assignee" label="权利人" rules={[{ required: true }]}>
              <Select placeholder="请选择权利人" showSearch>
                {dicts['organizations'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            <Form.Item name="patent_type" label="专利类型" rules={[{ required: true }]}>
              <Select placeholder="请选择专利类型">
                <Select.Option value="发明专利">发明专利</Select.Option>
                <Select.Option value="实用新型专利">实用新型专利</Select.Option>
                <Select.Option value="外观设计专利">外观设计专利</Select.Option>
              </Select>
            </Form.Item>
          </>
        );
      case 'transformation':
        return (
          <>
            {commonFields}
            <Form.Item name="project_category" label="项目分类">
              <Select placeholder="请选择项目分类">
                {dicts['project-categories'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            <Form.Item name="trans_method" label="转化方式"><Input /></Form.Item>
            <Form.Item name="trans_amount" label="转化金额 (元)"><InputNumber style={{ width: '100%' }} /></Form.Item>
          </>
        );
      case 'software':
        return (
          <>
            {commonFields}
            <Form.Item name="reg_no" label="登记号" rules={[{ required: true }]}><Input /></Form.Item>
            <Form.Item name="owner_unit" label="著作权人" rules={[{ required: true }]}>
              <Select placeholder="请选择著作权人" showSearch>
                {dicts['organizations'].filter(d => d.name !== '待定').map(d => <Select.Option key={d.id} value={d.name}>{d.name}</Select.Option>)}
              </Select>
            </Form.Item>
            <Form.Item name="acquisition_method" label="权利取得方式" rules={[{ required: true }]}>
              <Select placeholder="请选择权利取得方式">
                <Select.Option value="原始取得">原始取得</Select.Option>
                <Select.Option value="继受取得">继受取得</Select.Option>
              </Select>
            </Form.Item>
            <Form.Item name="scope" label="权利范围" rules={[{ required: true }]}>
              <Select placeholder="请选择权利范围">
                <Select.Option value="全部权利">全部权利</Select.Option>
                <Select.Option value="部分权利">部分权利</Select.Option>
              </Select>
            </Form.Item>
          </>
        );
      default:
        return null;
    }
  };

  return (
    <Modal
      title="修改成果信息"
      open={open}
      onOk={handleOk}
      onCancel={onClose}
      width={700}
      destroyOnClose
    >
      <Spin spinning={loading}>
        <Form form={form} layout="vertical">
          {renderFields()}
        </Form>
      </Spin>
    </Modal>
  );
};

export default AchievementEdit;
