package com.ruoyi.web.v2.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.web.v1.mapper.PigpenMapper;
import com.ruoyi.web.v1.model.Pigpen;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.web.v2.mapper.JsDivideCircleMapper;
import com.ruoyi.web.v2.model.JsDivideCircle;
import com.ruoyi.web.v2.model.JsReport;
import com.ruoyi.web.v2.mapper.JsReportMapper;
import com.ruoyi.web.v2.service.IJsReportService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * v2.0完工报告 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-06-11
 */
@Service
public class JsReportServiceImpl extends ServiceImpl<JsReportMapper, JsReport> implements IJsReportService {

    @Autowired
    private PigpenMapper pigpenMapper;

    @Autowired
    private JsDivideCircleMapper jsDivideCircleMapper;


    @Transactional
    @Override
    public boolean register(List<JsDivideCircle> circles) {
        //当日是否已提交完工报告检测
        boolean doubleReport = checkDuplicatedReport();
        if(doubleReport) {
            throw new RuntimeException("每日只能提交一次完工报告，本日已有提交记录，请勿重复提交...");
        }
        //根据提交的分圈登记，计算每个批次的剩余存栏量（每个猪圈的存栏量为0后视为该批次完结），然后决定猪圈状态和待宰栏中的该批次数据状态
        List<Map<String, String>> logList = new ArrayList<>();
        for (JsDivideCircle circle : circles) {
            if(ObjectUtils.isEmpty(circle.getAmount()) || circle.getAmount() < 0) {
                throw new IllegalArgumentException("待宰栏【" + circle.getPigpenName() + "】的猪只数量不能为空，或小于0...");
            }
            if (!ObjectUtils.isEmpty(circle.getEntranceBatchId()) && !ObjectUtils.isEmpty(circle.getSeriesNo())) {
                //先检索出同批次、同栏的历史记录，针对数量进行逻辑完整性校验，数量的变化过程，不能小于0，小于0就归零
                List<JsDivideCircle> records = jsDivideCircleMapper.selectList(new LambdaQueryWrapper<JsDivideCircle>()
                        .eq(JsDivideCircle::getSeriesNo, circle.getSeriesNo())
                        .eq(JsDivideCircle::getStatusFlag, "opened")
                        .ge(JsDivideCircle::getAmount, circle.getAmount()));
                boolean isDuplicated = records.stream().anyMatch(item -> item.getAmount().equals(circle.getAmount()));
                if(circle.getAmount() > 0) {
                    if (!ObjectUtils.isEmpty(records) && !isDuplicated) {
                        //检测输入数量是否为递减（不允许存栏量是增多的）
                        boolean isIncreasing = records.stream().anyMatch(item -> item.getAmount() < circle.getAmount());
                        if(isIncreasing) {
                            throw new IllegalArgumentException("待宰栏【" + circle.getPigpenName() + "】的存栏量不能多于已登记的数量...");
                        }
                        circle.setStatusFlag("opened");
                        circle.setId(null);
                        //系统自动插入的数据，分圈时间设置为空
                        circle.setDivideTime(null);
                        circle.setCreateTime(new Date());
                        //插入猪圈数据前，同时生成日志记录
                        Map<String, String> logRecord = new HashMap<>();
                        logRecord.put(circle.getPigpenName(), String.valueOf(circle.getAmount()));
                        logList.add(logRecord);
                        jsDivideCircleMapper.insert(circle);
                    }
                }else {
                    if (!ObjectUtils.isEmpty(records)) {
                        circle.setId(null);
                        //系统自动插入的数据，分圈时间设置为空
                        circle.setDivideTime(null);
                        circle.setCreateTime(new Date());
                        Map<String, String> logRecord = new HashMap<>();
                        logRecord.put(circle.getPigpenName(), String.valueOf(circle.getAmount()));
                        logList.add(logRecord);
                        jsDivideCircleMapper.insert(circle);
                        jsDivideCircleMapper.update(null, new LambdaUpdateWrapper<JsDivideCircle>()
                                .eq(JsDivideCircle::getSeriesNo, circle.getSeriesNo())
                                .eq(JsDivideCircle::getStatusFlag, "opened")
                                .set(JsDivideCircle::getStatusFlag, "closed"));
                        Pigpen pigpen = new Pigpen();
                        pigpen.setId(circle.getPigpenId().longValue());
                        pigpen.setIsUse(0);
                        pigpenMapper.updatePigpen(pigpen);
                    }
                }
            }
        }
        //保存完工报告记录
        JsReport jsReport = new JsReport();
        jsReport.setCreateTime(new Date());
        jsReport.setOperationLog(JSONObject.toJSONString(logList));
        LoginUser loginUser = SecurityUtils.getLoginUser();
        jsReport.setUserName(Optional.ofNullable(loginUser.getUser())
                .map(SysUser::getNickName)
                .orElse("系统管理员"));
        return save(jsReport);
    }

    private boolean checkDuplicatedReport() {
        LocalDateTime start = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime end = LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);
        long count = this.count(new LambdaQueryWrapper<JsReport>().between(JsReport::getCreateTime, start,end));
        return count > 0;
    }


}
