import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Table,
  Space,
  Tag,
  DatePicker,
  TablePaginationConfig,
  Tooltip,
  message,
  Modal,
  Timeline,
  Descriptions,
} from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  HistoryOutlined,
  AuditOutlined,
} from '@ant-design/icons';
import { TaskStatus, TaskStatusText, TaskStatusColor } from '@/dicts/supplierTaskDict';
import {
  ProcessStatus,
  ProcessStatusText,
  ProcessStatusColor,
  ApprovalResult,
  ApprovalResultText,
  ApprovalResultColor
} from '@/dicts/supplierEvaluateDict';
import moment from 'moment';
import { history } from 'umi';

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

// 使用全局类型定义

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

  // 审批相关状态
  const [historyModalVisible, setHistoryModalVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<SupplierEvaluate.ApprovalRecord | null>(null);
  const [approvalHistoryData, setApprovalHistoryData] = useState<SupplierEvaluate.ApprovalHistoryRecord[]>([]);

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

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

  // 模拟获取审批列表
  const fetchApprovalList = async (
    current = 1,
    pageSize = 10,
    params: SupplierEvaluate.ApprovalSearchParams = searchParams,
  ) => {
    // 更新搜索参数状态
    if (params !== searchParams) {
      setSearchParams(params);
    }

    setLoading(true);
    try {
      // 模拟API请求
      setTimeout(() => {
        // 模拟数据
        const mockData: SupplierEvaluate.ApprovalRecord[] = Array.from({ length: 35 }).map((_, index) => {
          const id = `${index + 1}`;

          // 随机生成流程状态
          const processStatusOptions = Object.values(ProcessStatus);
          const processStatus = processStatusOptions[Math.floor(Math.random() * processStatusOptions.length)];

          // 随机生成审批结果
          const approvalResultOptions = Object.values(ApprovalResult);
          const approvalResult = approvalResultOptions[Math.floor(Math.random() * approvalResultOptions.length)];

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

          // 随机生成申请日期
          const applyDate = moment().subtract(Math.floor(Math.random() * 60), 'days');

          return {
            id,
            key: id,
            evaluateTitle: `供应商评价任务${index + 1}`,
            evaluateCategory: categoryOptions[categoryIndex].value,
            initiatingUnit: unitOptions[unitIndex].value,
            applyTime: applyDate.format('YYYY-MM-DD'),
            processStatus,
            approvalResult,
          };
        });

        // 根据搜索条件过滤
        let filteredData = [...mockData];
        if (params.evaluateTitle) {
          filteredData = filteredData.filter(item =>
            item.evaluateTitle.includes(params.evaluateTitle || '')
          );
        }
        if (params.processStatus) {
          filteredData = filteredData.filter(item =>
            item.processStatus === params.processStatus
          );
        }
        if (params.approvalResult) {
          filteredData = filteredData.filter(item =>
            item.approvalResult === params.approvalResult
          );
        }
        if (params.timeRange && params.timeRange.length === 2) {
          const start = moment(params.timeRange[0]);
          const end = moment(params.timeRange[1]);
          filteredData = filteredData.filter(item => {
            const itemDate = moment(item.applyTime);
            return itemDate.isBetween(start, end, null, '[]');
          });
        }

        // 分页
        const startIndex = (current - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const paginatedData = filteredData.slice(startIndex, endIndex);

        setApprovalData(paginatedData);
        setPagination({
          ...pagination,
          current,
          pageSize,
          total: filteredData.length,
        });

        setLoading(false);
      }, 500);
    } catch (error) {
      console.error('获取审批列表失败:', error);
      message.error('获取审批列表失败');
      setLoading(false);
    }
  };

  // 模拟获取审批历史记录
  const fetchApprovalHistory = (recordId: string) => {
    // 模拟数据
    const historyData: SupplierEvaluate.ApprovalHistoryRecord[] = [
      {
        id: '1',
        operator: '张三',
        action: '提交申请',
        comment: '提交供应商评价结果审批',
        time: moment().subtract(5, 'days').format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        id: '2',
        operator: '李四',
        action: '部门审核',
        comment: '部门审核通过',
        time: moment().subtract(4, 'days').format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        id: '3',
        operator: '王五',
        action: '经理审批',
        comment: '经理审批通过',
        time: moment().subtract(3, 'days').format('YYYY-MM-DD HH:mm:ss'),
      },
      {
        id: '4',
        operator: '赵六',
        action: '总监审批',
        comment: '总监审批中',
        time: moment().subtract(2, 'days').format('YYYY-MM-DD HH:mm:ss'),
      },
    ];

    setApprovalHistoryData(historyData);
  };

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

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

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

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

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

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

  // 跳转到审批页面
  const handleApproval = (record: SupplierEvaluate.ApprovalRecord) => {
    history.push({
      pathname: '/supplierEvaluateResultApproval/supplierEvaluateResultApprovalInfo',
      state: { record }
    });
  };

  // 打开审批历史弹窗
  const handleViewHistory = (record: SupplierEvaluate.ApprovalRecord) => {
    setCurrentRecord(record);
    fetchApprovalHistory(record.id);
    setHistoryModalVisible(true);
  };

  // 刷新列表
  const refreshList = () => {
    fetchApprovalList(pagination.current, pagination.pageSize, searchParams);
  };

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

  // 获取审批结果标签
  const getApprovalResultTag = (result: string) => {
    const color = ApprovalResultColor[result as keyof typeof ApprovalResultColor] || 'default';
    const text = ApprovalResultText[result as keyof typeof ApprovalResultText] || '未知结果';
    return <Tag color={color}>{text}</Tag>;
  };

  const columns = [
    {
      title: '序号',
      render: (_: any, __: SupplierEvaluate.ApprovalRecord, 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: 'evaluateCategory',
      key: 'evaluateCategory',
      width: 120,
    },
    {
      title: '发起单位',
      dataIndex: 'initiatingUnit',
      key: 'initiatingUnit',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text: string) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '申请时间',
      dataIndex: 'applyTime',
      key: 'applyTime',
      width: 120,
    },
    {
      title: '流程状态',
      dataIndex: 'processStatus',
      key: 'processStatus',
      width: 100,
      align: 'center' as const,
      render: (status: string) => getProcessStatusTag(status),
    },
    {
      title: '审批结果',
      dataIndex: 'approvalResult',
      key: 'approvalResult',
      width: 100,
      align: 'center' as const,
      render: (result: string) => getApprovalResultTag(result),
    },
    {
      title: '操作',
      key: 'action',
      width: 180,
      align: 'center' as const,
      render: (_: unknown, record: SupplierEvaluate.ApprovalRecord) => (
        <Space size="middle">
          {record.approvalResult === ApprovalResult.PENDING && (
            <Button
              type="link"
              onClick={() => handleApproval(record)}
            >
              审批
            </Button>
          )}
          <Button
            type="link"
            onClick={() => handleViewHistory(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="timeRange" label="申请时间">
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              format="YYYY-MM-DD"
            />
          </Form.Item>
          <Form.Item name="processStatus" label="流程状态">
            <Select placeholder="请选择流程状态" allowClear style={{ width: 150 }}>
              <Option value={ProcessStatus.NOT_STARTED}>{ProcessStatusText[ProcessStatus.NOT_STARTED]}</Option>
              <Option value={ProcessStatus.IN_PROGRESS}>{ProcessStatusText[ProcessStatus.IN_PROGRESS]}</Option>
              <Option value={ProcessStatus.COMPLETED}>{ProcessStatusText[ProcessStatus.COMPLETED]}</Option>
            </Select>
          </Form.Item>
          <Form.Item name="approvalResult" label="审批结果">
            <Select placeholder="请选择审批结果" allowClear style={{ width: 150 }}>
              <Option value={ApprovalResult.PENDING}>{ApprovalResultText[ApprovalResult.PENDING]}</Option>
              <Option value={ApprovalResult.APPROVED}>{ApprovalResultText[ApprovalResult.APPROVED]}</Option>
              <Option value={ApprovalResult.REJECTED}>{ApprovalResultText[ApprovalResult.REJECTED]}</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={approvalData}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
        />
      </div>

      {/* 审批历史弹窗 */}
      <Modal
        title="审批历史记录"
        visible={historyModalVisible}
        onCancel={() => setHistoryModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setHistoryModalVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {currentRecord && (
          <div>
            <Descriptions column={2} bordered style={{ marginBottom: 20 }}>
              <Descriptions.Item label="评价主题" span={2}>
                {currentRecord.evaluateTitle}
              </Descriptions.Item>
              <Descriptions.Item label="评价品类">
                {currentRecord.evaluateCategory}
              </Descriptions.Item>
              <Descriptions.Item label="发起单位">
                {currentRecord.initiatingUnit}
              </Descriptions.Item>
            </Descriptions>

            <Timeline mode="left">
              {approvalHistoryData.map((item) => (
                <Timeline.Item key={item.id} label={item.time}>
                  <p><strong>{item.operator}</strong> - {item.action}</p>
                  <p>{item.comment}</p>
                </Timeline.Item>
              ))}
            </Timeline>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default SupplierEvaluateResultApproval;
