// 供应商评价打分
import React, { useState, useEffect } from 'react';
import { Button, Card, Form, message, Typography, Spin, Space } from 'antd';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons';
import { history, useLocation } from 'umi';
import ScoreEvaluationTable from '@/components/ScoreEvaluationTable';
import styles from './supplierEvaluateScore.less';
import { getSupplierScoreDetail, submitEvaluateScore } from '@/servers/api/supplierEvaluate';

const { Title } = Typography;

const SupplierEvaluateScore: React.FC = () => {
  const [form] = Form.useForm();
  const location = useLocation<{
    record: API.EvaluateSupplierRecord;
    parentRecord: API.EvaluateTaskRecord;
  }>();
  const [loading, setLoading] = useState<boolean>(false);
  const [submitting, setSubmitting] = useState<boolean>(false);
  const [supplierRecord, setSupplierRecord] = useState<API.EvaluateSupplierRecord | null>(null);
  const [parentRecord, setParentRecord] = useState<API.EvaluateTaskRecord | null>(null);
  const [scoreDetail, setScoreDetail] = useState<API.EvaluateScoreDetailData | null>(null);
  const [scoreData, setScoreData] = useState<any[]>([]);

  // 获取上级页面传递的数据
  useEffect(() => {
    if (location.state?.record) {
      setSupplierRecord(location.state.record);
    }
    if (location.state?.parentRecord) {
      setParentRecord(location.state.parentRecord);
    }
  }, [location]);

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

    return data.taskIndicatorVo.map(indicator => {
      return {
        baseIndicator: indicator.baseIndicator,
        descIndicator: indicator.indicatorDesc,
        score: indicator.score,
        indicatorNdList: indicator.subIndicator?.map(subItem => {
          return {
            subIndicator: subItem.subIndicator,
            score: subItem.subScore,
            isStar: subItem.starIndicator,
            id: subItem.id,
            actualScore: subItem.scoreNum || '',
            remark: subItem.remark || ''
          };
        }) || []
      };
    });
  };

  // 获取得分明细数据
  const fetchScoreDetail = async () => {
    if (!supplierRecord?.id) {
      message.error('缺少必要参数，无法获取数据');
      return;
    }

    setLoading(true);
    try {
      const response = await getSupplierScoreDetail(supplierRecord.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 (supplierRecord?.id) {
      fetchScoreDetail();
    }
  }, [supplierRecord]);

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

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

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

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

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

    setSubmitting(true);
    try {
      // 构建提交数据
      const submitData = {
        id: supplierRecord.id,
        taskIndicatorVo: scoreData.map(item => ({
          baseIndicator: item.baseIndicator,
          indicatorDesc: item.descIndicator,
          score: item.score,
          subIndicator: item.indicatorNdList.map((subItem: any) => ({
            id: subItem.id,
            subIndicator: subItem.subIndicator,
            subScore: subItem.score,
            starIndicator: subItem.isStar,
            scoreNum: subItem.actualScore,
            remark: subItem.remark
          }))
        }))
      };

      const response = await submitEvaluateScore(submitData);

      if (response.success) {
        message.success('评分提交成功');
        // 提交成功后返回列表页
        history.goBack();
      } else {
        message.error(response.message || '评分提交失败');
      }
    } catch (error) {
      console.error('评分提交失败:', error);
      message.error('评分提交失败');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="common-container">
      <div className={styles.headerRow}>
        <div className={styles.titleSection}>
          <Title level={4} className={styles.pageTitle}>
            {supplierRecord?.supplierName || '供应商'} - 评价打分
          </Title>
        </div>
        <div className={styles.actionSection}>
          <Space>
            <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
              返回
            </Button>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              onClick={handleSubmit}
              loading={submitting}
            >
              提交
            </Button>
          </Space>
        </div>
      </div>

      <div className="content-area">
        <Card bordered={false}>
          {loading ? (
            <div className="loading-container" style={{ textAlign: 'center', padding: '50px' }}>
              <Spin tip="加载中..." />
            </div>
          ) : (
            <Form form={form} layout="vertical">
              <ScoreEvaluationTable
                value={scoreData}
                onChange={handleScoreDataChange}
                isDetail={false}
                loading={loading}
              />
            </Form>
          )}
        </Card>
      </div>
    </div>
  );
};

export default SupplierEvaluateScore;
