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

import java.util.List;
import java.util.stream.Collectors;

import com.zhyc.common.annotation.DataScope;
import com.zhyc.module.base.domain.DaSheepfold;
import com.zhyc.module.feed.domain.SgFeedList;
import com.zhyc.module.feed.domain.SgFeedPlan;
import com.zhyc.module.feed.domain.SgFormulaList;
import com.zhyc.module.feed.service.ISgFeedListService;
import com.zhyc.module.feed.service.ISgFeedPlanService;
import org.springframework.stereotype.Service;
import com.zhyc.module.feed.mapper.SgFeedStatisticMapper;
import com.zhyc.module.feed.domain.SgFeedStatistic;
import com.zhyc.module.feed.service.ISgFeedStatisticService;

/**
 * 饲喂量统计Service业务层处理
 *
 * @author HashMap
 * @date 2025-08-23
 */
@Service
public class SgFeedStatisticServiceImpl implements ISgFeedStatisticService {
    private final SgFeedStatisticMapper sgFeedStatisticMapper;

    private final ISgFeedListService sgFeedListService;
    private final ISgFeedPlanService sgFeedPlanService;

    public SgFeedStatisticServiceImpl(SgFeedStatisticMapper sgFeedStatisticMapper, ISgFeedListService sgFeedListService, ISgFeedPlanService sgFeedPlanService) {
        this.sgFeedStatisticMapper = sgFeedStatisticMapper;
        this.sgFeedListService = sgFeedListService;
        this.sgFeedPlanService = sgFeedPlanService;
    }

    /**
     * 查询饲喂量统计
     *
     * @param id 饲喂量统计主键
     * @return 饲喂量统计
     */
    @Override
    public SgFeedStatistic selectSgFeedStatisticById(String id) {
        return sgFeedStatisticMapper.selectSgFeedStatisticById(id);
    }

    /**
     * 查询饲喂量统计列表
     *
     * @param sgFeedStatistic 饲喂量统计
     * @return 饲喂量统计
     */
    @Override
    @DataScope(deptAlias = "sg_feed_statistic_alias", userAlias = "sg_feed_statistic_alias")
    public List<SgFeedStatistic> selectSgFeedStatisticList(SgFeedStatistic sgFeedStatistic) {
        return sgFeedStatisticMapper.selectSgFeedStatisticList(sgFeedStatistic);
    }

    /**
     * 新增饲喂量统计
     *
     * @param sgFeedStatistic 饲喂量统计
     * @return 结果
     */
    @Override
    public int insertSgFeedStatistic(SgFeedStatistic sgFeedStatistic) {
        return sgFeedStatisticMapper.insertSgFeedStatistic(sgFeedStatistic);
    }

    /**
     * 修改饲喂量统计
     *
     * @param sgFeedStatistic 饲喂量统计
     * @return 结果
     */
    @Override
    public int updateSgFeedStatistic(SgFeedStatistic sgFeedStatistic) {
        return sgFeedStatisticMapper.updateSgFeedStatistic(sgFeedStatistic);
    }

    /**
     * 批量删除饲喂量统计
     *
     * @param ids 需要删除的饲喂量统计主键
     * @return 结果
     */
    @Override
    public int deleteSgFeedStatisticByIds(String[] ids) {
        return sgFeedStatisticMapper.deleteSgFeedStatisticByIds(ids);
    }

    /**
     * 删除饲喂量统计信息
     *
     * @param id 饲喂量统计主键
     * @return 结果
     */
    @Override
    public int deleteSgFeedStatisticById(String id) {
        return sgFeedStatisticMapper.deleteSgFeedStatisticById(id);
    }

    /**
     * 向待插入数据表单提供数据预载服务
     *
     * @param sgFeedStatistic 待填充的初始化数据
     * @author ShiHan Wang
     */
    @Override
    public void getInitSgFeedStatistic(SgFeedStatistic sgFeedStatistic) {
        // 1. 查找饲料清单
        SgFeedList sgFeedListQuery = new SgFeedList();
        sgFeedListQuery.setFormulaId(sgFeedStatistic.getFormulaId());
        sgFeedListQuery.setFormulaBatchId(sgFeedStatistic.getFormulaBatchId());

        List<SgFeedList> feedLists = sgFeedListService.selectSgFeedListList(sgFeedListQuery);

        if (!feedLists.isEmpty()) {
            // 刷新缓存
            sgFeedListService.SyncFeedList();

            // 从缓存获取完整配方清单
            String cacheKey = sgFeedStatistic.getFormulaId() + "_" + sgFeedStatistic.getFormulaBatchId() + "_" + sgFeedStatistic.getFeedDate();
            SgFeedList sgFeedList = SgFeedListServiceImpl.getSgFeedListMap().get(cacheKey);

            if (sgFeedList != null && sgFeedList.getFormulaList() != null) {
                // 并行流式计算 提高性能
                sgFeedList.getFormulaList().parallelStream().forEach(item -> {
                    double ratio = item.getRatio() / 100.0;
                    double feedSize = sgFeedList.getRootPlan().getPlanMorningSize() * ratio
                            + sgFeedList.getRootPlan().getPlanNoonSize() * ratio
                            + sgFeedList.getRootPlan().getPlanAfternoonSize() * ratio;
                    item.setFeedSize(feedSize);
                });

                // 统计总和
                double totalFeedSize = sgFeedList.getFormulaList()
                        .parallelStream()
                        .mapToDouble(SgFormulaList::getFeedSize)
                        .sum();
                sgFeedStatistic.setMaterialList(sgFeedList.getFormulaList());
                sgFeedStatistic.setFeedTotalSize(totalFeedSize);
            } else {
                throw new RuntimeException("WARNING: 当前日期无饲喂计划");
            }
        }

        // 2. 查找饲喂计划并填充羊舍信息
        SgFeedPlan sgFeedPlanQuery = new SgFeedPlan();
        sgFeedPlanQuery.setFormulaId(sgFeedStatistic.getFormulaId());
        sgFeedPlanQuery.setBatchId(sgFeedStatistic.getFormulaBatchId());
        sgFeedPlanQuery.setPlanDate(sgFeedStatistic.getFeedDate());
        List<SgFeedPlan> sgFeedPlans = sgFeedPlanService.selectSgFeedPlanList(sgFeedPlanQuery);

        if (!sgFeedPlans.isEmpty()) {
            // 并行计算提高查询性能
            List<DaSheepfold> sheepfolds = sgFeedPlans.parallelStream()
                    .map(plan -> {
                        DaSheepfold sheepfold = new DaSheepfold();
                        sheepfold.setId((long) plan.getSheepHouseId());
                        return sheepfold;
                    })
                    .collect(Collectors.toList());

            long sheepCount = sgFeedPlans.parallelStream()
                    .mapToLong(SgFeedPlan::getSheepCount)
                    .sum();
            sgFeedStatistic.setSheepFoldList(sheepfolds);
            sgFeedStatistic.setSheepFoldCount(sheepCount);
            // 计算日均饲喂量
            sgFeedStatistic.setFeedDailySize(sgFeedStatistic.getFeedTotalSize() / sgFeedStatistic.getSheepFoldCount());
        } else {
            throw new RuntimeException("WARNING: 不存在该计划");
        }
    }
}
