package com.ruoyi.app.service.impl;

import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.DTO.JsReportDto;
import com.ruoyi.app.mapper.*;
import com.ruoyi.app.model.DivideCircle;
import com.ruoyi.app.model.request.ReqEntranceBatchList;
import com.ruoyi.app.model.response.ValidEntrance;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.app.model.EntranceBatch;
import com.ruoyi.app.service.IEntranceBatchService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import static com.ruoyi.common.utils.DateUtils.format;


/**
 * 入场批次Service业务层处理
 *
 * @author coede
 * @date 2025-03-19
 */
@Service
public class EntranceBatchServiceImpl implements IEntranceBatchService {
    @Autowired
    private EntranceBatchMapper entranceBatchMapper;

    @Autowired
    private DistributeBatchMapper distributeBatchMapper;

    @Autowired
    private EntranceInspectionMapper entranceInspectionMapper;

    @Autowired
    private HarmlessTreatmentMapper harmlessTreatmentMapper;

    @Autowired
    private DivideCircleMapper divideCircleMapper;


    /**
     * 查询入场批次
     *
     * @param id 入场批次主键
     * @return 入场批次
     */
    @Override
    public EntranceBatch selectEntranceBatchById(Long id) {
        return entranceBatchMapper.selectEntranceBatchDetailById(id);
    }

    /**
     * 查询入场批次列表
     *
     * @param req 入场批次
     * @return 入场批次
     */
    @Override
    public List<EntranceBatch> selectEntranceBatchList(ReqEntranceBatchList req) {
        return entranceBatchMapper.selectEntranceBatchList(req);
    }

    /**/
    @Override
    public List<EntranceBatch> selectEntranceBatchList1(EntranceBatch entranceBatch) {
        JsReportDto jsReportDto = entranceBatchMapper.selectByTime();
        entranceBatch.setCreateTime(jsReportDto.getCreateTime());
        return entranceBatchMapper.selectEntranceBatchList1(entranceBatch);

    }

    @Override
    public List<EntranceBatch> selectEntranceBatchList2(EntranceBatch entranceBatch) {
        List<DivideCircle> closedList = divideCircleMapper.selectList(new LambdaQueryWrapper<DivideCircle>().eq(DivideCircle::getStatusFlag, "closed"));
        //过滤掉所有状态是closed的批次（保留状态是opened的批次以及还未分圈的批次）
        List<EntranceBatch> list = entranceBatchMapper.selectEntranceBatchList1(null).stream()
                .filter(item1 -> closedList.stream()
                        .noneMatch(item2 -> item2.getAnimalCertNo().equals(item1.getAnimalCertNo())))
                // 新增排序逻辑：按时间降序（从最近到最早）
                .sorted(Comparator.comparing(EntranceBatch::getEntranceTime).reversed())
                .collect(Collectors.toList());
//        if(!ObjectUtils.isEmpty(entranceBatch.getEntranceTime())) {
//            //限定数据的日期范围
//            entranceBatch.setCreateTime(Date.from(entranceBatch.getEntranceTime().atZone(ZoneId.systemDefault()).toInstant()));
//            //检索出关联猪圈状态为关闭的记录进行过滤
//            List<DivideCircle> closedList = divideCircleMapper.selectList(new LambdaQueryWrapper<DivideCircle>().eq(DivideCircle::getStatusFlag, "closed"));
//            //过滤掉所有状态是closed的批次（保留状态是opened的批次以及还未分圈的批次）
//            list = entranceBatchMapper.selectEntranceBatchList1(entranceBatch).stream()
//                    .filter(item1 -> closedList.stream()
//                            .noneMatch(item2 -> item2.getAnimalCertNo().equals(item1.getAnimalCertNo())))
//                    .collect(Collectors.toList());
//        }else {
//            //如果输入参数不带时间，就按普通分页查询进行处理
//            list = entranceBatchMapper.selectEntranceBatchList1(entranceBatch);
//        }
        return list;

    }

