/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.unis.reserveLayout.modular.grainInspectionArchive.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.reserveLayout.modular.grainInspectionArchive.param.GrainInspectionInfoParam;
import com.unis.reserveLayout.modular.utils.DateUtil;
import com.unis.reserveLayout.modular.utils.GenerateNumberUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.unis.common.enums.CommonSortOrderEnum;
import com.unis.common.exception.CommonException;
import com.unis.common.page.CommonPageRequest;
import com.unis.reserveLayout.modular.grainInspectionArchive.entity.GrainInspectionArchive;
import com.unis.reserveLayout.modular.grainInspectionArchive.mapper.GrainInspectionArchiveMapper;
import com.unis.reserveLayout.modular.grainInspectionArchive.param.GrainInspectionArchiveAddParam;
import com.unis.reserveLayout.modular.grainInspectionArchive.param.GrainInspectionArchiveEditParam;
import com.unis.reserveLayout.modular.grainInspectionArchive.param.GrainInspectionArchiveIdParam;
import com.unis.reserveLayout.modular.grainInspectionArchive.param.GrainInspectionArchivePageParam;
import com.unis.reserveLayout.modular.grainInspectionArchive.service.GrainInspectionArchiveService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;

/**
 * 粮情检查档案Service接口实现类
 *
 * @author QSHan
 * @date 2024/06/07 10:53
 **/
@Service
public class GrainInspectionArchiveServiceImpl extends ServiceImpl<GrainInspectionArchiveMapper, GrainInspectionArchive> implements GrainInspectionArchiveService {
    @Resource
    private GrainInspectionArchiveMapper grainInspectionArchiveMapper;

    @Override
    public Page<GrainInspectionArchive> page(GrainInspectionArchivePageParam param) {
        QueryWrapper<GrainInspectionArchive> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(param.getStorehouseName()))
            queryWrapper.like("bs.storehouse_name", param.getStorehouseName());
        if (ObjectUtil.isNotEmpty(param.getReportType()))
            queryWrapper.eq("gia.report_type", param.getReportType());
        if (ObjectUtil.isNotEmpty(param.getReportDate()))
            queryWrapper.eq("gia.report_date", param.getReportDate());
        queryWrapper.lambda().orderByDesc(GrainInspectionArchive::getId);
        return grainInspectionArchiveMapper.pageList(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(GrainInspectionArchiveAddParam grainInspectionArchiveAddParam) {
        GrainInspectionArchive grainInspectionArchive = BeanUtil.toBean(grainInspectionArchiveAddParam, GrainInspectionArchive.class);
        // 编号(LQJCDA+年月日+五位顺序号)
        grainInspectionArchive.setArchiveNumber(this.GetArchiveNumber());
        this.save(grainInspectionArchive);
    }

    // 编号 LQJCDA+年月日+五位顺序号
    private synchronized String GetArchiveNumber() {
        // 查询最后一个顺序号
        String xh = grainInspectionArchiveMapper.selectOnly();
        // 初始化
        int num = 1;
        if (!StringUtils.isEmpty(xh)) {
            String substring = xh.substring(xh.length() - 5);
            int i = Integer.parseInt(substring);
            if (i < 99999)
                num += i;
        }
        return String.format(
                "%s%s%s", "LQJCDA",
                DateUtil.getYMD(new Date()),
                GenerateNumberUtil.integerToString(5, num)
        );
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(GrainInspectionArchiveEditParam grainInspectionArchiveEditParam) {
        GrainInspectionArchive grainInspectionArchive = this.queryEntity(grainInspectionArchiveEditParam.getId());
        BeanUtil.copyProperties(grainInspectionArchiveEditParam, grainInspectionArchive);
        this.updateById(grainInspectionArchive);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<GrainInspectionArchiveIdParam> grainInspectionArchiveIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(grainInspectionArchiveIdParamList, GrainInspectionArchiveIdParam::getId));
    }

    @Override
    public GrainInspectionArchive detail(GrainInspectionArchiveIdParam grainInspectionArchiveIdParam) {
        return this.queryEntity(grainInspectionArchiveIdParam.getId());
    }

    @Override
    public GrainInspectionArchive queryEntity(String id) {
        GrainInspectionArchive grainInspectionArchive = this.getById(id);
        if (ObjectUtil.isEmpty(grainInspectionArchive)) {
            throw new CommonException("粮情检查档案不存在，id值为：{}", id);
        }
        return grainInspectionArchive;
    }

    @Override
    public GrainInspectionInfoParam getDetailInfo(Integer reportType, Integer orgId, Integer storehouseId) {
        // 报告类型，1：日报；2：周报；3：月报；4：季报；5：年报
        Map<String, Object> param = new HashMap<>();
        param.put("orgId", orgId);
        param.put("storehouseId", storehouseId);
        String startTime = "";
        String endTime = "";
        if (1 == reportType) { // 日报
            startTime = DateUtil.getNDay(1);
            endTime = DateUtil.getNow(new Date());
        } else if (2 == reportType) { // 周报
            endTime = DateUtil.getNow(new Date());
            startTime = DateUtil.getNDay(7);
        } else if (3 == reportType) { // 月报
            endTime = DateUtil.getNow(new Date());
            startTime = DateUtil.getNDay(30);
        } else if (4 == reportType) { // 季报
            startTime = DateUtil.getNow(new Date());
            endTime = DateUtil.getNDay(90);
        } else if (5 == reportType) { // 年报
            endTime = DateUtil.getNow(new Date());
            startTime = DateUtil.getNDay(365);
        } else { // 默认日报
            endTime = DateUtil.getNow(new Date());
            startTime = DateUtil.getNDay(1);
        }
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        List<GrainInspectionInfoParam> detailInfo = grainInspectionArchiveMapper.getDetailInfo(param);
        GrainInspectionInfoParam paramResult = new GrainInspectionInfoParam();
        if (CollectionUtils.isEmpty(detailInfo)) {
            return paramResult;
        }
        paramResult.setStorehouseId(detailInfo.get(0).getStorehouseId());
        paramResult.setStorehouseType(detailInfo.get(0).getStorehouseType());
        paramResult.setStorehouseTypeName(detailInfo.get(0).getStorehouseTypeName());
        paramResult.setGrainVarietyId(detailInfo.get(0).getGrainVarietyId());
        paramResult.setFoodVarietyName(detailInfo.get(0).getFoodVarietyName());
        // 最高-最高
        BigDecimal maxMax = detailInfo.stream().filter(GrainInspectionInfoParam -> !GrainInspectionInfoParam.getTempMax().equals(new BigDecimal("250.0"))).map(GrainInspectionInfoParam::getTempMax).reduce(BigDecimal.ZERO, BigDecimal::max);
        paramResult.setTempMax(maxMax);
        BigDecimal minMin = detailInfo.stream().filter(GrainInspectionInfoParam -> !GrainInspectionInfoParam.getTempMin().equals(new BigDecimal("250.0"))).map(GrainInspectionInfoParam::getTempMin).reduce(BigDecimal.ZERO, BigDecimal::min);
        paramResult.setTempMin(minMin);
        BigDecimal avgMax = detailInfo.stream().filter(GrainInspectionInfoParam -> !GrainInspectionInfoParam.getTempAvg().equals(new BigDecimal("250.0"))).map(GrainInspectionInfoParam::getTempAvg).reduce(BigDecimal.ZERO, BigDecimal::max);
        paramResult.setTempAvg(avgMax);
        return paramResult;
    }
}
