// 供应商评价结果打分情况
import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Space,
  TablePaginationConfig,
  Tooltip,
  message,
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  ArrowLeftOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { history, useLocation } from 'umi';
import { EvaluateLevel, EvaluateLevelText } from '@/dicts/supplierTemplateDict';
import styles from './supplierEvaluateResult.less';

const { Option } = Select;

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

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

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

  // 模拟获取评价打分情况列表
  const fetchScoreList = async (
    current = 1,
    pageSize = 10,
    params: any = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

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

          // 随机生成得分
          const score = Math.floor(Math.random() * 40) + 60; // 60-100分

          // 评价单位
          const units = ['中山市合创展包装材料有限公司', '广州市科技发展有限公司', '深圳市创新科技有限公司', '东莞市制造业有限公司'];
          const unitIndex = Math.floor(Math.random() * units.length);

          return {
            id,
            key: id,
            supplierName: supplierRecord?.supplierName || `供应商${index + 1}`,
            category: supplierRecord?.category || '电子',
            evaluateUnit: units[unitIndex],
            evaluator: `评价人${index + 1}`,
            evaluateTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}`,
            score,
          };
        });

        // 根据搜索条件过滤
        let filteredData = [...mockData];
        if (params.supplierName) {
          filteredData = filteredData.filter((item) =>
            item.supplierName.includes(params.supplierName || ''),
          );
        }
        if (params.level) {
          filteredData = filteredData.filter((item) => {
            let level;
            if (item.score >= 90) {
              level = EvaluateLevel.EXCELLENT;
            } else if (item.score >= 80) {
              level = EvaluateLevel.GOOD;
            } else if (item.score >= 70) {
              level = EvaluateLevel.AVERAGE;
            } else {
              level = EvaluateLevel.POOR;
            }
            return level === params.level;
          });
        }

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

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

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

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

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

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

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

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

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

  const columns = [
    {
      title: '序号',
      render: (_: any, __: any, 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: 'evaluateUnit',
      key: 'evaluateUnit',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '评价人员',
      dataIndex: 'evaluator',
      key: 'evaluator',
      width: 120,
    },
    {
      title: '评价时间',
      dataIndex: 'evaluateTime',
      key: 'evaluateTime',
      width: 120,
    },
    {
      title: '评价得分',
      dataIndex: 'score',
      key: 'score',
      align: 'center' as const,
      width: 100,
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      align: 'center' as const,
      render: (_: unknown, record: any) => (
        <Button
          type="link"
          onClick={() => handleViewDetail(record)}
        >
          查看
        </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 }}>
              {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={scoreData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </div>
    </div>
  );
};

export default SupplierEvaluateResultScoreByList;
