import React, { useEffect, useState } from 'react';
import {
  Pagination,
  Table,
  Tag,
  Button,
  Space,
  Message,
  Rate,
  Modal,
  Select,
  Radio,
  Input,
  Form
} from '@arco-design/web-react';
import styles from '@/pages/componentDevelopment/componentList/style/index.module.less';
import { getReviewGroupByNew, getComponentHistoryReview, reviewComponentMarket } from '@/api/componentMarket';
import dayjs from 'dayjs';

// 审核记录接口定义
interface ReviewRecord {
  id: string;
  identifier: string;
  componentBaseId: string;
  componentClassify: string;
  name: string;
  reviewOpinion: string;
  componentVersion: number;
  recommend: string;
  attachmentAddress: string;
  publicStatus: number;
  stars: number;
  reviewUserName: string;
  filesName: string;
  createTime: string;
  updateTime: string;
}

// 历史审核记录接口定义
interface HistoryAuditRecord {
  reviewOpinion: string;
  reviewUserName: string;
  createTime: string;
  publicStatus: number;
}

interface HistoryRecord {
  main: ReviewRecord;
  historyAudit: HistoryAuditRecord[];
}

// 发布状态映射
const PUBLIC_STATUS_MAP = {
  '-1': { text: '未发布', color: 'orange' },
  0: { text: '未发布', color: 'orange' },
  1: { text: '已发布', color: 'green' },
  2: { text: '审核中', color: 'arcoblue' },
  3: { text: '审核被拒', color: 'red' }
};

