package com.ruoyi.web.v2.v1.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.model.Pigpen;
import com.ruoyi.app.mapper.PigpenMapper;
import com.ruoyi.common.core.domain.AjaxResult;
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.v1.mapper.JsDivideCircleMapper;
import com.ruoyi.web.v2.v1.model.JsDivideCircle;
import com.ruoyi.web.v2.v1.model.JsReport;
import com.ruoyi.web.v2.v1.service.IJsReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

import static com.ruoyi.common.core.domain.AjaxResult.success;

/**
 * <p>
 * v2.0完工报告 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-11
 */
@RestController
@RequestMapping("/js-report")
@Api("2.0完工报告")
public class JsReportController {

    @Autowired
    private IJsReportService reportService;
    @Autowired
    private PigpenMapper pigpenMapper;
    @Autowired
    private JsDivideCircleMapper jsDivideCircleMapper;

    @ApiOperation("完工报告添加")
    @PostMapping("/add")
    public AjaxResult add(@RequestBody JsReport jsReport) {
        jsReport.setCreateTime(new Date());
        Pigpen pigpen = new Pigpen();
        List<Pigpen> pigpens = pigpenMapper.selectPigpenList(pigpen);
        if (pigpens.size() != 0) {
            for (Pigpen pigpen1 : pigpens) {
                pigpen1.setIsUse(0);
                pigpenMapper.updatePigpen(pigpen1);
            }
        }
        return success(reportService.save(jsReport));
    }

    @ApiOperation("完工报告分页")
    @GetMapping("/page")
    public AjaxResult page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize
            , @RequestParam(value = "startTime", required = false) String startTime
            , @RequestParam(value = "endTime", required = false) String endTime) {
        QueryWrapper<JsReport> queryWrapper = new QueryWrapper<>();
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("create_time", startTime + " 00:00:00", endTime + " 23:59:59");
        }
        queryWrapper.lambda().orderByDesc(JsReport::getId);
        Page<JsReport> page = new Page<>(pageNum, pageSize);
        return success(reportService.page(page,queryWrapper));
    }

    @ApiOperation("完工登记")
    @PostMapping("/register")
    public AjaxResult register(@RequestBody List<JsDivideCircle> circles) {
        //根据提交的分圈登记，计算每个批次的剩余存栏量（每个猪圈的存栏量为0后视为该批次完结），然后决定猪圈状态和待宰栏中的该批次数据状态
//        for (JsDivideCircle circle : circles) {
//            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) {
//                        circle.setStatusFlag("opened");
//                        circle.setId(null);
//                        //系统自动插入的数据，分圈时间设置为空
//                        circle.setDivideTime(null);
//                        circle.setCreateTime(new Date());
//                        jsDivideCircleMapper.insert(circle);
//                    }
//                }else {
//                    if (!ObjectUtils.isEmpty(records)) {
//                        circle.setId(null);
//                        //系统自动插入的数据，分圈时间设置为空
//                        circle.setDivideTime(null);
//                        circle.setCreateTime(new Date());
//                        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());
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        jsReport.setUserName(Optional.ofNullable(loginUser.getUser())
//                .map(SysUser::getNickName)
//                .orElse("系统管理员"));
        return success(reportService.register(circles));
    }
}
