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

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

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

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

  // 创建单位数据
  const unitOptions = [
    { label: '中山市合创展包装材料有限公司', value: '中山市合创展包装材料有限公司' },
    { label: '广州市科技发展有限公司', value: '广州市科技发展有限公司' },
    { label: '深圳市创新科技有限公司', value: '深圳市创新科技有限公司' },
    { label: '东莞市制造业有限公司', value: '东莞市制造业有限公司' },
  ];

  // 获取评价结果列表
  const fetchResultList = async (
    current = 1,
    pageSize = 10,
    params: API.EvaluateTaskSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 构建请求参数
      const requestParams: API.EvaluateTaskRequest = {
        basePageRequest: {
          pageNo: current,
          pageSize: pageSize,
        },
      };

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

      // 调用接口获取数据
      const response = await getEvaluateResultList(requestParams);
      if (response.data && response.success) {
        const { records, total, current: currentPage, size } = response.data;

        // 处理数据，增加表格需要的key属性
        const formattedData = records.map(record => ({
          ...record,
          key: record.id,
        }));

        setResultData(formattedData);
        setPagination({
          ...pagination,
          current: currentPage,
          pageSize: size,
          total,
        });
      } else {
        message.error(response.message || '获取评价结果列表失败');
      }
    } catch (error) {
      console.error('获取评价结果列表失败:', error);
      message.error('获取评价结果列表失败');
    } finally {
      setLoading(false);
    }
  };

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

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

  // 处理搜索
  const handleSearch = (values: any) => {
    const { timeRange, ...rest } = values;
    const params: API.EvaluateTaskSearchParams = { ...rest };

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

    fetchResultList(1, pagination.pageSize, params);
  };

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

  // 处理提交审批
  const handleApprove = (record: API.EvaluateTaskRecord) => {
    Modal.confirm({
      title: '提交审批确认',
      content: `确定要提交"${record.evaluateTheme}"的评价任务进行审批吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await submitTaskForApproval(record.id);
          if (response.success) {
            message.success('提交审批成功');
            // 刷新数据
            fetchResultList(pagination.current, pagination.pageSize, searchParams);
          } else {
            message.error(response.message || '提交审批失败');
          }
        } catch (error) {
          console.error('提交审批失败:', error);
          message.error('提交审批失败，请稍后重试');
        }
      }
    });
  };

  // 查看详情 - 修改为跳转到详情页
  const handleViewDetail = (record: API.EvaluateTaskRecord) => {
    history.push({
      pathname: 'supplierEvaluateResultInfo',
      state: { record }
    });
  };

  // 获取状态标签
  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 columns = [
    {
      title: '序号',
      render: (_: any, __: API.EvaluateTaskRecord, 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: 'categoryName',
      key: 'categoryName',
      width: 120,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text || '未指定'}>
          {text || '未指定'}
        </Tooltip>
      ),
    },
    {
      title: '发起单位',
      dataIndex: 'deptName',
      key: 'deptName',
      width: 180,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      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: 100,
      align: 'center' as const,
      render: (_: unknown, record: API.EvaluateTaskRecord) => (
        <Space>
          <Button type="link" onClick={() => handleViewDetail(record)}>
            查看
          </Button>
          {record.approveStatus === null && record.status === '2' && (
            <Button type="link" onClick={() => handleApprove(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="evaluateTheme" label="评价主题">
            <Input placeholder="请输入评价主题" allowClear />
          </Form.Item>
          <Form.Item name="timeRange" label="评价时间">
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              format="YYYY-MM-DD"
            />
          </Form.Item>
          <Form.Item name="status" label="评价状态">
            <Select placeholder="请选择状态" allowClear style={{ width: 150 }}>
              <Option value={TaskStatus.DRAFT}>{TaskStatusText[TaskStatus.DRAFT]}</Option>
              <Option value={TaskStatus.PROCESSING}>{TaskStatusText[TaskStatus.PROCESSING]}</Option>
              <Option value={TaskStatus.COMPLETED}>{TaskStatusText[TaskStatus.COMPLETED]}</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>

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

export default SupplierEvaluateResult;
