// 供应商评价打分
import React, { useState, useEffect } from 'react';
import {
  Button,
  Form,
  message,
  Typography,
  Space,
  Tabs,
  Input,
  DatePicker,
  Select,
  Table,
} from 'antd';
import { SearchOutlined, DeleteOutlined } from '@ant-design/icons';
import { history } from 'umi';
import styles from './supplierEvaluateScore.less';
import {
  getSupplierDimension,
  getTaskPage,
} from '@/servers/api/supplierEvaluate';

const { Title } = Typography;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;

const SupplierEvaluateScore: React.FC = () => {
  const [filterForm] = Form.useForm();
  // 新增状态
  const [activeTab, setActiveTab] = useState<string>('supplier');
  const [supplierTableData, setSupplierTableData] = useState<
    supplierEvaluateScore.SupplierDimensionRecord[]
  >([]);
  const [taskTableData, setTaskTableData] = useState<supplierEvaluateScore.TaskPageRecord[]>([]);
  const [supplierTableLoading, setSupplierTableLoading] = useState<boolean>(false);
  const [taskTableLoading, setTaskTableLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  // 构建查询参数
  const buildQueryParams = () => {
    const values = filterForm.getFieldsValue();

    if (activeTab === 'supplier') {
      const params: supplierEvaluateScore.SupplierDimensionRequest = {
        basePageRequest: {
          pageNo: pagination.current,
          pageSize: pagination.pageSize,
        },
        keyword: values.keyword || undefined,
        status: values.status || undefined,
      };

      // 处理时间范围
      if (values.evaluationTime && values.evaluationTime.length === 2) {
        params.startTime = values.evaluationTime[0].format('YYYY-MM-DD');
        params.endTime = values.evaluationTime[1].format('YYYY-MM-DD');
      }

      return params;
    } else {
      const params: supplierEvaluateScore.TaskPageRequest = {
        basePageRequest: {
          pageNo: pagination.current,
          pageSize: pagination.pageSize,
        },
        keyword: values.keyword || undefined,
        status: values.status || undefined,
      };

      // 处理时间范围
      if (values.evaluationTime && values.evaluationTime.length === 2) {
        params.startTime = values.evaluationTime[0].format('YYYY-MM-DD');
        params.endTime = values.evaluationTime[1].format('YYYY-MM-DD');
      }

      return params;
    }
  };

  // 获取供应商维度列表
  const fetchSupplierDimensionList = async (params: any) => {
    setSupplierTableLoading(true);
    try {
      const response = await getSupplierDimension(params);

      if (response.success && response.data) {
        setSupplierTableData(response.data.records || []);
        setPagination({
          ...pagination,
          current: response.data.current || 1,
          total: response.data.total || 0,
        });
      } else {
        message.error(response.message || '获取供应商列表失败');
        setSupplierTableData([]);
      }
    } catch (error) {
      console.error('获取供应商列表失败:', error);
      message.error('获取供应商列表失败');
      setSupplierTableData([]);
    } finally {
      setSupplierTableLoading(false);
    }
  };

  // 获取任务列表
  const fetchTaskList = async (params: any) => {
    setTaskTableLoading(true);
    try {
      const response = await getTaskPage(params);

      if (response.success && response.data) {
        setTaskTableData(response.data.records || []);
        setPagination({
          ...pagination,
          current: response.data.current || 1,
          total: response.data.total || 0,
        });
      } else {
        message.error(response.message || '获取任务列表失败');
        setTaskTableData([]);
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
      message.error('获取任务列表失败');
      setTaskTableData([]);
    } finally {
      setTaskTableLoading(false);
    }
  };

  // 处理搜索按钮点击
  const handleSearch = async () => {
    const params = buildQueryParams();

    if (activeTab === 'supplier') {
      fetchSupplierDimensionList(params);
    } else {
      fetchTaskList(params);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    handleSearch();
  }, [activeTab]);

  // 处理标签页切换
  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setPagination({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    filterForm.resetFields();
  };

  // 处理重置按钮点击
  const handleReset = () => {
    filterForm.resetFields();
    setPagination({
      current: 1,
      pageSize: 10,
      total: 0,
    });
    handleSearch();
  };

  // 处理分页变化
  const handleTableChange = (page: any) => {
    setPagination({
      ...pagination,
      current: page.current,
      pageSize: page.pageSize,
    });

    const params = buildQueryParams();
    params.basePageRequest.pageNo = page.current;
    params.basePageRequest.pageSize = page.pageSize;

    if (activeTab === 'supplier') {
      fetchSupplierDimensionList(params);
    } else {
      fetchTaskList(params);
    }
  };

  // 跳转到评分页面
  const goToScoring = (record: any, recordType: 'supplier' | 'task', mode: 'view' | 'score') => {
    // 构建路由状态参数
    const state: {
      record: any;
      mode: 'view' | 'score';
      recordType: 'supplier' | 'task';
    } = {
      record: record,
      mode,
      recordType: recordType,
    };
    if (recordType === 'task') {
      state.record.evaluateTaskId = record.id;
      history.push({
        pathname: '/supplierEvaluate/supplierEvaluateResultInfo',
        state: {record},
      });
      return;
    }

    history.push({
      pathname: '/supplierEvaluate/supplierEvaluateScoreDetail',
      state: state,
    });
  };

  // 导出功能
  const handleExport = async (record: any) => {
    if (!record?.id) {
      message.error('缺少必要参数，无法导出');
      return;
    }

    try {
      window.open(
        `${SERVER_BASE}/coscoEvaluate/supplier/export?evaluateTaskId=${record.id}`,
        '_blank',
        'noopener,noreferrer',
      );
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败，请稍后再试');
    }
  };

  // 供应商Tab的表格列
  const supplierColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) =>
        (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '供应商名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '评价主题',
      dataIndex: 'evaluateTheme',
      key: 'evaluateTheme',
    },
    {
      title: '发起单位',
      dataIndex: 'tenantName',
      key: 'tenantName',
    },
    {
      title: '评价开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '评价结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '评价状态',
      dataIndex: 'statusName',
      key: 'statusName',
    },
    {
      title: '提交状态',
      dataIndex: 'submissionStatus',
      key: 'submissionStatus',
    },
    {
      title: '提交时间',
      dataIndex: 'submissionTime',
      key: 'submissionTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: any) => (
        <Space>
          <Button type="link" onClick={() => goToScoring(record, 'supplier', 'view')}>
            查看
          </Button>
          {record.status === '1' && ( // 只有待评分状态才显示打分按钮
            <Button type="link" onClick={() => goToScoring(record, 'supplier', 'score')}>
              打分
            </Button>
          )}
        </Space>
      ),
    },
  ];

  // 评价任务Tab的表格列
  const taskColumns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) =>
        (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: '评价主题',
      dataIndex: 'evaluateTheme',
      key: 'evaluateTheme',
    },
    {
      title: '发起单位',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '评价开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
    },
    {
      title: '评价结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
    },
    {
      title: '评价状态',
      dataIndex: 'statusName',
      key: 'statusName',
    },
    {
      title: '操作',
      key: 'action',
      render: (text: string, record: any) => (
        <Space>
          <Button type="link" onClick={() => goToScoring(record, 'task', 'view')}>
            查看
          </Button>
          <Button type="link" onClick={() => handleExport(record)}>
            导出
          </Button>
        </Space>
      ),
    },
  ];

  // 筛选表单
  const renderFilterForm = () => (
    <div className="filter-action-row">
      <div className="filter-form">
        <Form form={filterForm} layout="inline">
          <Form.Item name="keyword" label="关键字">
            <Input
              placeholder={
                activeTab === 'supplier' ? '请输入供应商名称或评价主题' : '请输入评价主题'
              }
              allowClear
            />
          </Form.Item>

          <Form.Item name="evaluationTime" label="评价时间">
            <RangePicker />
          </Form.Item>

          <Form.Item name="status" label="评价状态">
            <Select placeholder="请选择" style={{ width: 150 }} allowClear>
              <Option value="1">待评分</Option>
              <Option value="2">已评分</Option>
              <Option value="3">进行中</Option>
              <Option value="4">已完成</Option>
            </Select>
          </Form.Item>

          <Form.Item className="filter-btns">
            <Space>
              <Button type="primary" onClick={handleSearch}>
                <SearchOutlined /> 查询
              </Button>
              <Button onClick={handleReset} type="primary" danger>
                <DeleteOutlined /> 重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );

  return (
    <div className="common-container">
      <div className={styles.headerRow}>
        <div className={styles.titleSection}>
          <Title level={4} className={styles.pageTitle}>
            供应商评价打分
          </Title>
        </div>
      </div>

      {/* 筛选条件区域 */}
      {renderFilterForm()}

      <div className="content-area">
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="按供应商" key="supplier">
            <Table
              columns={supplierColumns}
              dataSource={supplierTableData}
              rowKey="id"
              loading={supplierTableLoading}
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
              }}
              onChange={handleTableChange}
            />
          </TabPane>
          <TabPane tab="按评价任务" key="task">
            <Table
              columns={taskColumns}
              dataSource={taskTableData}
              rowKey="id"
              loading={taskTableLoading}
              pagination={{
                current: pagination.current,
                pageSize: pagination.pageSize,
                total: pagination.total,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条`,
              }}
              onChange={handleTableChange}
            />
          </TabPane>
        </Tabs>
      </div>
    </div>
  );
};

export default SupplierEvaluateScore;
