// 供应商评价结果打分情况
import React, { useState, useEffect } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Table,
  Tooltip,
  message,
} from 'antd';
import type { TablePaginationConfig } from 'antd';
import { SearchOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { history, useLocation } from 'umi';
import { getEvaluateScoreList, getAllEvaluateRules } from '@/servers/api/supplierEvaluate';

// 为修复类型问题，定义新的评分数据结构
interface ScoreDataItem {
  id: string;
  key: string;
  name?: string;
  supplierName: string;
  evaluateTheme: string;
  startTime?: string;
  endTime?: string;
  evaluateTime: string;
  status?: string;
  statusName?: string;
  score: string | number;
  suscore?: string | number;
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
  categoryName?: string; // 品类名称
  deptName?: string; // 评价单位
  evaluatorName?: string; // 评价人员
  [key: string]: any;
}

// 自定义类型用于传递给详情页的数据
interface DetailPageState {
  record: ScoreDataItem;
  parentRecord: API.EvaluateSupplierRecord | null;
}

const { Option } = Select;

const SupplierEvaluateResultScoreByList: React.FC = () => {
  const location = useLocation<{
    record: API.EvaluateSupplierRecord;
  }>();
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [scoreData, setScoreData] = useState<ScoreDataItem[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<API.EvaluateScoreSearchParams>({});
  const [record, setRecord] = useState<API.EvaluateSupplierRecord | null>(null);
  const [evaluateRules, setEvaluateRules] = useState<API.EvaluateRuleItem[]>([]);

  // 获取评价规则列表
  const fetchEvaluateRules = async () => {
    try {
      const response = await getAllEvaluateRules();
      if (response.success && response.data) {
        setEvaluateRules(response.data);
      } else {
        message.error(response.message || '获取评价规则列表失败');
      }
    } catch (error) {
      console.error('获取评价规则列表失败:', error);
      message.error('获取评价规则列表失败');
    }
  };

  // 首次加载获取评价规则列表
  useEffect(() => {
    fetchEvaluateRules();
  }, []);

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

  // 获取评价打分情况列表
  const fetchScoreList = async (
    current = 1,
    pageSize = 10,
    params: API.EvaluateScoreSearchParams = searchParams,
  ) => {
    // 确保有必要的参数
    if (!record?.supplierId || !record?.evaluateTaskId) {
      message.error('缺少必要参数，无法获取数据');
      return;
    }

    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构建请求参数
      const requestParams: API.EvaluateScoreRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        taskId: record.evaluateTaskId,
        supplierId: record.supplierId,
        ...params,
      };

      // 调用接口获取数据
      const response = await getEvaluateScoreList(requestParams);

      // 新的接口返回格式，结构是: { success, data: { records, total, ... } }
      if (response.success && response.data) {
        const { records = [], total = 0, size = 10, current: currentPage = 1 } = response.data;

        if (records && records.length > 0) {
          // 格式化数据用于表格显示 - 使用新的字段名称
          const formattedData = records.map((item: any, index: number) => ({
            ...item,
            key: index.toString(),
            supplierName: item.name || '-',
            evaluateTheme: item.evaluateTheme || '-',
            evaluateTime: item.endTime || item.startTime || '-',
            score: item.suscore || '0',
            status: item.statusName || '-',
            categoryName: item.categoryName || '-', // 品类
            deptName: item.deptName || '-', // 评价单位
            evaluatorName: item.evaluatorName || item.createBy || '-', // 评价人员
          }));

          setScoreData(formattedData);
          setPagination({
            ...pagination,
            current: currentPage,
            pageSize: size,
            total,
          });
        } else {
          setScoreData([]);
          setPagination({
            ...pagination,
            current,
            pageSize,
            total: 0,
          });
          message.info('暂无评价打分数据');
        }
      } else {
        message.error(response.message || '获取评价打分情况列表失败');
      }
    } catch (error) {
      console.error('获取评价打分情况列表失败:', error);
      message.error('获取评价打分情况列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (record?.supplierId && record?.evaluateTaskId) {
      fetchScoreList(pagination.current, pagination.pageSize);
    }
  }, [record]);

  // 处理搜索
  const handleSearch = (values: API.EvaluateScoreSearchParams) => {
    fetchScoreList(1, pagination.pageSize, values);
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchScoreList(1, pagination.pageSize, {});
  };

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

  // 查看评价详情
  const handleViewDetail = (scoreItem: ScoreDataItem) => {
    const detailState: DetailPageState = {
      record: scoreItem,
      parentRecord: record
    };
    history.push({
      pathname: 'supplierEvaluateResultByZb',
      state: detailState,
    });
  };

  // 处理表格分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchScoreList(newPagination.current, newPagination.pageSize, searchParams);
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: any, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 60,
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (supplierName: string) => (
        <Tooltip placement="topLeft" title={supplierName}>
          {supplierName}
        </Tooltip>
      ),
    },
    {
      title: '品类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '评价单位',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '评价人员',
      dataIndex: 'evaluatorName',
      key: 'evaluatorName',
      width: 120,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '评价时间',
      dataIndex: 'evaluateTime',
      key: 'evaluateTime',
      width: 120,
    },
    {
      title: '评价得分',
      dataIndex: 'score',
      key: 'score',
      align: 'center' as const,
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      align: 'center' as const,
      render: (_: unknown, scoreItem: ScoreDataItem) => (
        <Button type="link" onClick={() => handleViewDetail(scoreItem)}>
          查看
        </Button>
      ),
    },
  ];

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form form={form} layout="inline" onFinish={handleSearch} className="filter-form">
          <Form.Item name="supplierName" label="供应商名称">
            <Input placeholder="请输入供应商名称" allowClear />
          </Form.Item>
          <Form.Item name="level" label="评价等级">
            <Select placeholder="请选择评价等级" allowClear style={{ width: 150 }}>
              {evaluateRules.map((rule) => (
                <Option key={rule.id} value={rule.levelName}>
                  {rule.levelName}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" icon={<SearchOutlined />} onClick={() => form.submit()}>
              搜索
            </Button>
            <Button type="primary" danger icon={<DeleteOutlined />} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <div className="right-buttons">
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>
      </div>

      <div className="content-area">
        <Table
          columns={columns}
          dataSource={scoreData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </div>
    </div>
  );
};

export default SupplierEvaluateResultScoreByList;
