/*
 * 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.rotationPlan.info.modular.rpWarnBiweeklyReport.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateUtil;
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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.rotationPlan.info.modular.rpIssuance.entity.RpIssuance;
import com.unis.rotationPlan.info.modular.rpIssuance.service.RpIssuanceService;
import com.unis.rotationPlan.info.modular.rpWarnThreshold.entity.RpWarnThreshold;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.rotationPlan.info.modular.rpWarnBiweeklyReport.entity.RpWarnBiweeklyReport;
import com.unis.rotationPlan.info.modular.rpWarnBiweeklyReport.mapper.RpWarnBiweeklyReportMapper;
import com.unis.rotationPlan.info.modular.rpWarnBiweeklyReport.param.RpWarnBiweeklyReportAddParam;
import com.unis.rotationPlan.info.modular.rpWarnBiweeklyReport.param.RpWarnBiweeklyReportEditParam;
import com.unis.rotationPlan.info.modular.rpWarnBiweeklyReport.param.RpWarnBiweeklyReportIdParam;
import com.unis.rotationPlan.info.modular.rpWarnBiweeklyReport.param.RpWarnBiweeklyReportPageParam;
import com.unis.rotationPlan.info.modular.rpWarnBiweeklyReport.service.RpWarnBiweeklyReportService;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 轮换计划-库区半月报表-轮换数量预警Service接口实现类
 *
 * @author TS
 * @date  2024/05/08 09:45
 **/
@Service
public class RpWarnBiweeklyReportServiceImpl extends ServiceImpl<RpWarnBiweeklyReportMapper, RpWarnBiweeklyReport> implements RpWarnBiweeklyReportService {

    @Autowired
    private RpIssuanceService rpIssuanceService;

