import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Modal, Form, Input, Select, message, Card, Popconfirm, Tag, Progress, DatePicker } from 'antd';
import { UserAddOutlined, EditOutlined, DeleteOutlined, SearchOutlined, FileTextOutlined } from '@ant-design/icons';
import axios from 'axios';
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
import html2canvas from 'html2canvas';
import API_BASE_URL from '../config';
import AchievementFormRenderer from '../components/AchievementFormRenderer';
import { maskPhone } from '../utils/phoneMask';

const { RangePicker } = DatePicker;

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingUser, setEditingUser] = useState(null);
  const [keyword, setKeyword] = useState('');
  const [exportMonthRange, setExportMonthRange] = useState(null);
  const [departments, setDepartments] = useState([]);
  const [form] = Form.useForm();
  const currentUser = JSON.parse(localStorage.getItem('user') || '{}');

  // 批量导出相关状态
  const [batchLoading, setBatchLoading] = useState(false);
  const [batchProgress, setBatchProgress] = useState({ current: 0, total: 0 });
  const [batchCurrentData, setBatchCurrentData] = useState(null);

  useEffect(() => {
    fetchUsers();
    fetchDepartments();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const fetchDepartments = async () => {
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/dictionaries/departments`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setDepartments(response.data);
    } catch (error) {
      message.error('获取部门列表失败');
    }
  };

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/users`, {
        headers: { Authorization: `Bearer ${token}` },
        params: { keyword }
      });
      setUsers(response.data);
    } catch (error) {
      message.error('获取用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingUser(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingUser(record);
    form.setFieldsValue({
      username: record.username,
      role: record.role,
      real_name: record.real_name,
      department: record.department,
  // 批量导出相关状态
    });
    setIsModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const token = localStorage.getItem('token');
      await axios.delete(`${API_BASE_URL}/api/users/${id}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      message.success('删除成功');
      fetchUsers();
    } catch (error) {
      message.error(error.response?.data?.message || '删除失败');
    }
  };

  const handleSubmit = async (values) => {
    try {
      const token = localStorage.getItem('token');
      if (editingUser) {
        await axios.put(`${API_BASE_URL}/api/users/${editingUser.id}`, values, {
          headers: { Authorization: `Bearer ${token}` }
        });
        message.success('修改成功');
      } else {
        await axios.post(`${API_BASE_URL}/api/users`, values, {
          headers: { Authorization: `Bearer ${token}` }
        });
        message.success('创建成功');
      }
      setIsModalVisible(false);
      fetchUsers();
    } catch (error) {
      message.error(error.response?.data?.message || '操作失败');
    }
  };

  const hasExportRange = () => (
    exportMonthRange &&
    exportMonthRange.length === 2 &&
    exportMonthRange[0] &&
    exportMonthRange[1]
  );

  const getExportDateParams = () => {
    if (!hasExportRange()) {
      return {};
    }

    return {
      startDate: exportMonthRange[0].startOf('month').format('YYYY-MM-DD'),
      endDate: exportMonthRange[1].endOf('month').format('YYYY-MM-DD')
    };
  };

  const getExportRangeSuffix = () => {
    if (!hasExportRange()) {
      return '';
    }

    return `${exportMonthRange[0].format('YYYYMM')}_to_${exportMonthRange[1].format('YYYYMM')}`;
  };

  const triggerExportUserAchievements = (user) => {
    if (hasExportRange()) {
      handleExportUserAchievements(user);
      return;
    }

    Modal.confirm({
      title: '未选择导出年月范围',
      content: '当前将导出该用户全部成果。若需按年月导出，请先选择上方“导出年月范围”。',
      okText: '继续导出',
      cancelText: '取消',
      onOk: () => handleExportUserAchievements(user)
    });
  };

  const handleExportUserAchievements = async (user) => {
    setBatchLoading(true);
    setBatchProgress({ current: 0, total: 0 });
    const zip = new JSZip();
    const token = localStorage.getItem('token');
    const exportDateParams = getExportDateParams();
    const exportRangeSuffix = getExportRangeSuffix();

    try {
      // 1. 获取用户的所有成果
      // 使用 export_action=true 标记，以便后端审计日志记录为“导出用户成果数据”
      const response = await axios.get(`${API_BASE_URL}/api/achievements`, {
        headers: { Authorization: `Bearer ${token}` },
        params: { 
          keyword: user.username, // 使用手机号作为关键词匹配参与人
          export_action: 'true',
          ...exportDateParams
        }
      });
      
      const achievements = response.data;
      if (achievements.length === 0) {
        if (exportRangeSuffix) {
          message.warning('该用户在所选年月范围内没有成果数据');
          setBatchLoading(false);
          return;
        }
        message.warning('该用户没有相关成果数据');
        setBatchLoading(false);
        return;
      }

      setBatchProgress({ current: 0, total: achievements.length });

      // 2. 生成 CSV 清单
      let csvContent = '\uFEFF'; // BOM for Excel
      csvContent += "ID,成果名称,类型,状态,提交人,参与人,归属部门,成果时间\n";
      
      achievements.forEach(item => {
        const typeMap = {
          paper: '论文',
          project: '项目',
          award: '奖励',
          standard: '标准',
          monograph: '专著',
          report: '技术报告',
          plan: '规划',
          patent: '专利',
          transformation: '成果转化',
          software: '软著'
        };
        const statusMap = {
          pending: '待审核',
          approved: '已通过',
          rejected: '已驳回'
        };
        
        const contributors = (item.contributors || []).map(c => c.name).join('; ');
        const departments = (item.assigned_departments || []).join('; ');
        const date = item.achievement_date ? new Date(item.achievement_date).toLocaleDateString() : '';
        
        // 处理字段中的逗号和引号
        const escape = (field) => `"${String(field || '').replace(/"/g, '""')}"`;
        
        csvContent += [
          item.id,
          escape(item.name),
          escape(typeMap[item.type] || item.type),
          escape(statusMap[item.status] || item.status),
          escape(item.submitter_name),
          escape(contributors),
          escape(departments),
          escape(date)
        ].join(',') + "\n";
      });
      
      zip.file(`成果清单_${user.real_name}${exportRangeSuffix ? `_${exportRangeSuffix}` : ''}.csv`, csvContent);

      // 3. 批量生成表单图片
      for (let i = 0; i < achievements.length; i++) {
        const item = achievements[i];
        setBatchProgress({ current: i + 1, total: achievements.length });
        
        try {
          // 获取详情
          const detailRes = await axios.get(`${API_BASE_URL}/api/achievements/${item.id}`, {
            headers: { Authorization: `Bearer ${token}` }
          });
          const detailData = detailRes.data;
          
          // 渲染
          setBatchCurrentData(detailData);
          await new Promise(resolve => setTimeout(resolve, 500)); // 等待渲染
          
          // 截图
          const element = document.getElementById('batch-export-container-user');
          if (element) {
            const exportWidth = Math.max(element.scrollWidth, element.offsetWidth);
            const exportHeight = Math.max(element.scrollHeight, element.offsetHeight);
            const canvas = await html2canvas(element, {
              useCORS: true,
              scale: 2,
              backgroundColor: '#ffffff',
              width: exportWidth,
              height: exportHeight,
              windowWidth: exportWidth,
              windowHeight: exportHeight,
              scrollX: 0,
              scrollY: 0
            });
            
            const imgData = canvas.toDataURL('image/png').split(',')[1];
            const fileName = `成果表单_${detailData.name || '未命名'}_${detailData.id}.png`;
            const safeFileName = fileName.replace(/[\\/:*?"<>|]/g, '_');
            zip.file(safeFileName, imgData, { base64: true });
          }
        } catch (err) {
          console.error(`处理成果 ${item.id} 失败`, err);
        }
      }

      // 4. 下载 ZIP
      const content = await zip.generateAsync({ type: 'blob' });
      saveAs(content, `用户成果导出_${user.real_name}${exportRangeSuffix ? `_${exportRangeSuffix}` : ''}_${new Date().toISOString().slice(0,10)}.zip`);
      message.success('导出完成');

    } catch (error) {
      console.error(error);
      message.error('导出失败');
    } finally {
      setBatchLoading(false);
      setBatchCurrentData(null);
    }
  };

  const columns = [
    { title: '手机号', dataIndex: 'username', key: 'username', render: (value) => maskPhone(value) || '-' },
    { title: '真实姓名', dataIndex: 'real_name', key: 'real_name' },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      render: (text, record) => (
        <Space>
          {text}
          {record.dept_status === 'pending' && (
            <Tag color="error">待确认</Tag>
          )}
        </Space>
      )
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: (role) => {
        const roleMap = {
          super_admin: { color: 'purple', text: '超级管理员' },
          admin: { color: 'blue', text: '管理员' },
          senior_user: { color: 'cyan', text: '高级用户' },
          intermediate_user: { color: 'geekblue', text: '中级用户' },
          user: { color: 'green', text: '普通用户' },
          maintainer: { color: 'orange', text: '系统维护员' }
        };
        const { color, text } = roleMap[role] || { color: 'default', text: role };
        return <Tag color={color}>{text}</Tag>;
      }
    },
    { title: '创建时间', dataIndex: 'created_at', key: 'created_at', render: (t) => new Date(t).toLocaleString() },
    {
      title: '操作',
      key: 'action',
      width: 300,
      render: (_, record) => (
        <Space>
          <Button icon={<EditOutlined />} onClick={() => handleEdit(record)}>编辑</Button>
          {(currentUser.role === 'super_admin' || currentUser.role === 'admin') && (
            <Button icon={<FileTextOutlined />} onClick={() => triggerExportUserAchievements(record)}>导出成果</Button>
          )}
          {currentUser.role === 'super_admin' && (
            <Popconfirm title="确定删除吗？" onConfirm={() => handleDelete(record.id)}>
              <Button danger icon={<DeleteOutlined />}>删除</Button>
            </Popconfirm>
          )}
        </Space>
      ),
    },
  ];

  return (
    <Card 
      title="用户权限管理" 
      extra={currentUser.role === 'super_admin' && <Button type="primary" icon={<UserAddOutlined />} onClick={handleAdd}>新增用户</Button>}
    >
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Input 
            placeholder="搜索手机号/姓名/部门" 
            style={{ width: 250 }} 
            value={keyword}
            onChange={e => setKeyword(e.target.value)}
            onPressEnter={fetchUsers}
            allowClear
          />
          <Button type="primary" icon={<SearchOutlined />} onClick={fetchUsers}>查询</Button>
          {(currentUser.role === 'super_admin' || currentUser.role === 'admin') && (
            <>
              <span style={{ color: '#666' }}>导出年月范围：</span>
              <RangePicker
                picker="month"
                allowClear
                value={exportMonthRange}
                onChange={(dates) => setExportMonthRange(dates)}
                placeholder={['导出起始年月', '导出结束年月']}
              />
            </>
          )}
        </Space>
      </div>
      <Table columns={columns} dataSource={users} rowKey="id" loading={loading} />

      <Modal
        title={editingUser ? '编辑用户' : '新增用户'}
        open={isModalVisible}
        onOk={() => form.submit()}
        onCancel={() => setIsModalVisible(false)}
        destroyOnClose
      >
        <Form form={form} onFinish={handleSubmit} layout="vertical">
          <Form.Item
            name="username"
            label="手机号"
            rules={[
              { required: true, message: '请输入手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式' }
            ]}
          >
            <Input disabled={!!editingUser} />
          </Form.Item>
          <Form.Item name="real_name" label="真实姓名" rules={[{ required: true, message: '请输入真实姓名' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="department" label="部门" rules={[{ required: true, message: '请选择部门' }]}>
            <Select showSearch placeholder="请选择部门">
              {departments.map(dept => (
                <Select.Option key={dept.id} value={dept.name}>{dept.name}</Select.Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item name="role" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
            <Select disabled={currentUser.role === 'maintainer'}>
              <Select.Option value="super_admin">超级管理员</Select.Option>
              <Select.Option value="admin">管理员</Select.Option>
              <Select.Option value="senior_user">高级用户</Select.Option>
              <Select.Option value="intermediate_user">中级用户</Select.Option>
              <Select.Option value="user">普通用户</Select.Option>
              <Select.Option value="maintainer">系统维护员</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="password"
            label={editingUser ? "重置密码（留空不修改）" : "初始密码"}
            rules={[{ required: !editingUser }]}
          >
            <Input.Password />
          </Form.Item>
        </Form>
      </Modal>

      {/* 批量导出进度遮罩 */}
      <Modal
        open={batchLoading}
        footer={null}
        closable={false}
        centered
        maskClosable={false}
        title="正在导出用户成果数据"
      >
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Progress 
            type="circle" 
            percent={batchProgress.total > 0 ? Math.round((batchProgress.current / batchProgress.total) * 100) : 0} 
            format={() => `${batchProgress.current} / ${batchProgress.total}`}
          />
          <div style={{ marginTop: 20, color: '#666' }}>
            正在生成成果清单和表单图片...<br/>
            请勿关闭页面，这可能需要几分钟。
          </div>
        </div>
      </Modal>

      {/* 隐藏的渲染容器 */}
      <div 
        id="batch-export-container-user" 
        style={{ 
          position: 'fixed', 
          left: '-100000px', 
          top: 0, 
          width: '1100px', 
          backgroundColor: '#fff', 
          padding: '40px',
          boxSizing: 'border-box',
          overflow: 'visible',
          zIndex: -1 
        }}
      >
        {batchCurrentData && (
          <>
            <div style={{ textAlign: 'center', marginBottom: '30px', borderBottom: '2px solid #1890ff', paddingBottom: '20px' }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: '10px' }}>
                <img src="/logo.png" style={{ height: '50px', marginRight: '15px' }} onError={(e) => e.target.style.display='none'} alt="logo" />
                <h1 style={{ margin: 0, fontSize: '28px', fontWeight: 'bold', color: '#333', whiteSpace: 'normal', wordBreak: 'break-all', overflowWrap: 'anywhere' }}>科技成果管理表单</h1>
              </div>
              <div style={{ fontSize: '14px', color: '#666' }}>生成时间：{new Date().toLocaleString()}</div>
            </div>
            <AchievementFormRenderer data={batchCurrentData} />
          </>
        )}
      </div>
    </Card>
  );
};

export default UserManagement;
