import React, { useState, useEffect } from 'react';
import { history, useLocation } from 'umi';
import {
  Button,
  Card,
  Descriptions,
  Divider,
  Spin,
  message,
  Typography,
  Empty,
  Space,
  Form,
  Modal,
} from 'antd';
import { ArrowLeftOutlined, SaveOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { getSupplierScoreDetail, saveEvaluateScore } from '@/servers/api/supplierEvaluate';
import ScoreEvaluationTable from '@/components/ScoreEvaluationTable';
import styles from './supplierEvaluateScore.less';

const { Title } = Typography;
const { confirm } = Modal;

const SupplierEvaluateScoreDetail: React.FC = () => {
  const [form] = Form.useForm();
  const location = useLocation<{
    record: supplierEvaluateScore.SupplierDimensionRecord | supplierEvaluateScore.TaskPageRecord;
    mode?: 'view' | 'score'; // 查看模式或打分模式
    recordType: 'supplier' | 'task'; // 记录类型：供应商或任务
  }>();
  const [loading, setLoading] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [saving, setSaving] = useState<boolean>(false);
  const [scoreDetail, setScoreDetail] = useState<supplierEvaluateScore.ScoreDetailData | null>(
    null,
  );
  const [scoreData, setScoreData] = useState<any[]>([]);
  const [record, setRecord] = useState<any>(null);
  const [mode, setMode] = useState<'view' | 'score'>('view'); // 默认为查看模式
  const [recordType, setRecordType] = useState<'supplier' | 'task'>('supplier'); // 默认为供应商类型

  // 从路由获取传递的记录
  useEffect(() => {
    if (location.state?.record) {
      setRecord(location.state.record);

      // 设置记录类型
      if (location.state.recordType) {
        setRecordType(location.state.recordType);
      }

      // 设置模式
      if (location.state.mode) {
        setMode(location.state.mode);
      } else {
        // 如果没有传递mode，则根据状态判断
        setMode(location.state.record.status === '1' ? 'score' : 'view');
      }
    } else {
      message.error('缺少必要参数，无法获取详情');
      history.goBack();
    }
  }, [location]);

  // 将API数据转换为ScoreEvaluationTable组件所需的格式
  const formatDataForScoreTable = (data: supplierEvaluateScore.ScoreDetailData) => {
    if (!data?.taskIndicatorVo) return [];

    return data.taskIndicatorVo.map((indicator) => {
      return {
        baseIndicator: indicator.baseIndicator,
        indicatorDesc: indicator.indicatorDesc,
        score: indicator.score,
        // 为ScoreEvaluationTable组件添加额外字段
        indicatorNdList:
          indicator.subIndicator
            ?.map((subItem) => {
              // 确保subItem是一个对象，而不是直接渲染
              if (typeof subItem !== 'object' || subItem === null) {
                return null;
              }

              return {
                id: subItem.id,
                subIndicator: subItem.subIndicator,
                score: subItem.subScore,
                isStar: subItem.starIndicator,
                actualScore: subItem.scoreNum || '',
                remark: subItem.remark || '',
              };
            })
            .filter(Boolean) || [],
      };
    });
  };

  // 获取评价打分详情
  const fetchScoreDetail = async () => {
    if (!record?.id) {
      message.error('缺少必要参数，无法获取数据');
      return;
    }

    setLoading(true);
    try {
      const response = await getSupplierScoreDetail(record.id);

      if (response.success && response.data) {
        setScoreDetail(response.data);

        // 转换数据格式
        const formattedData = formatDataForScoreTable(response.data);
        setScoreData(formattedData);
      } else {
        message.error(response.message || '获取评价得分明细失败');
      }
    } catch (error) {
      console.error('获取评价得分明细失败:', error);
      message.error('获取评价得分明细失败');
    } finally {
      setLoading(false);
    }
  };

  // 当记录加载完成后，获取得分明细
  useEffect(() => {
    if (record?.id) {
      fetchScoreDetail();
    }
  }, [record]);

  // 返回上一页
  const handleBack = () => {
    history.goBack();
  };

  // 处理评分数据变更
  const handleScoreDataChange = (newData: any[]) => {
    setScoreData(newData);
  };

  // 提交评分
  const handleSubmit = async () => {
    if (!record?.id) {
      message.error('缺少必要参数，无法提交');
      return;
    }

    // 验证所有二级指标是否都已评分
    const hasEmptyScore = scoreData.some((item) =>
      item.indicatorNdList.some((subItem: any) => !subItem.scoreNum && subItem.scoreNum !== 0),
    );

    if (hasEmptyScore) {
      message.warning('请为所有指标填写评分');
      return;
    }

    // 显示确认对话框
    confirm({
      title: '提交确认',
      icon: <ExclamationCircleOutlined />,
      content: '评分提交后将不可修改，确定要提交吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        setSubmitting(true);
        try {
          // 构建提交数据
          const submitData: supplierEvaluateScore.ScoreSaveRequest = {
            id: record.id,
            scoreVoList: scoreData.flatMap((item) => {
              return item.indicatorNdList.map((subItem: any) => ({
                id: item.id,
                remark: subItem.remark || item.remark || '',
                score: String(subItem.scoreNum || item.score || ''),
              }));
            }),
          };
          const response = await saveEvaluateScore(submitData);

          if (response.success) {
            message.success('评分保存成功');
            history.goBack();
          } else {
            message.error(response.message || '评分保存失败');
          }
        } catch (error) {
          console.error('评分提交失败:', error);
          message.error('评分提交失败');
        } finally {
          setSubmitting(false);
        }
      },
    });
  };

  // 获取评价状态文本
  const getStatusText = (status: string) => {
    const statusMap: { [key: string]: string } = {
      '1': '待评分',
      '2': '已评分',
      '3': '进行中',
      '4': '已完成',
    };
    return statusMap[status] || '未知状态';
  };

  // 获取供应商名称
  const getSupplierName = () => {
    if (recordType === 'supplier') {
      return record?.supplierName || record?.name || scoreDetail?.name || '-';
    } else {
      return scoreDetail?.name || '-';
    }
  };

  // 获取评价主题
  const getEvaluateTheme = () => {
    return record?.evaluateTheme || '-';
  };

  // 获取发起单位
  const getUnitName = () => {
    return record?.tenantName || record?.deptName || '-';
  };

  // 判断是否可以编辑（只有打分模式才可编辑）
  const canEdit = mode === 'score';

  return (
    <div className="common-container">
      <div className={styles.headerRow}>
        <div className={styles.titleSection}>
          <Title level={4} className={styles.pageTitle}>
            {getSupplierName()} - 评价打分
          </Title>
        </div>
        <div className={styles.actionSection}>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>
      </div>

      <Spin spinning={loading}>
        {scoreDetail ? (
          <div className="content-area">
            <Card title="基本信息" bordered={false}>
              <Descriptions column={2} bordered>
                <Descriptions.Item label="供应商名称">{getSupplierName()}</Descriptions.Item>
                <Descriptions.Item label="品类">{scoreDetail.category || '-'}</Descriptions.Item>
                <Descriptions.Item label="评价主题">{getEvaluateTheme()}</Descriptions.Item>
                <Descriptions.Item label="评价状态">
                  {getStatusText(record?.status || '') || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="评价开始时间">
                  {record?.startTime || '-'}
                </Descriptions.Item>
                <Descriptions.Item label="评价结束时间">{record?.endTime || '-'}</Descriptions.Item>
                <Descriptions.Item label="发起单位">{getUnitName()}</Descriptions.Item>
              </Descriptions>
            </Card>

            <Divider />

            <Card title="评价打分" bordered={false}>
              {scoreData.length > 0 ? (
                <ScoreEvaluationTable
                  value={scoreData}
                  onChange={handleScoreDataChange}
                  isDetail={!canEdit} // 如果不可编辑，则以只读方式显示
                />
              ) : (
                <Empty description="暂无评分数据" />
              )}

              {/* 只在打分模式下显示提交按钮，并移至底部 */}
              {canEdit && (
                <div className={styles.submitButtonContainer}>
                  <Button
                    type="primary"
                    icon={<SaveOutlined />}
                    onClick={handleSubmit}
                    loading={submitting}
                    style={{ marginTop: 24 }}
                  >
                    提交评分
                  </Button>
                </div>
              )}
            </Card>
          </div>
        ) : (
          !loading && <Empty description="暂无评分数据" />
        )}
      </Spin>
    </div>
  );
};

export default SupplierEvaluateScoreDetail;
