// 供应商评价结果详情
import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Space,
  Tag,
  TablePaginationConfig,
  Modal,
  Row,
  Col,
  Tooltip,
  message,
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
  FileTextOutlined,
  BarChartOutlined,
} from '@ant-design/icons';
import { history, useLocation } from 'umi';
import moment from 'moment';
import { EvaluateLevel, EvaluateLevelText, EvaluateLevelColor } from '@/dicts/supplierTemplateDict';
import styles from './supplierEvaluateResult.less';

const { Option } = Select;

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

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

  // 评价等级选项
  const levelOptions = Object.entries(EvaluateLevelText).map(([value, label]) => ({
    label,
    value,
  }));

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

  // 模拟获取评价结果详情列表
  const fetchResultDetailList = async (
    current = 1,
    pageSize = 10,
    params: SupplierEvaluate.EvaluateResultDetailSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据
        const mockData: SupplierEvaluate.EvaluateResultDetailRecord[] = Array.from({
          length: 35,
        }).map((_, index) => {
          const id = `${index + 1}`;

          // 随机选择品类
          const categoryIndex = Math.floor(Math.random() * categoryOptions.length);

          // 随机生成得分和等级
          const score = Math.floor(Math.random() * 40) + 60; // 60-100分
          let level;
          if (score >= 90) {
            level = EvaluateLevel.EXCELLENT;
          } else if (score >= 80) {
            level = EvaluateLevel.GOOD;
          } else if (score >= 70) {
            level = EvaluateLevel.AVERAGE;
          } else {
            level = EvaluateLevel.POOR;
          }

          return {
            id,
            key: id,
            supplierName: `供应商${index + 1}`,
            category: categoryOptions[categoryIndex].value,
            score,
            level,
          };
        });

        // 根据搜索条件过滤
        let filteredData = [...mockData];
        if (params.supplierName) {
          filteredData = filteredData.filter((item) =>
            item.supplierName.includes(params.supplierName || ''),
          );
        }
        if (params.level) {
          filteredData = filteredData.filter((item) => item.level === params.level);
        }

        // 分页
        const startIndex = (current - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedData = filteredData.slice(startIndex, endIndex);

        setResultData(paginatedData);
        setPagination({
          ...pagination,
          current,
          pageSize,
          total: filteredData.length,
        });

        setLoading(false);
      }, 500);
    } catch (error) {
      console.error('获取评价结果详情列表失败:', error);
      message.error('获取评价结果详情列表失败');
      setLoading(false);
    }
  };

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

  // 处理表格分页变化
  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: SupplierEvaluate.EvaluateResultDetailRecord) => {
    history.push({
      pathname: '/supplierEvaluateResult/supplierEvaluateResultScoreDetail',
      state: { record }
    });
  };

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

  // 获取等级标签
  const getLevelTag = (level: string) => {
    const text = EvaluateLevelText[level as keyof typeof EvaluateLevelText] || '未知等级';
    return text;
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: SupplierEvaluate.EvaluateResultDetailRecord, 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: 'category',
      key: 'category',
      width: 120,
    },
    {
      title: '评价得分',
      dataIndex: 'score',
      key: 'score',
      width: 100
    },
    {
      title: '评价等级',
      dataIndex: 'level',
      key: 'level',
      width: 100,
      align: 'center' as const,
      render: (level: string) => getLevelTag(level),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center' as const,
      render: (_: unknown, record: SupplierEvaluate.EvaluateResultDetailRecord) => (
        <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 }}>
              {levelOptions.map((option) => (
                <Option key={option.value} value={option.value}>
                  {option.label}
                </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;
