import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import {
  Button,
  Card,
  Descriptions,
  Divider,
  Spin,
  message,
  Typography,
  Empty,
  Space,
  Form,
  Radio,
  Input,
  Modal,
  Tag,
  Table,
} from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { getAnnualReviewDetail, submitAnnualReviewScore } from '@/servers/api/supplierAnnual';
import {
  AnnualReviewStatusText,
  AnnualReviewStatusColor,
  ExamineResult,
  ExamineResultText,
} from '@/dicts/supplierAnnualReviewDict';
import styles from './supplierAnnualReview.less';

const { Title } = Typography;
const { TextArea } = Input;

// 评分项接口定义
interface ScoreFormItem {
  id: string;
  name: string;
  description: string;
  examineResult: string;
  remark: string;
}

const SupplierAnnualReviewScore: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [reviewDetail, setReviewDetail] = useState<supplierAnnualReview.ReviewRecord | null>(null);
  const [scoreItems, setScoreItems] = useState<ScoreFormItem[]>([]);

  // 从路由获取ID
  const { id } = history.location.state as { id: string };

  // 获取审查详情
  const fetchReviewDetail = async (reviewId: string) => {
    try {
      setLoading(true);
      const res = await getAnnualReviewDetail(reviewId);
      if (res.success && res.data) {
        setReviewDetail(res.data);

        // 使用接口返回的评分项数据
        if (res.data.scoreItems && res.data.scoreItems.length > 0) {
          setScoreItems(res.data.scoreItems);

          // 初始化表单
          const initialValues: any = {};
          res.data.scoreItems.forEach((item: ScoreFormItem) => {
            initialValues[`examineResult_${item.id}`] = item.examineResult || '';
            initialValues[`remark_${item.id}`] = item.remark || '';
          });

          form.setFieldsValue(initialValues);
        } else {
          message.warning('未找到评分项数据');
        }
      } else {
        message.error(res.message || '获取审查详情失败');
      }
    } catch (error) {
      console.error('获取审查详情失败:', error);
      message.error('获取审查详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (id) {
      fetchReviewDetail(id);
    } else {
      message.error('审查ID不存在，无法获取详情');
      history.goBack();
    }
  }, [id]);

  // 返回列表页
  const handleBack = () => {
    history.goBack();
  };
  // 提交评分
  const submitScore = async () => {
    if (!reviewDetail) return;

    try {
      setSubmitting(true);

      // 准备提交数据
      const formValues = form.getFieldsValue();
      const scoreVoList = scoreItems.map((item) => ({
        id: item.id,
        name: item.name,
        description: item.description,
        examineResult: formValues[`examineResult_${item.id}`],
        remark: formValues[`remark_${item.id}`] || '',
      }));

      const submitData: supplierAnnualReview.ScoreRequest = {
        id: reviewDetail.id,
        scoreVoList,
      };

      const res = await submitAnnualReviewScore(submitData);

      if (res.success) {
        message.success('评审提交成功');
        history.goBack();
      } else {
        message.error(res.message || '评审提交失败');
      }
    } catch (error) {
      console.error('评审提交失败:', error);
      message.error('评审提交失败');
    } finally {
      setSubmitting(false);
    }
  };
  // 提交表单
  const handleSubmit = async () => {
    try {
      // 表单验证
      await form.validateFields();

      // 确认提交
      Modal.confirm({
        title: '确认提交',
        content: '确定要提交评审结果吗？提交后将无法修改。',
        okText: '确定',
        cancelText: '取消',
        onOk: submitScore,
      });
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 获取状态标签
  const getStatusTag = (status: string | undefined, statusName: string | undefined) => {
    if (!status) return <Tag>未知状态</Tag>;
    const color =
      AnnualReviewStatusColor[status as keyof typeof AnnualReviewStatusColor] || 'default';
    const text =
      statusName ||
      AnnualReviewStatusText[status as keyof typeof AnnualReviewStatusText] ||
      '未知状态';
    return <Tag color={color}>{text}</Tag>;
  };

  return (
    <div className="common-container">
      <Card>
        <div className={styles['page-header']}>
          <Title level={4} style={{ margin: 0 }}>
            年度审查评分
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>
        <Spin spinning={loading}>
          {reviewDetail ? (
            <>
              <Card title="基本信息" bordered={false} className={styles['detail-card']}>
                <Descriptions column={2} bordered>
                  <Descriptions.Item label="审查主题">
                    {reviewDetail.annualreviewTheme}
                  </Descriptions.Item>
                  <Descriptions.Item label="供应商名称">{reviewDetail.name}</Descriptions.Item>
                  <Descriptions.Item label="所属部门">
                    {reviewDetail.deptName || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="审查员">
                    {reviewDetail.userName || '-'}
                  </Descriptions.Item>
                  <Descriptions.Item label="开始时间">{reviewDetail.startTime}</Descriptions.Item>
                  <Descriptions.Item label="结束时间">{reviewDetail.endTime}</Descriptions.Item>
                  <Descriptions.Item label="状态">
                    {getStatusTag(reviewDetail.reviewStatus, reviewDetail.reviewStatusName)}
                  </Descriptions.Item>
                </Descriptions>
              </Card>

              <Divider />

              <Card title="审查结果" bordered={false} className={styles['detail-card']}>
                <Form form={form} layout="vertical" className={styles['score-form']}>
                  {scoreItems.length > 0 ? (
                    <Table
                      rowKey="id"
                      dataSource={scoreItems}
                      pagination={false}
                      bordered
                      className={styles['score-table']}
                      columns={[
                        {
                          title: '评分项',
                          dataIndex: 'name',
                          width: '15%',
                        },
                        {
                          title: '评分项说明',
                          dataIndex: 'description',
                          width: '25%',
                        },
                        {
                          title: '评审结果',
                          dataIndex: 'examineResult',
                          width: '25%',
                          render: (_, record) => (
                            <Form.Item
                              name={`examineResult_${record.id}`}
                              rules={[{ required: true, message: '请选择评审结果' }]}
                              style={{ marginBottom: 0 }}
                            >
                              <Radio.Group>
                                <Radio value={ExamineResult.QUALIFIED}>
                                  {ExamineResultText[ExamineResult.QUALIFIED]}
                                </Radio>
                                <Radio value={ExamineResult.UNQUALIFIED}>
                                  {ExamineResultText[ExamineResult.UNQUALIFIED]}
                                </Radio>
                              </Radio.Group>
                            </Form.Item>
                          ),
                        },
                        {
                          title: '评审说明',
                          dataIndex: 'remark',
                          width: '35%',
                          render: (_, record) => (
                            <Form.Item
                              name={`remark_${record.id}`}
                              style={{ marginBottom: 0 }}
                            >
                              <TextArea
                                rows={2}
                                placeholder="请输入评审说明"
                                maxLength={200}
                              />
                            </Form.Item>
                          ),
                        },
                      ]}
                    />
                  ) : (
                    <Empty description="暂无评分项数据" />
                  )}

                  <div className={styles['score-actions']}>
                    <Button
                      type="primary"
                      icon={<SaveOutlined />}
                      onClick={handleSubmit}
                      loading={submitting}
                    >
                      提交评审
                    </Button>
                  </div>
                </Form>
              </Card>
            </>
          ) : (
            !loading && <Empty description="暂无审查详情数据" />
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default SupplierAnnualReviewScore;
