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

import com.zhyc.common.annotation.DataScope;
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
    @DataScope(deptAlias = "mpc", userAlias = "mpc")
    public List<NpMilkProdClasses> selectNpMilkProdClassesList(NpMilkProdClasses npMilkProdClasses, Date datetimeStart, Date datetimeEnd) {
        // 修改处：传递实体对象
        return mapper.selectNpMilkProdClassesList(npMilkProdClasses, datetimeStart, datetimeEnd);
    }

    // 修改处：实现搜索方法
    @Override
    public List<String> searchEarNumbers(String query) {
        return mapper.searchEarNumbers(query);
    }

    @Override
    public int importMilkProdClasses(List<NpMilkProdClasses> list) {
        int count = 0;
        for (NpMilkProdClasses item : list) {
            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;

        Double weightCorrection = mapper.getWeightCorrection(item.getDatetime(), item.getFactory());
        if (weightCorrection == null) weightCorrection = 1.0;

        Double parityCorrection = mapper.getParityCorrection(item.getParity());
        if (parityCorrection == null) parityCorrection = 1.0;

        Double dryMatterCorrection = mapper.getDryMatterCorrection(item.getDatetime(), item.getFactory());
        if (dryMatterCorrection == null) dryMatterCorrection = 1.0;

        return milk * weightCorrection * parityCorrection * dryMatterCorrection;
    }
}