package com.ruoyi.web.modules.news.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.category.domain.vo.InformationCategoryItemVo;
import com.ruoyi.web.modules.category.service.IBizInformationCategoryService;

/**
 * 农技课堂 type 须为 v_agricultural_course 涉及的类别编码（005 下主题或 006 下培训状态）。
 */
@Component
public class AgriculturalCourseTypeValidator
{
    @Autowired
    private IBizInformationCategoryService bizInformationCategoryService;

    public void assertAllowed(String typeCode)
    {
        AgriculturalCourseValidation.validateType(typeCode);
        if (!isAgriculturalCourseType(typeCode.trim()))
        {
            throw new ServiceException("类型无效，请选择农技课堂支持的类型");
        }
    }

    private boolean isAgriculturalCourseType(String code)
    {
        if (matchesChildren(AgriculturalCourseRules.PARENT_VIDEO_TOPIC,
                AgriculturalCourseRules.CATEGORY_TYPE_VIDEO_TOPIC, code))
        {
            return true;
        }
        return matchesChildren(AgriculturalCourseRules.PARENT_TRAINING_STATUS, null, code);
    }

    private boolean matchesChildren(String parentCode, String categoryType, String code)
    {
        for (InformationCategoryItemVo item : bizInformationCategoryService.selectChildren(parentCode, categoryType))
        {
            if (item != null && code.equals(StringUtils.trim(item.getCode())))
            {
                return true;
            }
        }
        return false;
    }
}
