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

const { Option } = Select;

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

  // 品类数据
  const categoryOptions = [
    { label: '食品', value: '食品' },
    { label: '电子', value: '电子' },
    { label: '机械', value: '机械' },
    { label: '化工', value: '化工' },
    { label: '医药', value: '医药' },
  ];

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

  // 获取评价规则列表
  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();
  }, []);

  // 获取评价结果详情列表
  const fetchResultDetailList = async (
    current = 1,
    pageSize = 10,
    params: API.EvaluateSupplierSearchParams = searchParams,
  ) => {
    // 确保有评价任务ID
    if (!parentRecord?.id) {
      message.error('缺少评价任务ID，无法获取数据');
      return;
    }

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

    setLoading(true);
    try {
      // 构建请求参数
      const requestParams: API.EvaluateSupplierRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
        evaluateTaskId: parentRecord.id,
      };

      // 添加搜索条件
      if (params.supplierName) {
        requestParams.supplierName = params.supplierName;
      }
      if (params.level) {
        requestParams.level = params.level;
      }

      // 调用接口获取数据
      const response = await getEvaluateSupplierList(requestParams);
      if (response.data && response.success) {
        const { records, total, current: currentPage, size } = response.data;

        // 处理数据，增加表格需要的key属性
        const formattedData = records.map(record => ({
          ...record,
          key: record.id,
        }));

        setResultData(formattedData);
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total,
        });
      } else {
        message.error(response.message || '获取评价结果详情列表失败');
      }
    } catch (error) {
      console.error('获取评价结果详情列表失败:', error);
      message.error('获取评价结果详情列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (parentRecord?.id) {
      fetchResultDetailList(pagination.current, pagination.pageSize, {});
    }
  }, [parentRecord]);

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

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

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

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

  // 查看得分明细
  const handleViewScoreDetail = (record: API.EvaluateSupplierRecord) => {
    history.push({
      pathname: 'supplierEvaluateResultScoreDetail',
      state: { record, parentRecord }
    });
  };

  // 查看打分情况
  const handleViewScoring = (record: API.EvaluateSupplierRecord) => {
    history.push({
      pathname: 'supplierEvaluateResultScoreByList',
      state: { record, parentRecord }
    });
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: API.EvaluateSupplierRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (supplierName: string) => (
        <Tooltip placement="topLeft" title={supplierName}>
          {supplierName}
        </Tooltip>
      ),
    },
    {
      title: '品类',
      dataIndex: 'categoryName',
      key: 'categoryName',
      width: 120,
    },
    {
      title: '评价得分',
      dataIndex: 'reviewScore',
      key: 'reviewScore',
      width: 100
    },
    {
      title: '评价等级',
      dataIndex: 'levelName',
      key: 'levelName',
      width: 100,
      align: 'center' as const
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center' as const,
      render: (_: unknown, record: API.EvaluateSupplierRecord) => (
        <Space size="middle">
          <Button
            type="link"
            onClick={() => handleViewScoreDetail(record)}
          >
            得分明细
          </Button>
          <Button type="link" onClick={() => handleViewScoring(record)}>
            打分情况
          </Button>
        </Space>
      ),
    },
  ];

  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={resultData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </div>
    </div>
  );
};

export default SupplierEvaluateResultInfo;
