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

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizCooperativeDevelopment;

/**
 * 合作社发展数据填报校验
 */
public final class CooperativeDevelopmentValidation
{
    private static final Set<String> SCOPE_SET = new HashSet<>(
            Arrays.asList(CooperativeDevelopmentExcelParser.BUSINESS_SCOPE_LABELS));

    private static final Set<String> MODEL_SET = new HashSet<>(
            Arrays.asList(CooperativeDevelopmentExcelParser.BUSINESS_MODEL_LABELS));

    private static final Set<String> STATUS_SET = new HashSet<>(
            Arrays.asList(CooperativeDevelopmentExcelParser.OPERATION_STATUS_LABELS));

    private CooperativeDevelopmentValidation()
    {
    }

    public static void validateRowForSave(BizCooperativeDevelopment row, TownDeptSupport townDeptSupport)
    {
        if (row == null)
        {
            throw new ServiceException("参数不能为空");
        }
        YakHerdInventoryMonthSupport.validateStatPeriod(row.getStatYear(), row.getStatMonth());
        if (row.getVillageDeptId() == null)
        {
            throw new ServiceException("所属村不能为空");
        }
        if (StringUtils.isEmpty(row.getCooperativeName()))
        {
            throw new ServiceException("合作社名称不能为空");
        }
        row.setCooperativeName(row.getCooperativeName().trim());
        if (row.getCooperativeName().length() > 200)
        {
            throw new ServiceException("合作社名称不能超过200字");
        }
        SysDept village = townDeptSupport.requireReportVillage(row.getVillageDeptId());
        if (village == null)
        {
            throw new ServiceException("所属村不合法");
        }
        SysDept town = townDeptSupport.requireReportTown(village.getParentId());
        if (town == null)
        {
            throw new ServiceException("所属村的上级乡镇不合法");
        }
        row.setVillageName(village.getDeptName());
        row.setTownDeptId(town.getDeptId());
        row.setTownName(town.getDeptName());

        if (StringUtils.isNotEmpty(row.getLegalRepresentative()) && row.getLegalRepresentative().length() > 64)
        {
            throw new ServiceException("法定代表人不能超过64字");
        }
        if (StringUtils.isNotEmpty(row.getEstablishDate()) && row.getEstablishDate().length() > 32)
        {
            throw new ServiceException("成立时间不能超过32字");
        }

        validateNonNegative(row.getMemberHouseholdCount(), "入社户数");
        validateNonNegative(row.getMemberPopulationCount(), "入社人数");
        validateNonNegative(row.getPovertyMonitorCount(), "防返贫监测人数");
        validateNonNegative(row.getCattleShareCount(), "牛入股数量");
        validateNonNegative(row.getSheepShareCount(), "羊入股数量");
        validateNonNegative(row.getLaborShareCount(), "劳动力入股");
        validateNonNegative(row.getCollegeGraduateCount(), "吸纳大学生");
        validateNonNegative(row.getFarmerTransferEmploymentCount(), "农牧民转移就业");
        validateNonNegative(row.getCattleInventoryCount(), "牛存栏");
        validateNonNegative(row.getCattleOutboundCount(), "牛出栏");
        validateNonNegative(row.getSheepInventoryCount(), "羊存栏");
        validateNonNegative(row.getSheepOutboundCount(), "羊出栏");
        validateNonNegative(row.getTrademarkProductCount(), "注册商标产品数量");
        validateNonNegative(row.getQualityCertProductCount(), "质量认证产品数量");
        validateNonNegative(row.getTrainingManageCount(), "培训-管理能力");
        validateNonNegative(row.getTrainingSkillCount(), "培训-专业技能");
        validateNonNegative(row.getTrainingOtherCount(), "培训-其他");

        validateNonNegativeDecimal(row.getRegisteredCapital(), "注册资本");
        validateNonNegativeDecimal(row.getYearEndTotalAssets(), "截止年底总资产");
        validateNonNegativeDecimal(row.getGrasslandShareArea(), "草场入股");
        validateNonNegativeDecimal(row.getCashShareAmount(), "现金入股");
        validateNonNegativeDecimal(row.getOtherShareAmount(), "其他入股");
        validateNonNegativeDecimal(row.getTotalIncome(), "总收入");
        validateNonNegativeDecimal(row.getNetIncome(), "纯收入");
        validateNonNegativeDecimal(row.getCashDividend(), "现金分红");
        validateNonNegativeDecimal(row.getInKindDividend(), "实物分红折算");
        validateNonNegativeDecimal(row.getRevolvingFund(), "周转金");
        validateNonNegativeDecimal(row.getLossAmount(), "亏损");
        validateNonNegativeDecimal(row.getCollegeGraduateWage(), "大学生工资性收入");
        validateNonNegativeDecimal(row.getFarmerTransferWage(), "农牧民工资性收入");

        row.setLivestockShareTotal(safe(row.getCattleShareCount()) + safe(row.getSheepShareCount()));
        normalizeBusinessScope(row);
        normalizeBusinessModel(row);
        normalizeOperationStatus(row);

        if (StringUtils.isNotEmpty(row.getRemark()) && row.getRemark().length() > 500)
        {
            throw new ServiceException("备注不能超过500字");
        }
    }

    private static void normalizeBusinessScope(BizCooperativeDevelopment row)
    {
        if (StringUtils.isEmpty(row.getBusinessScope()))
        {
            row.setBusinessScope(null);
            return;
        }
        String[] parts = row.getBusinessScope().split("[,，]");
        Set<String> uniq = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        for (String part : parts)
        {
            if (StringUtils.isEmpty(part))
            {
                continue;
            }
            String label = part.trim();
            if (!SCOPE_SET.contains(label))
            {
                throw new ServiceException("主要经营范围取值不合法：" + label);
            }
            if (uniq.add(label))
            {
                if (sb.length() > 0)
                {
                    sb.append(',');
                }
                sb.append(label);
            }
        }
        row.setBusinessScope(sb.length() == 0 ? null : sb.toString());
    }

    private static void normalizeBusinessModel(BizCooperativeDevelopment row)
    {
        if (StringUtils.isEmpty(row.getBusinessModel()))
        {
            row.setBusinessModel(null);
            return;
        }
        String label = row.getBusinessModel().trim();
        if (!MODEL_SET.contains(label))
        {
            throw new ServiceException("经营模式分类取值不合法");
        }
        row.setBusinessModel(label);
    }

    private static void normalizeOperationStatus(BizCooperativeDevelopment row)
    {
        if (StringUtils.isEmpty(row.getOperationStatus()))
        {
            row.setOperationStatus(null);
            return;
        }
        String label = row.getOperationStatus().trim();
        if (!STATUS_SET.contains(label))
        {
            throw new ServiceException("运营情况取值不合法");
        }
        row.setOperationStatus(label);
    }

    private static void validateNonNegative(Integer value, String label)
    {
        if (value != null && value < 0)
        {
            throw new ServiceException(label + "不能为负数");
        }
    }

    private static void validateNonNegativeDecimal(BigDecimal value, String label)
    {
        if (value != null && value.compareTo(BigDecimal.ZERO) < 0)
        {
            throw new ServiceException(label + "不能为负数");
        }
    }

    private static int safe(Integer value)
    {
        return value == null ? 0 : value;
    }
}
