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_farming_news 涉及的资讯类别叶子编码（001 下 type 1–4、002、003 子项）。
 */
@Component
public class FarmingNewsTypeValidator
{
    private static final String PARENT_STANDARD = "001";

    private static final String[] STANDARD_CATEGORY_TYPES = { "1", "2", "3", "4" };

    private static final String PARENT_TECH = "002";

    private static final String PARENT_POLICY = "003";

    @Autowired
    private IBizInformationCategoryService bizInformationCategoryService;

    public void assertAllowed(String typeCode)
    {
        FarmingNewsValidation.validateType(typeCode);
        if (!isFarmingNewsType(typeCode))
        {
            throw new ServiceException("资讯类型无效，请选择资讯类别中的类型");
        }
    }

    private boolean isFarmingNewsType(String typeCode)
    {
        String code = typeCode.trim();
        if (matchesChildren(PARENT_TECH, null, code) || matchesChildren(PARENT_POLICY, null, code))
        {
            return true;
        }
        for (String categoryType : STANDARD_CATEGORY_TYPES)
        {
            if (matchesChildren(PARENT_STANDARD, categoryType, code))
            {
                return true;
            }
        }
        return false;
    }

    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;
    }
}
