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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.app.model.EntranceBatch;
import com.ruoyi.app.model.HarmlessTreatment;
import com.ruoyi.app.model.Pigpen;
import com.ruoyi.app.mapper.EntranceBatchMapper;
import com.ruoyi.app.mapper.HarmlessTreatmentMapper;
import com.ruoyi.app.mapper.PigpenMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.v2.v1.model.JsDivideCircle;
import com.ruoyi.web.v2.v1.mapper.JsDivideCircleMapper;
import com.ruoyi.web.v2.v1.model.vo.CircleVo;
import com.ruoyi.web.v2.v1.service.IJsDivideCircleService;
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.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.DateUtils.format;

/**
 * <p>
 * v2.0分圈登记 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-05-22
 */
@Service
public class JsDivideCircleServiceImpl extends ServiceImpl<JsDivideCircleMapper, JsDivideCircle> implements IJsDivideCircleService {

    @Autowired
    private JsDivideCircleMapper jsDivideCircleMapper;
    @Autowired
    private PigpenMapper pigpenMapper;
    @Autowired
    private HarmlessTreatmentMapper harmlessTreatmentMapper;
    @Autowired
    private EntranceBatchMapper entranceBatchMapper;

    @Transactional
    @Override
    public AjaxResult add(JsDivideCircle divideCircle) {
        Pigpen pigpen = pigpenMapper.selectPigpenById(divideCircle.getPigpenId().longValue());
        if (pigpen.getIsUse() != 0) {
            return error("新增失败，该待宰圈已被使用");
        }

        HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(divideCircle.getEntranceBatchId().longValue());
        EntranceBatch entranceBatch = entranceBatchMapper.selectEntranceBatchById(divideCircle.getEntranceBatchId().longValue());
        if (ObjectUtil.isEmpty(harmlessTreatment)) {
            return error("未进行无害化处理");
        }
        int i = harmlessTreatment.getIllnessDeadAmount() + harmlessTreatment.getIllnessDiseaseAmount() + harmlessTreatment.getRoadDealAmount();
        if (divideCircle.getAmount() > (entranceBatch.getAmount() - i)) {
            return error("新增失败，分圈数量应小于批次号中现存活猪只数量");
        }
        if (divideCircle.getAmount() > pigpen.getMaxCapacity()) {
            return error("超过猪圈的最大容量");
        }
        String animalCertNo = divideCircle.getAnimalCertNo();
        QueryWrapper<JsDivideCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("animal_cert_no", animalCertNo);
        List<JsDivideCircle> jsDivideCircles = jsDivideCircleMapper.selectList(queryWrapper);
        Integer amount = 0;
        if (jsDivideCircles.size() != 0) {
            for (JsDivideCircle jsDivideCircle : jsDivideCircles) {
                amount = amount + jsDivideCircle.getAmount();
            }
        }
        if (divideCircle.getAmount() > (entranceBatch.getAmount() - i) - amount) {
            return error("该批次中所剩需分圈猪只不足");
        }
        divideCircle.setCreateTime(new Date());
        divideCircle.setSeriesNo(
                generateSeriesNo(animalCertNo, pigpen.getPigpenName(), Date.from(entranceBatch.getEntranceTime().atZone(ZoneId.systemDefault()).toInstant())));
        //分圈添加时的数据，状态都是未闭环的状态
        divideCircle.setStatusFlag("opened");
        jsDivideCircleMapper.insert(divideCircle);
        pigpen.setIsUse(1);
        pigpenMapper.updatePigpen(pigpen);
        return success();
    }

    /**
     * 批次序列号处理
     */
    private String generateSeriesNo(String animalCertNo, String pigpenName, Date entranceTime) {
        try {
            if (ObjectUtil.isNotEmpty(animalCertNo) && ObjectUtil.isNotEmpty(pigpenName) && entranceTime != null) {
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.append(animalCertNo).append(pigpenName)
                        .append(new SimpleDateFormat("yyyyMMdd").format(entranceTime));
                return strBuilder.toString();
            }
        } catch (Exception e) {
            log.error("生成批次序列号出现异常，异常详细是：{}", e);
        }
        return "";
    }

    @Override
    public AjaxResult edit(JsDivideCircle divideCircle) {
        Pigpen pigpen = pigpenMapper.selectPigpenById(divideCircle.getPigpenId().longValue());
        if (pigpen.getIsUse() != 0 && pigpen.getId() != divideCircle.getPigpenId().longValue()) {
            return error("修改失败，该待宰圈已被使用");
        }
        HarmlessTreatment harmlessTreatment = harmlessTreatmentMapper.selectByEntraceBatchId(divideCircle.getEntranceBatchId().longValue());
        EntranceBatch entranceBatch = entranceBatchMapper.selectEntranceBatchById(divideCircle.getEntranceBatchId().longValue());
        if (ObjectUtil.isEmpty(harmlessTreatment)) {
            return error("未进行无害化处理");
        }
        int i = harmlessTreatment.getIllnessDeadAmount() + harmlessTreatment.getIllnessDiseaseAmount() + harmlessTreatment.getRoadDealAmount();
        if (divideCircle.getAmount() > (entranceBatch.getAmount() - i)) {
            return error("修改失败，分圈数量应小于批次号中现存活猪只数量");
        }
        if (divideCircle.getAmount() > pigpen.getMaxCapacity()) {
            return error("超过猪圈的最大容量");
        }
        String animalCertNo = divideCircle.getAnimalCertNo();
        QueryWrapper<JsDivideCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("animal_cert_no", animalCertNo);
        List<JsDivideCircle> jsDivideCircles = jsDivideCircleMapper.selectList(queryWrapper);
        Integer amount = 0;
        if (jsDivideCircles.size() != 0) {
            for (JsDivideCircle jsDivideCircle : jsDivideCircles) {
                amount = amount + jsDivideCircle.getAmount();
            }
        }
        JsDivideCircle circle = jsDivideCircleMapper.selectById(divideCircle.getId());
        if (divideCircle.getAmount() > (entranceBatch.getAmount() - i) + circle.getAmount() - amount) {
            return error("该批次中所剩需分圈猪只不足");
        }
        divideCircle.setCreateTime(new Date());
        pigpen.setIsUse(1);
        pigpenMapper.updatePigpen(pigpen);
        jsDivideCircleMapper.updateById(divideCircle);
        return success();
    }

