package com.zhyc.module.dairyProducts.service.impl;

import com.zhyc.module.dairyProducts.domain.NpMilkProdClasses;
import com.zhyc.module.dairyProducts.mapper.NpMilkProdClassesMapper;
import com.zhyc.module.dairyProducts.service.INpMilkProdClassesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class NpMilkProdClassesServiceImpl implements INpMilkProdClassesService {

    @Autowired
    private NpMilkProdClassesMapper mapper;

    @Override
    public List<NpMilkProdClasses> selectNpMilkProdClassesList(Date datetimeStart, Date datetimeEnd,
                                                               String manageEarNo, String factory, Integer classes) {
        return mapper.selectNpMilkProdClassesList(datetimeStart, datetimeEnd, manageEarNo, factory, classes);
    }

    @Override
    public int importMilkProdClasses(List<NpMilkProdClasses> list) {
        int count = 0;
        for (NpMilkProdClasses item : list) {
            // 根据管理耳号查 sheep_id
            String sheepId = mapper.selectSheepIdByManageEarNo(item.getManageEarNo());
            if (sheepId == null) continue;

            item.setSheepId(sheepId);

            // 计算校正奶量
            Double correctedMilk = calculateCorrectedMilk(item);
            item.setCorrectedMilk(correctedMilk);

            // 插入数据
            count += mapper.insertNpMilkProdClasses(item);
        }
        return count;
    }

    private Double calculateCorrectedMilk(NpMilkProdClasses item) {
        Double milk = item.getMilk();
        if (milk == null) return null;

        // 1. 称重矫正系数
        Double weightCorrection = mapper.getWeightCorrection(item.getDatetime(), item.getFactory());
        if (weightCorrection == null) weightCorrection = 1.0;

        // 2. 胎次矫正系数
        Double parityCorrection = mapper.getParityCorrection(item.getParity());
        if (parityCorrection == null) parityCorrection = 1.0;

        // 3. 干物质矫正系数
        Double dryMatterCorrection = mapper.getDryMatterCorrection(item.getDatetime(), item.getFactory());
        if (dryMatterCorrection == null) dryMatterCorrection = 1.0;

        return milk * weightCorrection * parityCorrection * dryMatterCorrection;
    }
}