import React, { useState } from 'react';
import { Card, Button, Table, Tag, Space, message, Typography, Alert } from 'antd';
import { SafetyCertificateOutlined, EditOutlined, ReloadOutlined } from '@ant-design/icons';
import axios from 'axios';
import API_BASE_URL from '../config';
import AchievementEdit from '../components/AchievementEdit';

const { Title, Text } = Typography;

const DataValidation = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [editVisible, setEditVisible] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [hasValidated, setHasValidated] = useState(false);

  const user = JSON.parse(localStorage.getItem('user') || '{}');

  const handleValidate = async () => {
    setLoading(true);
    try {
      const token = localStorage.getItem('token');
      const response = await axios.get(`${API_BASE_URL}/api/achievements/validate`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      setData(response.data);
      setHasValidated(true);
      if (response.data.length === 0) {
        message.success('校验完成，未发现异常数据');
      } else {
        message.warning(`校验完成，发现 ${response.data.length} 条异常数据`);
      }
    } catch (error) {
      console.error('校验失败', error);
      message.error('校验失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '成果名称',
      dataIndex: 'name',
      key: 'name',
      width: 300,
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <span style={{ fontWeight: 600 }}>{text}</span>
          <Tag color="blue">{record.type}</Tag>
        </Space>
      )
    },
    {
      title: '提交人',
      dataIndex: 'submitter',
      key: 'submitter',
      width: 150,
    },
    {
      title: '异常详情',
      dataIndex: 'errors',
      key: 'errors',
      render: (errors) => (
        <ul style={{ margin: 0, paddingLeft: 20, color: '#ff4d4f' }}>
          {errors.map((err, idx) => (
            <li key={idx}>{err}</li>
          ))}
        </ul>
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_, record) => (
        user.role === 'super_admin' ? (
          <Button 
            type="primary" 
            size="small" 
            icon={<EditOutlined />} 
            onClick={() => { setSelectedId(record.id); setEditVisible(true); }}
          >
            修改
          </Button>
        ) : (
          <span style={{ color: '#999' }}>无权限</span>
        )
      )
    }
  ];

  return (
    <div>
      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <Title level={4} style={{ margin: 0 }}>
              <SafetyCertificateOutlined style={{ marginRight: 8 }} />
              数据一致性校验
            </Title>
            <Text type="secondary">
              全量扫描数据库，检查成果完成人、归属部门以及各类字典字段（如论文类型、奖励等级等）的数据一致性。
            </Text>
          </div>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            loading={loading} 
            onClick={handleValidate}
            size="large"
          >
            开始全量校验
          </Button>
        </div>
      </Card>

      {hasValidated && (
        <Card title={`校验结果：发现 ${data.length} 条异常数据`}>
          {data.length > 0 ? (
            <Table 
              columns={columns} 
              dataSource={data} 
              rowKey="id" 
              pagination={{ pageSize: 10 }}
              rowClassName={() => 'validation-error-row'}
            />
          ) : (
            <Alert message="恭喜！所有数据均校验通过，未发现异常。" type="success" showIcon />
          )}
        </Card>
      )}

      <AchievementEdit 
        id={selectedId} 
        open={editVisible} 
        onClose={() => { setEditVisible(false); setSelectedId(null); }} 
        onSave={() => {
          setEditVisible(false);
          setSelectedId(null);
          handleValidate(); // 修改后重新校验
        }} 
      />
      
      <style>{`
        .validation-error-row {
          background-color: #fff1f0;
        }
        .validation-error-row:hover > td {
          background-color: #ffccc7 !important;
        }
      `}</style>
    </div>
  );
};

export default DataValidation;
