import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Space,
  Tag,
  DatePicker,
  TablePaginationConfig,
  Tooltip,
  message,
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  PlusOutlined,
  EditOutlined,
  EyeOutlined,
  FormOutlined,
} from '@ant-design/icons';
import { TaskStatus, TaskStatusText, TaskStatusColor } from '@/dicts/supplierTaskDict';
import moment from 'moment';

const { Option } = Select;
const { RangePicker } = DatePicker;

// 定义搜索参数接口
interface ScoreSearchParams {
  evaluateTitle?: string;
  supplierName?: string;
  status?: string;
}

// 定义打分记录接口
interface ScoreRecord {
  id: string;
  evaluateTitle: string;
  supplierName: string;
  category: string;
  status: string;
  scoreStatus: string; // 打分状态：未打分、已打分、已提交
  createTime: string;
  key: string;
}

// 打分状态
const ScoreStatus = {
  NOT_SCORED: 'not_scored',
  SCORED: 'scored',
  SUBMITTED: 'submitted',
};

const ScoreStatusText = {
  [ScoreStatus.NOT_SCORED]: '未打分',
  [ScoreStatus.SCORED]: '已打分',
  [ScoreStatus.SUBMITTED]: '已提交',
};

const ScoreStatusColor = {
  [ScoreStatus.NOT_SCORED]: 'orange',
  [ScoreStatus.SCORED]: 'blue',
  [ScoreStatus.SUBMITTED]: 'green',
};

const SupplierEvaluateScore: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [scoreData, setScoreData] = useState<ScoreRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<ScoreSearchParams>({});

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

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

    setLoading(true);
    try {
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据
        const mockData: ScoreRecord[] = Array.from({ length: 35 }).map((_, index) => {
          const id = `${index + 1}`;
          const status = Object.values(TaskStatus)[Math.floor(Math.random() * 3)];
          const scoreStatus = Object.values(ScoreStatus)[Math.floor(Math.random() * 3)];

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

          return {
            id,
            key: id,
            evaluateTitle: `供应商评价任务${index + 1}`,
            supplierName: `供应商${index + 1}`,
            category: categoryOptions[categoryIndex].value,
            status,
            scoreStatus,
            createTime: moment().subtract(Math.floor(Math.random() * 90), 'days').format('YYYY-MM-DD HH:mm:ss'),
          };
        });

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

        // 分页
        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 handleScore = (record: ScoreRecord) => {
    message.info(`开始为 ${record.supplierName} 打分`);
  };

  // 处理查看
  const handleView = (record: ScoreRecord) => {
    message.info(`查看 ${record.supplierName} 的打分情况`);
  };

  // 处理提交
  const handleSubmit = (record: ScoreRecord) => {
    message.success(`已提交 ${record.supplierName} 的评分`);
    fetchScoreList(pagination.current, pagination.pageSize, searchParams);
  };

  // 获取状态标签
  const getScoreStatusTag = (status: string) => {
    const color = ScoreStatusColor[status as keyof typeof ScoreStatusColor] || 'default';
    const text = ScoreStatusText[status as keyof typeof ScoreStatusText] || '未知状态';
    return <Tag color={color}>{text}</Tag>;
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: ScoreRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '评价主题',
      dataIndex: 'evaluateTitle',
      key: 'evaluateTitle',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (evaluateTitle: string) => (
        <Tooltip placement="topLeft" title={evaluateTitle}>
          {evaluateTitle}
        </Tooltip>
      ),
    },
    {
      title: '供应商名称',
      dataIndex: 'supplierName',
      key: 'supplierName',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (supplierName: string) => (
        <Tooltip placement="topLeft" title={supplierName}>
          {supplierName}
        </Tooltip>
      ),
    },
    {
      title: '品类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
    },
    {
      title: '打分状态',
      dataIndex: 'scoreStatus',
      key: 'scoreStatus',
      width: 100,
      render: (status: string) => getScoreStatusTag(status),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      align: 'center' as const,
      render: (_: unknown, record: ScoreRecord) => (
        <Space size="middle">
          {record.scoreStatus === ScoreStatus.NOT_SCORED && (
            <Button
              type="link"
              icon={<FormOutlined />}
              onClick={() => handleScore(record)}
            >
              打分
            </Button>
          )}
          {record.scoreStatus === ScoreStatus.SCORED && (
            <Button
              type="link"
              icon={<EditOutlined />}
              onClick={() => handleSubmit(record)}
            >
              提交
            </Button>
          )}
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => handleView(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="evaluateTitle" label="评价主题">
            <Input placeholder="请输入评价主题" allowClear />
          </Form.Item>
          <Form.Item name="supplierName" label="供应商名称">
            <Input placeholder="请输入供应商名称" allowClear />
          </Form.Item>
          <Form.Item name="status" label="打分状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 150 }}>
              <Option value={ScoreStatus.NOT_SCORED}>{ScoreStatusText[ScoreStatus.NOT_SCORED]}</Option>
              <Option value={ScoreStatus.SCORED}>{ScoreStatusText[ScoreStatus.SCORED]}</Option>
              <Option value={ScoreStatus.SUBMITTED}>{ScoreStatusText[ScoreStatus.SUBMITTED]}</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="primary" ghost icon={<PlusOutlined />} onClick={() => message.info('新增打分任务')}>
            新增
          </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 SupplierEvaluateScore;
