import React, { useState, useEffect } from 'react';
import {
  Button,
  Table,
  Space,
  Modal,
  message,
  Input,
  Select,
  Form,
  Tooltip,
  Tag,
  TablePaginationConfig,
  DatePicker,
  Row,
  Col,
} from 'antd';
import {
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
  EditOutlined,
  EyeOutlined,
} from '@ant-design/icons';
import { history } from 'umi';
import { TaskStatus, TaskType, TaskStatusText, TaskStatusColor, TaskTypeText } from '@/dicts/supplierTaskDict';
import { getTaskList, deleteTask } from '@/servers/api/supplierEvaluate';
import styles from './supplierTaskManage.less';

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

const SupplierTaskManage: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [form] = Form.useForm();
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [isViewMode, setIsViewMode] = useState<boolean>(false);
  const [currentId, setCurrentId] = useState<string>('');

  // 查看详情数据
  const [viewData, setViewData] = useState<SupplierEvaluate.TaskRecord | null>(null);
  const [taskData, setTaskData] = useState<SupplierEvaluate.TaskRecord[]>([]);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total) => `共 ${total} 条记录`,
  });
  const [searchParams, setSearchParams] = useState<SupplierEvaluate.TaskSearchParams>({});

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

    setLoading(true);
    try {
      // 构造请求参数
      const requestParams: SupplierEvaluate.TaskRequest = {
        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;

        // 转换数据结构以适应组件
        const formattedData = records.map(item => ({
          id: item.id || '',
          key: item.id || '',
          taskName: item.evaluateTheme || '',
          taskCode: item.id || '', // 使用id作为临时的taskCode
          status: item.status || '',
          startTime: item.startTime || '',
          endTime: item.endTime || '',
          createBy: item.tenantName || '',
          // 添加必要的字段，以符合TaskRecord类型
          taskType: TaskType.REGULAR, // 默认值，实际应从API获取
          templateName: '评价模板', // 默认值，实际应从API获取
          createTime: item.startTime || '', // 使用开始时间作为创建时间
        }));

        setTaskData(formattedData);
        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, {});
  }, []);

  // 处理查看
  const handleView = (record: SupplierEvaluate.TaskRecord) => {
    setCurrentId(record.id);
    setIsViewMode(true);
    setViewData(record);
    setModalVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: SupplierEvaluate.TaskRecord) => {
    setIsEdit(true);
    setIsViewMode(false);
    setCurrentId(record.id);
    setViewData(record);
    setModalVisible(true);
  };

  // 处理删除
  const showDeleteConfirm = (record: SupplierEvaluate.TaskRecord) => {
    Modal.confirm({
      title: '确认删除',
      icon: <ExclamationCircleOutlined />,
      content: `确定要删除任务: ${record.taskName}?`,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      maskClosable: false,
      onOk: async () => {
        try {
          const response = await deleteTask(record.id);
          if (response.success) {
            message.success('删除成功');
            fetchTaskList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(response.message || '删除任务失败');
          }
        } catch (error) {
          console.error('删除任务失败:', error);
          message.error('删除任务失败');
        }
      },
    });
  };

  // 处理发布/取消
  const handlePublishStatus = (record: SupplierEvaluate.TaskRecord) => {
    const isInProgress = record.status === TaskStatus.PROCESSING;
    const actionText = isInProgress ? '取消' : '开始';

    Modal.confirm({
      title: `确认${actionText}`,
      icon: <ExclamationCircleOutlined />,
      content: `确定要${actionText}任务: ${record.taskName}?`,
      okText: '确定',
      cancelText: '取消',
      maskClosable: false,
      onOk: async () => {
        try {
          // 这里需要添加实际的API调用
          message.success(`${actionText}成功`);
          fetchTaskList(pagination.current, pagination.pageSize, searchParams);
        } catch (error) {
          console.error(`${actionText}失败:`, error);
          message.error(`${actionText}失败`);
        }
      },
    });
  };

  // 获取状态标签
  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, __: SupplierEvaluate.TaskRecord, index: number) =>
        (pagination.current! - 1) * pagination.pageSize! + index + 1,
      width: 80,
    },
    {
      title: '评价主题',
      dataIndex: 'taskName',
      key: 'taskName',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (taskName: string) => (
        <Tooltip placement="topLeft" title={taskName}>
          {taskName}
        </Tooltip>
      ),
    },
    {
      title: '发起单位',
      dataIndex: 'createBy',
      key: 'createBy',
      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: 180,
      align: 'center' as const,
      render: (_: unknown, record: SupplierEvaluate.TaskRecord) => (
        <Space size="middle">
          <Button type="link" onClick={() => handleView(record)}>
            查看
          </Button>
          <Button type="link" onClick={() => handleEdit(record)}>
            修改
          </Button>
          <Button type="link" onClick={() => showDeleteConfirm(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, params);
  };

  // 处理模态框取消
  const handleModalCancel = () => {
    setModalVisible(false);
    setIsViewMode(false);
    setViewData(null);
  };

  // 渲染任务详情
  const renderTaskDetail = () => {
    if (!viewData) return null;

    return (
      <div className={styles.taskDetail}>
        <Row gutter={[16, 16]}>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>任务名称：</span>
              <span className={styles.content}>{viewData.taskName}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>任务编号：</span>
              <span className={styles.content}>{viewData.taskCode}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>任务类型：</span>
              <span className={styles.content}>
                {TaskTypeText[viewData.taskType as keyof typeof TaskTypeText] || '未知类型'}
              </span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>使用模板：</span>
              <span className={styles.content}>{viewData.templateName}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>状态：</span>
              <span className={styles.content}>{getStatusTag(viewData.status)}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>开始时间：</span>
              <span className={styles.content}>{viewData.startTime}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>结束时间：</span>
              <span className={styles.content}>{viewData.endTime}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>创建人：</span>
              <span className={styles.content}>{viewData.createBy}</span>
            </div>
          </Col>
          <Col span={12}>
            <div className={styles.detailItem}>
              <span className={styles.label}>创建时间：</span>
              <span className={styles.content}>{viewData.createTime}</span>
            </div>
          </Col>
          {viewData.updateBy && (
            <Col span={12}>
              <div className={styles.detailItem}>
                <span className={styles.label}>更新人：</span>
                <span className={styles.content}>{viewData.updateBy}</span>
              </div>
            </Col>
          )}
          {viewData.updateTime && (
            <Col span={12}>
              <div className={styles.detailItem}>
                <span className={styles.label}>更新时间：</span>
                <span className={styles.content}>{viewData.updateTime}</span>
              </div>
            </Col>
          )}
        </Row>
      </div>
    );
  };

  // 渲染任务表单
  const renderTaskForm = () => {
    return (
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        initialValues={viewData || {}}
      >
        <Form.Item
          label="任务名称"
          name="taskName"
          rules={[{ required: true, message: '请输入任务名称' }]}
        >
          <Input placeholder="请输入任务名称" />
        </Form.Item>

        <Form.Item
          label="任务编号"
          name="taskCode"
          rules={[{ required: true, message: '请输入任务编号' }]}
        >
          <Input placeholder="请输入任务编号" disabled={isEdit} />
        </Form.Item>

        <Form.Item
          label="任务类型"
          name="taskType"
          rules={[{ required: true, message: '请选择任务类型' }]}
        >
          <Select placeholder="请选择任务类型">
            <Option value={TaskType.REGULAR}>{TaskTypeText[TaskType.REGULAR]}</Option>
            <Option value={TaskType.SPECIAL}>{TaskTypeText[TaskType.SPECIAL]}</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="使用模板"
          name="templateName"
          rules={[{ required: true, message: '请选择使用模板' }]}
        >
          <Select placeholder="请选择使用模板">
            <Option value="常规评价模板1">常规评价模板1</Option>
            <Option value="常规评价模板2">常规评价模板2</Option>
            <Option value="专项评价模板1">专项评价模板1</Option>
            <Option value="专项评价模板2">专项评价模板2</Option>
          </Select>
        </Form.Item>

        <Form.Item
          label="时间范围"
          rules={[{ required: true, message: '请选择时间范围' }]}
        >
          <RangePicker />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={handleModalCancel}>
            取消
          </Button>
        </Form.Item>
      </Form>
    );
  };

  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();
                fetchTaskList(1, pagination.pageSize, {});
              }}
            >
              重置
            </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}
          dataSource={taskData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1500 }}
        />
      </div>

      {/* 新增/编辑/查看模态框 */}
      <Modal
        title={isViewMode
          ? "查看任务详情"
          : isEdit
          ? "编辑任务"
          : "新增任务"}
        visible={modalVisible}
        onCancel={handleModalCancel}
        width={800}
        maskClosable={false}
        destroyOnClose
        footer={
          isViewMode
            ? [
                <Button key="close" onClick={handleModalCancel}>
                  关闭
                </Button>,
              ]
            : null
        }
      >
        {isViewMode ? renderTaskDetail() : renderTaskForm()}
      </Modal>
    </div>
  );
};

export default SupplierTaskManage;
