import React, { useState, useEffect } from 'react';
import { history, useIntl } from 'umi';
import { Button, Card, Descriptions, Divider, Spin, message, Typography, Empty } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { getTemplateDetail } from '@/servers/api/supplierEvaluate';
import { TemplateStatusText, CategoryLimitationTypeText } from '@/dicts/supplierTemplateDict';
import EvaluateTemplateTable from '@/components/EvaluateTemplateTable';
import type { TemplateDimension } from '@/servers/dao/supplierEvaluateTask';

const { Title } = Typography;

const SupplierTemplateManageDetail: React.FC = () => {
  const intl = useIntl();
  const [loading, setLoading] = useState<boolean>(false);
  const [templateDetail, setTemplateDetail] = useState<TemplateDimension | null>(null);
  const [templateData, setTemplateData] = useState<any[]>([]);

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

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

        // 直接设置指标数据，无需转换
        if (res.data.indicatorStList && res.data.indicatorStList.length > 0) {
          setTemplateData(res.data.indicatorStList);
        }
      } else {
        message.error(
          intl.formatMessage({ id: 'supplierTemplateManage.message.getDetailFailed' }) ||
            res.message,
        );
      }
    } catch (error) {
      console.error('获取模板详情失败:', error);
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.message.getDetailFailed' }));
    } finally {
      setLoading(false);
    }
  };

  // 首次加载获取数据
  useEffect(() => {
    if (id) {
      fetchTemplateDetail(id);
    } else {
      message.error(intl.formatMessage({ id: 'supplierTemplateManage.detail.idNotExist' }));
      history.goBack();
    }
  }, [id]);

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

  // 获取状态标签
  const getStatusText = (status: string | undefined) => {
    if (!status) return intl.formatMessage({ id: 'supplierTemplateManage.detail.unknown' });
    return (
      TemplateStatusText[status as keyof typeof TemplateStatusText] ||
      intl.formatMessage({ id: 'supplierTemplateManage.detail.unknown' })
    );
  };

  return (
    <div className="common-container">
      <Card>
        <div className="page-header">
          <Title level={4} style={{ margin: 0 }}>
            {intl.formatMessage({ id: 'supplierTemplateManage.detail.title' })}
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            {intl.formatMessage({ id: 'supplierTemplateManage.button.back' })}
          </Button>
        </div>
        <Spin spinning={loading}>
          {templateDetail ? (
            <>
              <Card
                title={intl.formatMessage({ id: 'supplierTemplateManage.detail.card.basicInfo' })}
                bordered={false}
              >
                <Descriptions column={2} bordered>
                  <Descriptions.Item
                    label={intl.formatMessage({
                      id: 'supplierTemplateManage.detail.label.templateName',
                    })}
                  >
                    {templateDetail.templateName}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label={intl.formatMessage({
                      id: 'supplierTemplateManage.detail.label.categoryLimitation',
                    })}
                  >
                    {CategoryLimitationTypeText[
                      templateDetail.categoryLimitation as keyof typeof CategoryLimitationTypeText
                    ] || intl.formatMessage({ id: 'supplierTemplateManage.detail.unknown' })}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label={intl.formatMessage({
                      id: 'supplierTemplateManage.detail.label.category',
                    })}
                  >
                    {templateDetail.categoryName ||
                      intl.formatMessage({ id: 'supplierTemplateManage.detail.unknownCategory' })}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label={intl.formatMessage({ id: 'supplierTemplateManage.detail.label.status' })}
                  >
                    {getStatusText(templateDetail.status)}
                  </Descriptions.Item>
                  <Descriptions.Item
                    label={intl.formatMessage({
                      id: 'supplierTemplateManage.detail.label.createTime',
                    })}
                  >
                    {templateDetail.createTime}
                  </Descriptions.Item>
                  {templateDetail.updateTime && (
                    <Descriptions.Item
                      label={intl.formatMessage({
                        id: 'supplierTemplateManage.detail.label.updateTime',
                      })}
                    >
                      {templateDetail.updateTime}
                    </Descriptions.Item>
                  )}
                </Descriptions>
              </Card>

              <Divider />

              <Card
                title={intl.formatMessage({ id: 'supplierTemplateManage.detail.card.indicators' })}
                bordered={false}
              >
                {templateData.length > 0 ? (
                  <EvaluateTemplateTable value={templateData} isDetail={true} />
                ) : (
                  <Empty
                    description={intl.formatMessage({
                      id: 'supplierTemplateManage.detail.noIndicators',
                    })}
                  />
                )}
              </Card>
            </>
          ) : (
            !loading && (
              <Empty
                description={intl.formatMessage({ id: 'supplierTemplateManage.detail.noDetail' })}
              />
            )
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default SupplierTemplateManageDetail;
