import React, { useState, useEffect } from 'react';
import { history } from 'umi';
import { Button, Card, Descriptions, Divider, Spin, message, Typography, Empty, Space, Table, Tag } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getAnnualTemplateDetail } from '@/servers/api/supplierAnnual';
import {
  AnnualTemplateStatus,
  AnnualTemplateStatusText,
  AnnualTemplateStatusColor,
} from '@/dicts/supplierAnnualDict';
import styles from './supplierAnnualTemplateManage.less';

const { Title } = Typography;

// 品类限制类型常量
const CategoryLimitationType = {
  UNIVERSAL: '0', // 不限
  LIMITED: '1', // 限制
};

// 品类限制类型文本
const CategoryLimitationTypeText = {
  [CategoryLimitationType.UNIVERSAL]: '不限',
  [CategoryLimitationType.LIMITED]: '限制',
};

// 是否星号项常量
const StarOptions = {
  YES: '1',
  NO: '0',
};

// 是否星号项文本
const StarOptionsText = {
  [StarOptions.YES]: '是',
  [StarOptions.NO]: '否',
};

const SupplierAnnualTemplateManageDetail: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(false);
  const [templateDetail, setTemplateDetail] = useState<supplierAnnualTemplateManage.TemplateDetailData | null>(null);
  const [indicatorList, setIndicatorList] = useState<supplierAnnualTemplateManage.IndicatorItem[]>([]);

  // 从路由获取ID
  const { id } = history.location.state as { id: string };

  // 获取模板详情
  const fetchTemplateDetail = async (templateId: string) => {
    try {
      setLoading(true);
      const res = await getAnnualTemplateDetail(templateId);
      if (res.success && res.data) {
        setTemplateDetail(res.data);

        // 设置指标数据
        if (res.data.indicatorList && res.data.indicatorList.length > 0) {
          setIndicatorList(res.data.indicatorList);
        }
      } else {
        message.error(res.message || '获取模板详情失败');
      }
    } catch (error) {
      console.error('获取模板详情失败:', error);
      message.error('获取模板详情失败');
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (id) {
      fetchTemplateDetail(id);
    } else {
      message.error('模板ID不存在，无法获取详情');
      history.goBack();
    }
  }, [id]);

  // 返回列表页
  const handleBack = () => {
    history.goBack();
  };

  // 获取状态标签
  const getStatusText = (status: string | undefined) => {
    if (!status) return '未知状态';
    return AnnualTemplateStatusText[status as keyof typeof AnnualTemplateStatusText] || '未知状态';
  };

  // 指标表格列定义
  const columns = [
    {
      title: '序号',
      dataIndex: 'orderBy',
      key: 'orderBy',
      width: 80,
      render: (_: string, __: any, index: number) => index + 1,
    },
    {
      title: '检查项目',
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: '星号项',
      dataIndex: 'isStar',
      key: 'isStar',
      width: 100,
      render: (isStar: string) => {
        return isStar === StarOptions.YES ? (
          <Tag color="warning">是</Tag>
        ) : (
          <Tag>否</Tag>
        );
      },
    },
  ];

  return (
    <div className="common-container">
      <Card>
        <div className={styles['page-header']}>
          <Title level={4} style={{ margin: 0 }}>
            年度模板详情
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            返回
          </Button>
        </div>
        <Spin spinning={loading}>
          {templateDetail ? (
            <>
              <Card title="基本信息" bordered={false} className={styles['detail-card']}>
                <Descriptions column={2} bordered>
                  <Descriptions.Item label="模板名称">
                    {templateDetail.templateName}
                  </Descriptions.Item>
                  <Descriptions.Item label="品类限制">
                    {CategoryLimitationTypeText[templateDetail.categoryLimitation as keyof typeof CategoryLimitationTypeText] || '未知'}
                  </Descriptions.Item>
                  {templateDetail.categoryLimitation === CategoryLimitationType.LIMITED && (
                    <Descriptions.Item label="品类">
                      {templateDetail.categoryName || '未知品类'}
                    </Descriptions.Item>
                  )}
                  <Descriptions.Item label="状态">
                    <Tag color={AnnualTemplateStatusColor[templateDetail.status as keyof typeof AnnualTemplateStatusColor]} className={styles['status-tag']}>
                      {getStatusText(templateDetail.status)}
                    </Tag>
                  </Descriptions.Item>
                </Descriptions>
              </Card>

              <Divider />

              <Card title="指标信息" bordered={false} className={styles['detail-card']}>
                {indicatorList.length > 0 ? (
                  <Table
                    columns={columns}
                    dataSource={indicatorList}
                    rowKey="id"
                    pagination={false}
                    bordered
                    className={styles['indicator-table']}
                  />
                ) : (
                  <Empty description="暂无指标数据" />
                )}
              </Card>
            </>
          ) : (
            !loading && <Empty description="暂无模板详情数据" />
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default SupplierAnnualTemplateManageDetail;
