import React, { useState, useEffect } from 'react';
import { Card, Button, message, Spin, Tabs, Typography } from 'antd';
import { history, useLocation } from 'umi';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getTaskDetail } from '@/servers/api/supplierEvaluate';
import {
  BasicInfo,
  SupplierInfo,
  EvaluatorInfo,
  WeightInfo,
  EvaluatorModal,
  IndicatorModal
} from './components/Detail';
import styles from './supplierTaskManageDetail.less';
import type { TaskDetailData } from '@/servers/types/supplierEvaluateTask';

const { TabPane } = Tabs;
const { Title } = Typography;

// 解析查询参数
const useQuery = () => {
  const { search } = useLocation();
  return React.useMemo(() => new URLSearchParams(search), [search]);
};

const SupplierTaskManageDetail: React.FC = () => {
  const query = useQuery();
  const taskId = query.get('id');

  // 数据加载状态
  const [loading, setLoading] = useState<boolean>(true);

  // 任务数据
  const [taskData, setTaskData] = useState<TaskDetailData | null>(null);

  // 当前活动标签页
  const [activeTab, setActiveTab] = useState<string>('1');

  // 模态框状态
  const [evaluatorModalVisible, setEvaluatorModalVisible] = useState<boolean>(false);
  const [indicatorModalVisible, setIndicatorModalVisible] = useState<boolean>(false);
  const [currentSupplier, setCurrentSupplier] = useState<any>(null);
  const [currentIndicators, setCurrentIndicators] = useState<string[]>([]);
  const [currentEvaluator, setCurrentEvaluator] = useState<string>('');

  // 获取任务详情
  const fetchTaskDetail = async (id: string) => {
    if (!id) {
      message.error('任务ID不能为空');
      return;
    }

    setLoading(true);
    try {
      const response = await getTaskDetail(id);
      if (response.success) {
        setTaskData(response.data);
      } else {
        message.error(response.message || '获取任务详情失败');
      }
    } catch (error) {
      console.error('获取任务详情失败:', error);
      message.error('获取任务详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 当组件挂载时，获取任务详情
  useEffect(() => {
    if (taskId) {
      fetchTaskDetail(taskId);
    } else {
      message.error('未提供任务ID');
      history.push('/supplier/supplierTaskManage');
    }
  }, [taskId]);

  // 处理返回
  const handleBack = () => {
    history.goBack();
  };

  // 处理查看供应商评价人员
  const handleViewSupplierEvaluators = (supplier: any) => {
    setCurrentSupplier(supplier);
    setEvaluatorModalVisible(true);
  };

  // 处理查看评价人员分工
  const handleViewIndicators = (record: any) => {
    setCurrentIndicators(record.indicatorIds || []);
    setCurrentEvaluator(record.userId);
    setIndicatorModalVisible(true);
  };

  return (
    <div className="common-container">
      <Card bordered={false}>
        <div className="page-header">
          <Title level={4}>评价任务详情</Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>

        {loading ? (
          <div className={styles.loadingContainer}>
            <Spin size="large" tip="数据加载中..." />
          </div>
        ) : (
          <Tabs activeKey={activeTab} onChange={setActiveTab}>
            <TabPane tab="基本信息" key="1">
              {taskData && <BasicInfo taskData={taskData} />}
            </TabPane>
            <TabPane tab="供应商信息" key="2">
              {taskData && <SupplierInfo
                taskData={taskData}
                onViewEvaluators={handleViewSupplierEvaluators}
              />}
            </TabPane>
            <TabPane tab="评价指标分工" key="3">
              {taskData && <EvaluatorInfo
                taskData={taskData}
                onViewIndicators={handleViewIndicators}
              />}
            </TabPane>
            <TabPane tab="评分单位权重" key="4">
              {taskData && <WeightInfo taskData={taskData} />}
            </TabPane>
          </Tabs>
        )}
      </Card>

      {/* 供应商评价人员模态框 */}
      <EvaluatorModal
        visible={evaluatorModalVisible}
        supplier={currentSupplier}
        onCancel={() => setEvaluatorModalVisible(false)}
      />

      {/* 评价人员分工模态框 */}
      <IndicatorModal
        visible={indicatorModalVisible}
        evaluatorId={currentEvaluator}
        indicators={currentIndicators}
        templateId={taskData?.templateId || ''}
        onCancel={() => setIndicatorModalVisible(false)}
      />
    </div>
  );
};

export default SupplierTaskManageDetail;