    @Override
    public AjaxResult delete(String ids) {
        String[] split = ids.split(",");
        for (String s : split) {
            JsDivideCircle jsDivideCircle = jsDivideCircleMapper.selectById(s);
            Pigpen pigpen = pigpenMapper.selectPigpenById(jsDivideCircle.getPigpenId().longValue());
            pigpen.setIsUse(0);
            pigpenMapper.updatePigpen(pigpen);
            jsDivideCircleMapper.deleteById(s);
        }
        return success();
    }

    @Override
    public AjaxResult page(Integer pageNum, Integer pageSize, String startTime, String endTime, String pigpenName) {
        Page<JsDivideCircle> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JsDivideCircle> queryWrapper = new QueryWrapper<>();
        if ("".equals(startTime) || null == startTime) {

        } else {
            queryWrapper.between("divide_time", startTime + " 00:00:00", endTime + " 23:59:59");
        }
        queryWrapper.isNotNull("divide_time");
        queryWrapper.orderByDesc("divide_time");
        queryWrapper.like(StringUtils.isNotEmpty(pigpenName), "pigpen_name", pigpenName);
        return success(jsDivideCircleMapper.selectPage(page, queryWrapper));
    }

    @Override
    public AjaxResult listAll(String startTime) {
        QueryWrapper<JsDivideCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("divide_time", startTime + " 00:00:00");
        return success(jsDivideCircleMapper.selectList(queryWrapper));
    }

    /**
     * 分圈数据核查--暂不使用，备份之前原代码逻辑
     * 用于查询出所有猪圈的当前有效分圈数据，以便完工报告进行数据更新闭环
     *
     * @return
     */
    public AjaxResult review_backup() {
        List<Pigpen> pigpenList = pigpenMapper.selectPigpenList(new Pigpen());
        List<JsDivideCircle> circles = new ArrayList<>();
        for (Pigpen pigpen : pigpenList) {
            //根据猪圈号，检索有效的分圈数据记录(未闭环的数据)
            List<JsDivideCircle> circleList = jsDivideCircleMapper.selectList(new LambdaQueryWrapper<JsDivideCircle>()
                    .eq(JsDivideCircle::getPigpenName, pigpen.getPigpenName())
                    .eq(JsDivideCircle::getStatusFlag, "opened")
                    .orderByDesc(JsDivideCircle::getId).last("limit 1"));
            if (!ObjectUtils.isEmpty(circleList)) {
                circles.add(circleList.get(0));
            } else {
                JsDivideCircle dummyCircle = new JsDivideCircle();
                dummyCircle.setPigpenId(pigpen.getId().intValue());
                dummyCircle.setPigpenName(pigpen.getPigpenName());
                dummyCircle.setAmount(0);
                dummyCircle.setStatusFlag("closed");
                circles.add(dummyCircle);
            }
        }
        return success(circles);
    }

    /**
     * 分圈数据核查 - 2025-10-15
     * 用于查询出所有猪圈的当前有效分圈数据，以便完工报告进行数据更新闭环
     *
     * @return
     */
    @Override
    public List<JsDivideCircle> review() {
        return jsDivideCircleMapper.review();
    }

    @Override
    public AjaxResult listSeriesNo() {
        List<CircleVo> circleVoList = new ArrayList<>();
        List<JsDivideCircle> circles = review();
        for (JsDivideCircle circle : circles) {
            CircleVo circleVo = new CircleVo();
            circleVo.setSupplierName(circle.getSupplierName());
            circleVo.setAnimalCertNo(circle.getAnimalCertNo());
            circleVo.setPigpenName(circle.getPigpenName());
            try {
                if (!ObjectUtils.isEmpty(circle.getSeriesNo())) {
                    circleVo.setEntranceDate(LocalDate.parse(
                            circle.getSeriesNo().substring(circle.getSeriesNo().length() - 8), DateTimeFormatter.ofPattern("yyyyMMdd")));
                }
            } catch (Exception e) {
                log.warn(String.format("处理入场日期出现异常：seriesNo -> %s", circle.getSeriesNo()));
            }
            circleVo.setSupplierId(circle.getSupplierId());
            circleVo.setAmount(circle.getAmount());
            circleVo.setEntranceBatchId(circle.getEntranceBatchId());
            circleVo.setDivideCircleId(circle.getId());
            circleVo.setAnimalType(circle.getAnimalType());
            circleVo.setDesc(String.format("%s,检疫证号:%s,圈号:%s,数量:%d~%s", circleVo.getSupplierName(), circleVo.getAnimalCertNo(), circleVo.getPigpenName(), circleVo.getAmount(), circleVo.getEntranceDate()));
            circleVo.setShortDesc(String.format("%s,数量:%d(%s,%s)", circleVo.getSupplierName(),  circleVo.getAmount(),circleVo.getAnimalCertNo(),format(circleVo.getEntranceDate(),"MM-dd")));
            circleVoList.add(circleVo);
        }

        return success(circleVoList.stream().filter(vo -> vo.getEntranceBatchId() != null)
                .sorted(Comparator.comparing(CircleVo::getEntranceBatchId).reversed())
                .collect(Collectors.toList()));
    }

}