    @Resource
    private RpWarnBiweeklyReportMapper rpWarnBiweeklyReportMapper;
    @Override
    public Page<RpWarnBiweeklyReport> page(RpWarnBiweeklyReportPageParam rpWarnBiweeklyReportPageParam) {
        QueryWrapper<RpWarnBiweeklyReport> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(rpWarnBiweeklyReportPageParam.getSortField(), rpWarnBiweeklyReportPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(rpWarnBiweeklyReportPageParam.getSortOrder());
            queryWrapper.orderBy(true, rpWarnBiweeklyReportPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(rpWarnBiweeklyReportPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(RpWarnBiweeklyReport::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(RpWarnBiweeklyReportAddParam rpWarnBiweeklyReportAddParam) {
        RpWarnBiweeklyReport rpWarnBiweeklyReport = BeanUtil.toBean(rpWarnBiweeklyReportAddParam, RpWarnBiweeklyReport.class);
        this.save(rpWarnBiweeklyReport);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(RpWarnBiweeklyReportEditParam rpWarnBiweeklyReportEditParam) {
        RpWarnBiweeklyReport rpWarnBiweeklyReport = this.queryEntity(rpWarnBiweeklyReportEditParam.getId());
        BeanUtil.copyProperties(rpWarnBiweeklyReportEditParam, rpWarnBiweeklyReport);
        this.updateById(rpWarnBiweeklyReport);
    }

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

    @Override
    public RpWarnBiweeklyReport detail(RpWarnBiweeklyReportIdParam rpWarnBiweeklyReportIdParam) {
        return this.queryEntity(rpWarnBiweeklyReportIdParam.getId());
    }

    @Override
    public RpWarnBiweeklyReport queryEntity(String id) {
        RpWarnBiweeklyReport rpWarnBiweeklyReport = this.getById(id);
        if(ObjectUtil.isEmpty(rpWarnBiweeklyReport)) {
            throw new CommonException("轮换计划-库区半月报表-轮换数量预警不存在，id值为：{}", id);
        }
        return rpWarnBiweeklyReport;
    }

    /**
     * ○ 库区半月报表预警
     * ■ 频率：每个月2号、17号下午3点执行。
     * ■ 功能：没有提交报表，生成预警记录。
     * ● 每月2号：检查上个月16-31号，是否提交报表。
     * ● 每月17号：检查本个月1-15号，是否提交报表。没有提交报表，生成预警记录。
     */
    @Override
    public void taskAction() {
        //检测当前时间是当月第几天
        int day = DateUtil.thisDayOfMonth();
        //每月17号：检查上个月1-15号，是否提交报表。没有提交报表，生成预警记录。
        String startDate;
        String endDate;
        if (day == 17-1){ //17号
            Date firstDay = DateUtil.beginOfMonth(new Date());
            startDate = DateUtil.formatDate(firstDay); //1号
            endDate = DateUtil.formatDate((DateUtil.offsetDay(firstDay,14))); //15号
        }else if (day == 2-1) { //2号
            Date preMotnh = DateUtil.offsetMonth(new Date(),-1); //得到上一月
            Date preFirstDay = DateUtil.beginOfMonth(preMotnh); //上有第一天
            startDate = DateUtil.formatDate((DateUtil.offsetDay(preFirstDay,15))); //16号
            endDate = DateUtil.formatDate(DateUtil.endOfMonth(preMotnh)); //上月最后一天
        }else {
             //其它天不做业务
            return;
        }
        //查询是否有满足条件的已下发的轮换计划
        QueryWrapper<RpIssuance> rpIssuanceQueryWrapper = new QueryWrapper<>();

        rpIssuanceQueryWrapper.lambda().isNotNull(RpIssuance::getIssuanceDate);
        rpIssuanceQueryWrapper.between( "DATE_FORMAT(NOW(), '%Y-%m-%d')","start_date","end_date");

        List<RpIssuance> rpIssuanceList = rpIssuanceService.list(rpIssuanceQueryWrapper);
        if (rpIssuanceList.isEmpty()){
            return;
        }
        for (int i = 0; i < rpIssuanceList.size(); i++) {
            RpIssuance rpIssuance = rpIssuanceList.get(i);
            String id = rpIssuance.getId();
            Integer rpReportId = rpIssuance.getRpReportId();
            //查询轮换计划主表及对应的库区
            List<Map<String,Object>> list = rpWarnBiweeklyReportMapper.getOrgInfos(rpReportId);
            for (int j = 0; j < list.size(); j++) {
                Map<String,Object> map = list.get(j);
                String orgId = list.get(j).getOrDefault("orgId","").toString();
                String unitInfoId = list.get(j).getOrDefault("unitInfoId","").toString();
                //查询规定时间内是否有上报的半月报
                List<Map<String,Object>> list1 = rpWarnBiweeklyReportMapper.getBiweeklyReports(rpReportId,startDate,endDate);
                if (list1.size() <= 0){ //表示未有上报数据
                    RpWarnBiweeklyReport biweeklyReport = new RpWarnBiweeklyReport();
                    biweeklyReport.setRpIssuanceId(id); // 轮换下发id
                    biweeklyReport.setUnitInfoId(unitInfoId); //企业id
                    biweeklyReport.setOrgId(Integer.parseInt(orgId)); //库点id
                    biweeklyReport.setWarningTime(new Date()); //预警时间
                    this.save(biweeklyReport); //保存半月报预警
                }

            }
        }

    }

    /**
     * 获取轮换计划-库区半月报表-轮换数量预警自定义分页
     *
     * @param pageParam
     * @return
     */
    @Override
    public IPage<Map<String, Object>> findPage(RpWarnBiweeklyReportPageParam pageParam) {
        //条形查询器
        QueryWrapper<RpWarnBiweeklyReport> queryWrapper = new QueryWrapper<>();
        //分页相关
        if(StringUtils.isNotBlank(pageParam.getUnitName())){
            queryWrapper.like("e.dwmc",pageParam.getUnitName() );
        }
        if(StringUtils.isNotBlank(pageParam.getOrgName())){
            queryWrapper.like("d.org_name",pageParam.getOrgName() );
        }
        Page<RpWarnBiweeklyReport> p =new Page<>(pageParam.getCurrent(),pageParam.getSize());
        IPage<Map<String,Object>> page = rpWarnBiweeklyReportMapper.selectMyMapsPage(p,queryWrapper);
        return page;
    }
}