const CompAudit = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ReviewRecord[]>([]);
  const [pagination, setPagination] = useState({
    totalCount: 0,
    pageSize: 10,
    totalPage: 0,
    currPage: 1
  });

  // 历史记录弹窗状态
  const [historyModalVisible, setHistoryModalVisible] = useState(false);
  const [historyLoading, setHistoryLoading] = useState(false);
  const [historyData, setHistoryData] = useState<HistoryRecord[]>([]);
  const [currentRecord, setCurrentRecord] = useState<ReviewRecord | null>(null);

  // 审核弹窗状态
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [reviewLoading, setReviewLoading] = useState(false);
  const [form] = Form.useForm();

  const RadioGroup = Radio.Group;
  const TextArea = Input.TextArea;

  // 历史记录表格列定义
  const historyColumns = [
    {
      title: '组件名称',
      dataIndex: 'name',
      width: 150,
      render: (_, record: HistoryRecord) => record.main.name
    },
    {
      title: '分类',
      dataIndex: 'componentClassify',
      width: 120,
      render: (_, record: HistoryRecord) => record.main.componentClassify
    },
    {
      title: '组件标识',
      dataIndex: 'identifier',
      width: 180,
      render: (_, record: HistoryRecord) => record.main.identifier
    },
    {
      title: '组件版本',
      dataIndex: 'componentVersion',
      width: 100,
      render: (_, record: HistoryRecord) => `v${record.main.componentVersion}`
    },
    {
      title: '发布状态',
      dataIndex: 'publicStatus',
      width: 120,
      render: (_, record: HistoryRecord) => {
        const statusInfo = PUBLIC_STATUS_MAP[record.main.publicStatus] || { text: '未知', color: 'gray' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '组件评分',
      dataIndex: 'stars',
      width: 200,
      render: (_, record: HistoryRecord) => {
        if (record.main.stars < 0) return <span style={{ color: '#999' }}>暂无评分</span>;
        return <Rate disabled allowHalf value={record.main.stars} />;
      }
    },
    {
      title: '组件介绍',
      dataIndex: 'recommend',
      width: 100,
      render: (_, record: HistoryRecord) => record.main.recommend
    },
    {
      title: '审核人',
      dataIndex: 'reviewUserName',
      width: 120,
      render: (_, record: HistoryRecord) => record.main.reviewUserName
    },
    {
      title: '审核结果',
      dataIndex: 'reviewOpinion',
      render: (_, record: HistoryRecord) => record.main.reviewOpinion || '-'
    },
    {
      title: '组件附件',
      dataIndex: 'attachmentAddress',
      width: 120,
      fixed: 'right' as const,
      render: (_, record: HistoryRecord) => {
        if (!record.main.attachmentAddress) return '-';
        return (
          <Button
            type="text"
            size="small"
            onClick={() => handleDownloadAttachments(record.main.attachmentAddress)}
          >
            下载
          </Button>
        );
      }
    }
    // {
    //   title: '操作',
    //   dataIndex: 'operations',
    //   width: 100,
    //   fixed: 'right' as const,
    //   render: (_, record: HistoryRecord) => (
    //     <Button
    //       type="text"
    //       size="small"
    //       onClick={() => handleViewHistoryDetail(record)}
    //     >
    //       查看
    //     </Button>
    //   )
    // }
  ];

  const columns = [
    {
      title: '组件名称',
      dataIndex: 'name',
      width: 150
    },
    {
      title: '分类',
      dataIndex: 'componentClassify',
      width: 120
    },
    {
      title: '组件标识',
      dataIndex: 'identifier',
      width: 180
    },
    {
      title: '组件版本',
      dataIndex: 'componentVersion',
      width: 100,
      render: (version: number) => `v${version}`
    },
    {
      title: '发布状态',
      dataIndex: 'publicStatus',
      width: 120,
      render: (status: number) => {
        const statusInfo = PUBLIC_STATUS_MAP[status] || { text: '未知', color: 'gray' };
        return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
      }
    },
    {
      title: '组件评分',
      dataIndex: 'stars',
      width: 200,
      render: (stars: number) => {
        if (stars < 0) return <span style={{ color: '#999' }}>暂无评分</span>;
        return <Rate disabled allowHalf value={stars} />;
      }
    },
    {
      title: '组件介绍',
      dataIndex: 'recommend',
      width: 100
    },
    {
      title: '审核人',
      dataIndex: 'reviewUserName',
      width: 120
    },
    {
      title: '审核结果',
      dataIndex: 'reviewOpinion',
      // width: 200,
      render: (opinion: string) => opinion || '-'
    },
    {
      title: '操作',
      dataIndex: 'operations',
      width: 200,
      fixed: 'right' as const,
      render: (_, record: ReviewRecord) => (
        <Space>
          <Button
            type="text"
            size="small"
            onClick={() => handleGetHistory(record)}
          >
            版本记录
          </Button>
          {record.publicStatus === 2 && (
            <Button
              type="text"
              size="small"
              onClick={() => handleViewReview(record)}
            >
              组件审核
            </Button>
          )}
        </Space>
      )
    }
  ];

  // 获取组件审核列表数据
  const fetchComponentReview = async () => {
    setLoading(true);
    try {
      const res: any = await getReviewGroupByNew({
        queryType: 'create',
        current: pagination.currPage,
        size: pagination.pageSize
      });

      if (res.code === 200 && res.data) {
        setData(res.data.list || []);
        setPagination({
          totalCount: res.data.totalCount || 0,
          pageSize: res.data.pageSize || 10,
          totalPage: res.data.totalPage || 0,
          currPage: res.data.currPage || 1
        });
      }
      else {
        Message.error(res.msg || '获取审核列表失败');
      }
    } catch (error) {
      console.error('获取审核列表失败:', error);
      Message.error('获取审核列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 下载组件附件
  const handleDownloadAttachments = (attachmentAddress: string) => {
    if (!attachmentAddress || attachmentAddress == '[]') {
      Message.warning('暂无附件');
      return;
    }

    // 按逗号分割多个文件地址
    const fileUrls = attachmentAddress.split(',').map(url => url.trim()).filter(url => url);

    if (fileUrls.length === 0) {
      Message.warning('暂无附件');
      return;
    }

    // 下载所有文件
    fileUrls.forEach((url, index) => {
      // 延迟下载，避免浏览器阻止多个下载
      setTimeout(() => {
        // 使用 fetch 下载文件
        fetch(url)
          .then(response => response.blob())
          .then(blob => {
            const blobUrl = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = blobUrl;
            link.download = url.split('/').pop() || `attachment-${index + 1}`;
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            // 释放 blob URL
            window.URL.revokeObjectURL(blobUrl);
          })
          .catch(error => {
            console.error('下载失败:', error);
            // 如果 fetch 失败，尝试直接打开链接
            window.open(url, '_blank');
          });
      }, index * 500); // 每个文件间隔500ms
    });

    Message.success(`开始下载 ${fileUrls.length} 个文件`);
  };

  // 组件审核
  const handleViewReview = (record: ReviewRecord) => {
    setCurrentRecord(record);
    setReviewModalVisible(true);
    // 初始化表单
    form.setFieldsValue({
      reviewResult: 1, // 默认通过
      stars: 0,
      reason: ''
    });
  };

  // 提交审核
  const handleSubmitReview = async () => {
    try {
      const values = await form.validate();

      if (!currentRecord) {
        Message.error('当前记录不存在');
        return;
      }

      setReviewLoading(true);

      const params = {
        id: Number(currentRecord.id),
        reviewResult: values.reviewResult,
        stars: values.stars,
        reason: values.reason || ''
      };

      const res: any = await reviewComponentMarket(params);

      if (res.code === 200) {
        Message.success('审核成功');
        setReviewModalVisible(false);
        form.resetFields();
        // 刷新列表
        fetchComponentReview();
      }
      else {
        Message.error(res.msg || '审核失败');
      }
    } catch (error) {
      console.error('审核失败:', error);
      if (error?.errors) {
        // 表单验证失败
        return;
      }
      Message.error('审核失败');
    } finally {
      setReviewLoading(false);
    }
  };


  // 查看审核历史
  const handleGetHistory = async (record: ReviewRecord) => {
    setCurrentRecord(record);
    setHistoryModalVisible(true);
    setHistoryLoading(true);

    try {
      const res: any = await getComponentHistoryReview({
        identifier: record.identifier,
        componentVersion: record.componentVersion
      });

      if (res.code === 200 && res.data) {
        setHistoryData(res.data.list || []);
      }
      else {
        Message.error(res.msg || '获取审核历史失败');
      }
    } catch (error) {
      console.error('获取审核历史失败:', error);
      Message.error('获取审核历史失败');
    } finally {
      setHistoryLoading(false);
    }
  };

  // 查看历史记录详情
  const handleViewHistoryDetail = (record: HistoryRecord) => {
    // 展开显示历史审核记录
    if (record.historyAudit && record.historyAudit.length > 0) {
      Modal.info({
        title: '历史审核记录',
        style: { width: 800 },
        content: (
          <div>
            <Table
              columns={[
                {
                  title: '审核时间',
                  dataIndex: 'createTime',
                  render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm:ss')
                },
                {
                  title: '审核人',
                  dataIndex: 'reviewUserName'
                },
                {
                  title: '审核状态',
                  dataIndex: 'publicStatus',
                  render: (status: number) => {
                    const statusInfo = PUBLIC_STATUS_MAP[status] || { text: '未知', color: 'gray' };
                    return <Tag color={statusInfo.color}>{statusInfo.text}</Tag>;
                  }
                },
                {
                  title: '审核意见',
                  dataIndex: 'reviewOpinion',
                  render: (opinion: string) => opinion || '-'
                }
              ]}
              data={record.historyAudit}
              pagination={false}
              border
            />
          </div>
        )
      });
    }
    else {
      Message.info('暂无历史审核记录');
    }
  };

  // 分页变化处理
  const handlePageChange = (page: number, pageSize?: number) => {
    setPagination({
      ...pagination,
      currPage: page,
      pageSize: pageSize || pagination.pageSize
    });
  };

  // 监听分页变化
  useEffect(() => {
    fetchComponentReview();
  }, [pagination.currPage, pagination.pageSize]);

  return (
    <>
      <Table
        columns={columns}
        data={data}
        loading={loading}
        pagination={false}
        scroll={{ x: 1800, y: 'calc(100vh - 380px)' }}
        border={{
          wrapper: true,
          cell: true
        }}
        rowKey="id"
      />
      <div className={styles['pagination-container']}>
        <Pagination
          current={pagination.currPage}
          pageSize={pagination.pageSize}
          total={pagination.totalCount}
          onChange={handlePageChange}
          showTotal
          showJumper
          sizeCanChange
        />
      </div>

      {/* 审核历史弹窗 */}
      <Modal
        title={`审核历史 - ${currentRecord?.name || ''}`}
        visible={historyModalVisible}
        onCancel={() => setHistoryModalVisible(false)}
        footer={null}
        style={{ width: '90%', maxWidth: 1400, minWidth: 800 }}
      >
        <div style={{ minHeight: 700 }}>
          <Table
            columns={historyColumns}
            data={historyData}
            loading={historyLoading}
            pagination={false}
            scroll={{ x: 1800, y: 500 }}
            border={{
              wrapper: true,
              cell: true
            }}
          />
        </div>
      </Modal>

      {/* 组件审核弹窗 */}
      <Modal
        title="组件审核"
        visible={reviewModalVisible}
        onCancel={() => {
          setReviewModalVisible(false);
          form.resetFields();
        }}
        onOk={handleSubmitReview}
        confirmLoading={reviewLoading}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          autoComplete="off"
        >
          <Form.Item label="组件附件">
            {currentRecord?.attachmentAddress ? (
              <Button
                type="primary"
                size="small"
                onClick={() => handleDownloadAttachments(currentRecord.attachmentAddress)}
              >
                下载附件
              </Button>
            ) : (
              <span style={{ color: '#999' }}>暂无附件</span>
            )}
          </Form.Item>

          <Form.Item
            label="组件评分"
            field="stars"
            rules={[{ required: true, message: '请选择评分' }]}
          >
            <Rate allowHalf />
          </Form.Item>

          <Form.Item
            label="审核状态"
            field="reviewResult"
            rules={[{ required: true, message: '请选择审核状态' }]}
          >
            <RadioGroup>
              <Radio value={1}>通过</Radio>
              <Radio value={3}>拒绝</Radio>
            </RadioGroup>
          </Form.Item>

          <Form.Item
            label="驳回原因"
            field="reason"
          >
            <TextArea
              placeholder="请输入驳回原因"
              rows={4}
              maxLength={500}
              showWordLimit
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default CompAudit;