import React, { useState, useEffect } from 'react';
import { history, useIntl } 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 intl = useIntl();
  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 || intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.getDetailFailed' }));
      }
    } catch (error) {
      console.error('获取模板详情失败:', error);
      message.error(intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.getDetailFailed' }));
    } finally {
      setLoading(false);
    }
  };

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

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

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

  // 指标表格列定义
  const columns = [
    {
      title: intl.formatMessage({ id: 'supplierAnnualTemplateManage.list.serialNumber' }),
      dataIndex: 'orderBy',
      key: 'orderBy',
      width: 80,
      render: (_: string, __: any, index: number) => index + 1,
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.checkItem' }),
      dataIndex: 'itemName',
      key: 'itemName',
    },
    {
      title: intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.starItem' }),
      dataIndex: 'isStar',
      key: 'isStar',
      width: 100,
      render: (isStar: string) => {
        return isStar === StarOptions.YES ? (
          <Tag color="warning">{intl.formatMessage({ id: 'supplierAnnualTemplateManage.common.yes' })}</Tag>
        ) : (
          <Tag>{intl.formatMessage({ id: 'supplierAnnualTemplateManage.common.no' })}</Tag>
        );
      },
    },
  ];

  return (
    <div className="common-container">
      <Card>
        <div className={styles['page-header']}>
          <Title level={4} style={{ margin: 0 }}>
            {intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.title' })}
          </Title>
          <Button type="link" icon={<ArrowLeftOutlined />} onClick={handleBack}>
            {intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.back' })}
          </Button>
        </div>
        <Spin spinning={loading}>
          {templateDetail ? (
            <>
              <Card title={intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.basicInfo' })} bordered={false} className={styles['detail-card']}>
                <Descriptions column={2} bordered>
                  <Descriptions.Item label={intl.formatMessage({ id: 'supplierAnnualTemplateManage.list.templateName' })}>
                    {templateDetail.templateName}
                  </Descriptions.Item>
                  <Descriptions.Item label={intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.categoryLimitation' })}>
                    {templateDetail.categoryLimitation === CategoryLimitationType.UNIVERSAL
                      ? intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.categoryLimitationUniversal' })
                      : intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.categoryLimitationLimited' })}
                  </Descriptions.Item>
                  {templateDetail.categoryLimitation === CategoryLimitationType.LIMITED && (
                    <Descriptions.Item label={intl.formatMessage({ id: 'supplierAnnualTemplateManage.list.category' })}>
                      {templateDetail.categoryName || intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.unknownCategory' })}
                    </Descriptions.Item>
                  )}
                  <Descriptions.Item label={intl.formatMessage({ id: 'supplierAnnualTemplateManage.list.status' })}>
                    <Tag color={AnnualTemplateStatusColor[templateDetail.status as keyof typeof AnnualTemplateStatusColor]} className={styles['status-tag']}>
                      {getStatusText(templateDetail.status)}
                    </Tag>
                  </Descriptions.Item>
                </Descriptions>
              </Card>

              <Divider />

              <Card title={intl.formatMessage({ id: 'supplierAnnualTemplateManage.add.indicatorInfo' })} 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={intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.noIndicatorData' })} />
                )}
              </Card>
            </>
          ) : (
            !loading && <Empty description={intl.formatMessage({ id: 'supplierAnnualTemplateManage.detail.noTemplateData' })} />
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default SupplierAnnualTemplateManageDetail;