    /**
     * 校验检疫证号是否唯一
     *
     * @param entranceBatch 入场批次
     * @return 结果
     */
    @Override
    public boolean checkAnimalCertNoUnique(EntranceBatch entranceBatch) {
        Long entranceBatchId = StringUtils.isNull(entranceBatch.getId()) ? -1L : entranceBatch.getId();
        EntranceBatch info = entranceBatchMapper.checkAnimalCertNoUnique(entranceBatch.getAnimalCertNo());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != entranceBatchId.longValue()) {
            return false;
        }
        return true;
    }

    /**
     * 新增入场批次
     *
     * @param entranceBatch 入场批次
     * @return 结果
     */
    @Override
    public Long insertEntranceBatch(EntranceBatch entranceBatch) {
        entranceBatch.setCreateTime(DateUtils.getNowDate());
        //对入场时间进行适配，前端填报的入场时间只有日期，没有时分秒（时间被初始化为凌晨12点），那么自动设置当前系统的时分秒
        entranceBatch.entranceTimeAdapter();
        int result =  entranceBatchMapper.insertEntranceBatch(entranceBatch);
        if (result > 0) {
            return entranceBatch.getId();
        }
        return 0L;
    }

    /**
     * 修改入场批次
     *
     * @param entranceBatch 入场批次
     * @return 结果
     */
    @Override
    public int updateEntranceBatch(EntranceBatch entranceBatch) {
        entranceBatch.setUpdateTime(DateUtils.getNowDate());
        return entranceBatchMapper.updateEntranceBatch(entranceBatch);
    }

    /**
     * 批量删除入场批次
     *
     * @param ids 需要删除的入场批次主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEntranceBatchByIds(Long[] ids) {
        for (Long entranceBatchId : ids) {
            if (entranceBatchId != null) {
                if (distributeBatchMapper.countBatchByEntrance(entranceBatchId) > 0) {
                    throw new ServiceException("有关联分销批次，不能删除");
                }

            }
        }
        //删除无害化、检查信息
        entranceInspectionMapper.deleteEntranceInspectionByIds(ids);
        harmlessTreatmentMapper.deleteHarmlessTreatmentByIds(ids);
        return entranceBatchMapper.deleteEntranceBatchByIds(ids);
    }

    /**
     * 删除入场批次信息
     *
     * @param id 入场批次主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteEntranceBatchById(Long id) {
        if (id != null) {
            if (distributeBatchMapper.countBatchByEntrance(id) > 0) {
                throw new ServiceException("有关联分销批次，不能删除");
            }
        }
        //删除无害化、检查信息
        entranceInspectionMapper.deleteEntranceInspectionById(id);
        harmlessTreatmentMapper.deleteHarmlessTreatmentById(id);
        return entranceBatchMapper.deleteEntranceBatchById(id);
    }

    /**
     * 获取最近一条记录
     *
     * @return 结果
     */
    @Override
    public EntranceBatch selectLatelyEntrance() {
        return entranceBatchMapper.selectLatelyEntrance();
    }

    //获取所有可用批次
    @Override
    public List<ValidEntrance> getAllValidEntrance() {
        List<EntranceBatch> result = entranceBatchMapper.getAllValidEntrance();
        List<ValidEntrance> newData = new ArrayList<>();
        for (EntranceBatch entranceBatch : result) {
            ValidEntrance validEntrance = new ValidEntrance();
            validEntrance.setId(entranceBatch.getId());
            validEntrance.setCarNum( entranceBatch.getSupplier().getCarNum());

            validEntrance.setAnimalCertNo(entranceBatch.getAnimalCertNo());
            validEntrance.setEntranceTime(entranceBatch.getEntranceTime());
            validEntrance.setSupplierId(entranceBatch.getSupplierId());
            if (!ObjectUtils.isEmpty(entranceBatch.getSupplier())){
                validEntrance.setSupplierName(entranceBatch.getSupplier().getSupplierName());
            }
            validEntrance.setVariety(entranceBatch.getVariety());
            validEntrance.setAmount(entranceBatch.getAmount());
            validEntrance.setDesc(String.format("%s,检疫证号:%s,数量:%d~%s", validEntrance.getSupplierName(), validEntrance.getAnimalCertNo(),  validEntrance.getAmount(), validEntrance.getEntranceTime().toLocalDate()));
            validEntrance.setShortDesc(String.format("%s,数量:%d(%s,%s)", validEntrance.getSupplierName(),  validEntrance.getAmount(),validEntrance.getAnimalCertNo(),format(validEntrance.getEntranceTime(),"MM-dd")));
            newData.add(validEntrance);
        }
        return newData;
    }

    @Override
    public Integer getOne( Date dateTime) {
        return entranceBatchMapper.getOne(dateTime);
    }

    @Override
    public List<EntranceBatch> listAll() {
        return entranceBatchMapper.listAll();
    }
}
