import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Input,
  Row,
  Col,
  message,
  Space,
  Form,
  DatePicker,
  Select,
  Tag,
  Tooltip,
  Modal,
} from 'antd';
import { history } from 'umi';
import {
  SearchOutlined,
  DeleteOutlined,
  PlusOutlined,
  EditOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { getAnnualTaskList } from '@/servers/api/supplierAnnual';
import {
  AnnualTaskStatus,
  AnnualTaskStatusText,
  AnnualTaskStatusColor,
  AnnualTaskStatusOptions,
} from '@/dicts/supplierAnnualTaskManageDict';
import moment from 'moment';
import styles from './supplierAnnualTaskManage.less';

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

const SupplierAnnualTaskManage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<supplierAnnualTaskManage.TaskRecord[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
  });
  const [searchParams, setSearchParams] = useState<any>({});

  // 获取年度任务列表
  const fetchList = async (params: any = {}) => {
    try {
      setLoading(true);
      const { current, pageSize, ...restParams } = params;
      const res = await getAnnualTaskList({
        basePageRequest: {
          pageNo: current,
          pageSize,
        },
        ...restParams,
        ...searchParams,
      });

      if (res.success) {
        setData(res.data?.records || []);
        setPagination({
          ...pagination,
          current,
          pageSize,
          total: res.data?.total || 0,
        });
      } else {
        message.error(res.message || '获取列表失败');
      }
    } catch (error) {
      console.error('获取列表失败:', error);
      message.error('获取列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    fetchList({ current: 1, pageSize: 10 });
  }, []);

  // 表格变化处理
  const handleTableChange = (paginationParams: any) => {
    fetchList({
      current: paginationParams.current,
      pageSize: paginationParams.pageSize,
    });
  };

  // 搜索
  const handleSearch = (values: any) => {
    const params = { ...values };

    // 处理日期范围
    if (params.timeRange && params.timeRange.length === 2) {
      params.startTime = params.timeRange[0].format('YYYY-MM-DD');
      params.endTime = params.timeRange[1].format('YYYY-MM-DD');
      delete params.timeRange;
    }

    setSearchParams(params);
    fetchList({ current: 1, pageSize: pagination.pageSize, ...params });
  };

  // 重置搜索
  const handleReset = () => {
    form.resetFields();
    setSearchParams({});
    fetchList({ current: 1, pageSize: pagination.pageSize });
  };

  // 新增任务
  const handleAdd = () => {
    history.push({
      pathname: 'supplierAnnualTaskManageAdd',
    });
  };

  // 编辑任务
  const handleEdit = (record: supplierAnnualTaskManage.TaskRecord) => {
    if (record.status !== AnnualTaskStatus.PENDING) {
      message.warning('只有待执行状态的任务才能编辑！');
      return;
    }

    history.push(`/supplierAnnual/supplierAnnualTaskManageAdd?id=${record.id}&mode=edit`);
  };

  // 查看详情
  const handleView = (record: supplierAnnualTaskManage.TaskRecord) => {
    history.push({
      pathname: '/supplierAnnual/supplierAnnualTaskManageDetail?id=' + record.id,
    });
  };

  // 获取状态标签
  const getStatusTag = (status: string, statusName: string) => {
    const color = AnnualTaskStatusColor[status] || 'default';
    return <Tag color={color}>{statusName || AnnualTaskStatusText[status] || '未知状态'}</Tag>;
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 80,
      render: (_: any, __: any, index: number) =>
        index + 1 + (pagination.current - 1) * pagination.pageSize,
    },
    {
      title: '评价主题',
      dataIndex: 'annualreviewTheme',
      key: 'annualreviewTheme',
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '发起单位',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 150,
    },
    {
      title: '评价开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      width: 140,
    },
    {
      title: '评价结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      width: 140,
    },
    {
      title: '评价状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string, record: supplierAnnualTaskManage.TaskRecord) =>
        getStatusTag(status, record.statusName),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      fixed: 'right' as const,
      align: 'center' as const,
      render: (_: any, record: supplierAnnualTaskManage.TaskRecord) => (
        <Space size="middle">
          <Button type="link" size="small" onClick={() => handleView(record)}>
            查看
          </Button>
          {record.status === AnnualTaskStatus.PENDING && (
            <Button type="link" size="small" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
        </Space>
      ),
    },
  ];

  return (
    <div className="common-container">
      <div className="filter-action-row">
        <Form
          form={form}
          name="search"
          onFinish={handleSearch}
          layout="inline"
          className="filter-form"
        >
          <Form.Item name="annualreviewTheme" label="评价主题">
            <Input placeholder="请输入评价主题" allowClear />
          </Form.Item>
          <Form.Item name="timeRange" label="评价时间">
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              format="YYYY-MM-DD"
              style={{ width: 230 }}
            />
          </Form.Item>
          <Form.Item name="status" label="评价状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 150 }}>
              {AnnualTaskStatusOptions.map((item) => (
                <Option key={item.value} value={item.value}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item className="filter-btns">
            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
              搜索
            </Button>
            <Button type="primary" danger icon={<DeleteOutlined />} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <div className="right-buttons">
          <Button type="primary" ghost icon={<PlusOutlined />} onClick={handleAdd}>
            新增任务
          </Button>
        </div>
      </div>

      <div className="content-area">
        <Table
          columns={columns}
          dataSource={data}
          rowKey="id"
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1100 }}
        />
      </div>
    </div>
  );
};

export default SupplierAnnualTaskManage;
