import React, { useState, useEffect } from 'react';
import { Button, Table, Space, message, Input, Select, Form, Tooltip, Tag, DatePicker } from 'antd';
import type { TablePaginationConfig } from 'antd/es/table';
import { PlusOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { history } from 'umi';
import { TaskStatus, TaskStatusText, TaskStatusColor } from '@/dicts/supplierTaskDict';
import { getTaskList } from '@/servers/api/supplierEvaluate';
import styles from './supplierTaskManage.less';
import type { TaskRequest, TaskRecord, TaskItem } from '@/servers/dao/supplierEvaluateTask';
import type { TaskSearchParams } from '@/servers/dao/supplierEvaluateTask';

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

const SupplierTaskManage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [taskData, setTaskData] = useState<TaskItem[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<TaskSearchParams>({
    basePageRequest: {
      pageNo: 1,
      pageSize: 10,
    },
  });

  // 获取任务列表
  const fetchTaskList = async (
    current = 1,
    pageSize = 10,
    params: TaskSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构造请求参数
      const requestParams: TaskSearchParams = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
      };

      // 添加搜索条件
      if (params.evaluateTheme) {
        requestParams.evaluateTheme = params.evaluateTheme;
      }
      if (params.status) {
        requestParams.status = params.status;
      }
      if (params.dateRange && params.dateRange.length === 2) {
        requestParams.startTime = params.dateRange[0];
        requestParams.endTime = params.dateRange[1];
      }

      const response = await getTaskList(requestParams);

      if (response.success) {
        // 处理返回的数据
        const { records, total, current: currentPage, size } = response.data;
        setTaskData(records);
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total: total,
        });
      } else {
        message.error(response.message || '获取任务列表失败');
      }
    } catch (error) {
      console.error('获取任务列表失败:', error);
      message.error('获取任务列表失败');
    } finally {
      setLoading(false);
    }
  };

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

  // 处理查看
  const handleView = (record: TaskItem) => {
    // 跳转到详情页面
    history.push(`supplierTaskManageDetail?id=${record.id}`);
  };

  // 处理编辑
  const handleEdit = (record: TaskItem) => {
    // 跳转到编辑页面（复用新增页面）
    history.push(`supplierTaskManageAdd?id=${record.id}&mode=edit`);
  };

  // 处理分工
  const handleDivision = (record: TaskItem) => {
    // 跳转到分工页面
    history.push(`supplierTaskManageAdd?id=${record.id}&mode=division`);
  };

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

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

  const columns = [
    {
      title: '序号',
      render: (_: any, __: TaskItem, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '评价主题',
      dataIndex: 'evaluateTheme',
      key: 'evaluateTheme',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (evaluateTheme: string) => (
        <Tooltip placement="topLeft" title={evaluateTheme}>
          {evaluateTheme}
        </Tooltip>
      ),
    },
    {
      title: '发起单位',
      dataIndex: 'tenantName',
      key: 'tenantName',
      width: 150,
    },
    {
      title: '评价开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 120,
    },
    {
      title: '评价结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 120,
    },
    {
      title: '评价状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => getStatusTag(status),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      align: 'center' as const,
      render: (_: unknown, record: TaskItem) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
          {record.division == '1' && (
            <Button type="link" onClick={() => handleDivision(record)}>
              分工
            </Button>
          )}

          <Button type="link" onClick={() => handleEdit(record)}>
            修改
          </Button>
        </Space>
      ),
    },
  ];

  // 处理添加
  const handleAdd = () => {
    // 跳转到新增页面
    history.push('supplierTaskManageAdd');
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    const { dateRange, ...rest } = values;
    const params: SupplierEvaluate.TaskSearchParams = { ...rest };

    if (dateRange && dateRange.length === 2) {
      params.dateRange = [dateRange[0].format('YYYY-MM-DD'), dateRange[1].format('YYYY-MM-DD')];
    }

    fetchTaskList(1, pagination.pageSize, searchParams);
  };

  return (
    <div className={`${styles.supplierTaskManageContainer} common-container`}>
      <div className={styles.filterActionRow}>
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className={styles.filterForm}
        >
          <Form.Item name="evaluateTheme" label="评价主题">
            <Input placeholder="请输入评价主题" allowClear />
          </Form.Item>
          <Form.Item name="status" label="评价状态">
            <Select placeholder="请选择状态" allowClear>
              <Option value={TaskStatus.DRAFT}>未开始</Option>
              <Option value={TaskStatus.PROCESSING}>进行中</Option>
              <Option value={TaskStatus.COMPLETED}>已结束</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="评价时间">
            <RangePicker />
          </Form.Item>
          <Form.Item className={styles.filterBtns}>
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={() => {
                form.resetFields();
                setSearchParams({
                  basePageRequest: {
                    pageNo: 1,
                    pageSize: 10,
                  },
                });
                fetchTaskList(1, pagination.pageSize, searchParams);
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
        <div className={styles.rightButtons}>
          <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
            新增
          </Button>
        </div>
      </div>

      <div className={styles.contentArea}>
        <Table
          columns={columns}
          rowKey="id"
          dataSource={taskData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1500 }}
        />
      </div>
    </div>
  );
};

export default SupplierTaskManage;
