/*
 * 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.financialSupervision.modular.fsgrainoilstoragesummary.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.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.basic.info.modular.enumInfo.entity.BasicEnum;
import com.unis.basic.info.modular.orgInfo.entity.OrgInfo;
import com.unis.basic.info.modular.orgInfo.mapper.OrgInfoMapper;
import com.unis.basic.info.modular.orgInfo.service.impl.OrgInfoServiceImpl;
import com.unis.financialSupervision.modular.fsgrainoilstoragesummary.param.*;
import com.unis.financialSupervision.modular.fsrotatedgrainstorage.entity.BizFsRotatedGrainStorage;
import com.unis.financialSupervision.modular.fsrotatedgrainstorage.mapper.BizFsRotatedGrainStorageMapper;
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.financialSupervision.modular.fsgrainoilstoragesummary.entity.BizFsGrainOilStorageSummary;
import com.unis.financialSupervision.modular.fsgrainoilstoragesummary.mapper.BizFsGrainOilStorageSummaryMapper;
import com.unis.financialSupervision.modular.fsgrainoilstoragesummary.service.BizFsGrainOilStorageSummaryService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 财务监管-原粮储备粮油库存情况表（总表）Service接口实现类
 *
 * @author shine
 * @date  2024/06/27 20:33
 **/
@Service
public class BizFsGrainOilStorageSummaryServiceImpl extends ServiceImpl<BizFsGrainOilStorageSummaryMapper, BizFsGrainOilStorageSummary> implements BizFsGrainOilStorageSummaryService {

    @Resource
    private OrgInfoServiceImpl OrgInfoServiceImpl;

    @Resource
    private BizFsGrainOilStorageSummaryMapper bizFsGrainOilStorageSummaryMapper;

    @Resource
    private BizFsRotatedGrainStorageMapper bizFsRotatedGrainStorageMapper;

    @Resource
    private OrgInfoMapper orgInfoMapper;




    @Override
    public Page<BizFsGrainOilStorageSummary> page(BizFsGrainOilStorageSummaryPageParam bizFsGrainOilStorageSummaryPageParam) {
        QueryWrapper<BizFsGrainOilStorageSummary> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizFsGrainOilStorageSummaryPageParam.getOrgId())) {
            queryWrapper.lambda().eq(BizFsGrainOilStorageSummary::getOrgId, bizFsGrainOilStorageSummaryPageParam.getOrgId());
        }
        if(ObjectUtil.isAllNotEmpty(bizFsGrainOilStorageSummaryPageParam.getSortField(), bizFsGrainOilStorageSummaryPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizFsGrainOilStorageSummaryPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizFsGrainOilStorageSummaryPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizFsGrainOilStorageSummaryPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizFsGrainOilStorageSummary::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFsGrainOilStorageSummaryAddParam bizFsGrainOilStorageSummaryAddParam) {
        BizFsGrainOilStorageSummary bizFsGrainOilStorageSummary = BeanUtil.toBean(bizFsGrainOilStorageSummaryAddParam, BizFsGrainOilStorageSummary.class);
        this.save(bizFsGrainOilStorageSummary);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFsGrainOilStorageSummaryEditParam bizFsGrainOilStorageSummaryEditParam) {
        BizFsGrainOilStorageSummary bizFsGrainOilStorageSummary = this.queryEntity(bizFsGrainOilStorageSummaryEditParam.getId());
        BeanUtil.copyProperties(bizFsGrainOilStorageSummaryEditParam, bizFsGrainOilStorageSummary);
        this.updateById(bizFsGrainOilStorageSummary);
    }

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

    @Override
    public BizFsGrainOilStorageSummary detail(BizFsGrainOilStorageSummaryIdParam bizFsGrainOilStorageSummaryIdParam) {
        return this.queryEntity(bizFsGrainOilStorageSummaryIdParam.getId());
    }

    @Override
    public BizFsGrainOilStorageSummary queryEntity(String id) {
        BizFsGrainOilStorageSummary bizFsGrainOilStorageSummary = this.getById(id);
        if(ObjectUtil.isEmpty(bizFsGrainOilStorageSummary)) {
            throw new CommonException("财务监管-原粮储备粮油库存情况表（总表）不存在，id值为：{}", id);
        }
        return bizFsGrainOilStorageSummary;
    }

    @Override
    public void grainOilStorageSummary() {

        //当前年
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();

        /**
         * 删除当年的数据 每天新增
         */
        QueryWrapper<BizFsGrainOilStorageSummary> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BizFsGrainOilStorageSummary::getPlanYear, year);
        List<BizFsGrainOilStorageSummary> bizFsGrainOilStorageSummaryList = this.list(queryWrapper);

        if(bizFsGrainOilStorageSummaryList.size()>0){
            this.remove(queryWrapper);
        }

        /**
         * 所有库区信息
         */
        List<OrgInfo> orgList = OrgInfoServiceImpl.getAllList();
        for(OrgInfo orgInfo:orgList){

            int orgId = orgInfo.getOrgId();

            /**
             * 1月-12月平均月储备原粮规模    1月数量10，5月数量20，平均月储备规模=（10+20）/2。
             */
            BizFsGrainOilStorageSummary bizFsGrainOilStorageSummary = new  BizFsGrainOilStorageSummary();
            bizFsGrainOilStorageSummary.setOrgId(orgId);
            bizFsGrainOilStorageSummary.setPlanYear(year);

            Map<String,Object> tjMap = new HashMap<String,Object>();
            tjMap.put("orgId",orgId);
            tjMap.put("year",year);
            List<Map<String,Object>> pjcbgmList =  bizFsGrainOilStorageSummaryMapper.getPjcbgmSl(tjMap);
            System.out.println(pjcbgmList.size()+"***********************************");
            if(pjcbgmList.size()>0 && null != pjcbgmList.get(0) && !pjcbgmList.get(0).isEmpty()){ //每个库 每年 一条数据
                    BigDecimal pjcbgmsl = (BigDecimal)pjcbgmList.get(0).get("pjcbgmsl");
                    bizFsGrainOilStorageSummary.setAverageRawGrainScale(pjcbgmsl);//平均月储备原粮规模
            }else{
                bizFsGrainOilStorageSummary.setAverageRawGrainScale(new BigDecimal(0));
            }

            /**
             * 1月-12月平均月末库存
             *     ● 按当前时间来算，如果没到月末，按当前库存。
             *     ● 示例：1月末库存10，2月末库存20，3月12号（当前时间）库存30；平均月末实物库存=（10+20+30）/3。
             */
            List<Map<String,Object>> pjymkcList =  bizFsGrainOilStorageSummaryMapper.getPjymkcsl(tjMap);
            if(pjymkcList.size()>0 && null != pjymkcList.get(0) && !pjymkcList.get(0).isEmpty()){ //每个库 每年 一条数据
                Double pjymkc = (Double)pjymkcList.get(0).get("pjymkc");
                bizFsGrainOilStorageSummary.setAverageRawGrainInventory(new BigDecimal(pjymkc)); //月末实物库存
            }else{
                bizFsGrainOilStorageSummary.setAverageRawGrainInventory(new BigDecimal(0));
            }

            /**
             * 1月-12月平均月末原粮库存情况-正常轮空期内轮空数量
             */
            //查询架空期的时间  ● 正常轮空期内轮空数量=在架空期内的轮出数量
            List<Map<String,Object>> jkqsjList = bizFsRotatedGrainStorageMapper.getJkqSj(tjMap);
            if(jkqsjList.size()>0){
                for(Map<String,Object> jkqmap:jkqsjList){
                    if(null != jkqmap.get("rotationStart") && null != jkqmap.get("rotationEnd")){
                        Date rotationStart= (Date)jkqmap.get("rotationStart");
                        Date rotationEnd= (Date)jkqmap.get("rotationEnd");
                        //System.out.println("======="+rotationStart+"***************************"+rotationEnd);
                        tjMap.put("rotationStart",rotationStart);
                        tjMap.put("rotationEnd",rotationEnd);
                        //查询数量    1月-12月平均月末原粮库存情况-正常轮空期内轮空数量
                        List<Map<String,Object>> zclkqslpjList = bizFsGrainOilStorageSummaryMapper.getZclkqslPj(tjMap);
                        if(zclkqslpjList.size()>0 && null != zclkqslpjList.get(0)){
                            BigDecimal zclkqnlkslpj = (BigDecimal)zclkqslpjList.get(0).get("zclkqnlkslpj");//正常轮空期内轮空数量
                            bizFsGrainOilStorageSummary.setAverageRawGrainEmptyNormal(zclkqnlkslpj);
                        }else{
                            bizFsGrainOilStorageSummary.setAverageRawGrainEmptyNormal(new BigDecimal(0));
                        }

                        //超轮空期数量 1月-12月平均月末原粮库存情况-超轮空期数量
                        List<Map<String,Object>> clkqslPjList = bizFsGrainOilStorageSummaryMapper.getClkqslpj(tjMap);
                        if(clkqslPjList.size()>0 && null != clkqslPjList.get(0)){
                            BigDecimal clkqslpj = (BigDecimal)clkqslPjList.get(0).get("clkqslpj"); //超轮空期数量
                            bizFsGrainOilStorageSummary.setAverageRawGrainEmptyOverdue(clkqslpj);
                        }else{
                            bizFsGrainOilStorageSummary.setAverageRawGrainEmptyOverdue(new BigDecimal(0));
                        }
                    }else{
                        bizFsGrainOilStorageSummary.setAverageRawGrainEmptyNormal(new BigDecimal(0));
                        bizFsGrainOilStorageSummary.setAverageRawGrainEmptyOverdue(new BigDecimal(0));
                    }
                }
            }else{
                bizFsGrainOilStorageSummary.setAverageRawGrainEmptyNormal(new BigDecimal(0));
                bizFsGrainOilStorageSummary.setAverageRawGrainEmptyOverdue(new BigDecimal(0));

            }

            /**
             * 库存率  实物库存/储备规模计划数 即当前库存/总库存
             */
            String kcl  = bizFsGrainOilStorageSummaryMapper.getKcl(tjMap);
            if(null != kcl){
                bizFsGrainOilStorageSummary.setRawGrainInventoryRate(new BigDecimal(kcl));
            }else{
                bizFsGrainOilStorageSummary.setRawGrainInventoryRate(new BigDecimal(0));
            }


            /**
             * ● 成品粮、油没有关联轮换计划，所以数据为0。
             */
            bizFsGrainOilStorageSummary.setAverageProcessedGrainScale(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setAverageProcessedGrainInventory(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setAverageProcessedGrainEmptyNormal(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setAverageProcessedGrainEmptyOverdue(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setProcessedGrainInventoryRate(new BigDecimal(0));

            bizFsGrainOilStorageSummary.setAverageOilScale(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setAverageOilInventory(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setAverageOilEmptyNormal(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setAverageOilEmptyOverdue(new BigDecimal(0));
            bizFsGrainOilStorageSummary.setOilInventoryRate(new BigDecimal(0));

            this.save(bizFsGrainOilStorageSummary);
        }

    }

    @Override
    public List<BizFsGrainOilStorageSummary> getList(BizFsGrainOilStorageSummaryListParam bizFsGrainOilStorageSummaryListParam) {
        QueryWrapper<BizFsGrainOilStorageSummary> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizFsGrainOilStorageSummaryListParam.getOrgId())) {
            queryWrapper.lambda().eq(BizFsGrainOilStorageSummary::getOrgId, bizFsGrainOilStorageSummaryListParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(bizFsGrainOilStorageSummaryListParam.getPlanYear())) {
            queryWrapper.lambda().eq(BizFsGrainOilStorageSummary::getPlanYear, bizFsGrainOilStorageSummaryListParam.getPlanYear());
        }
        queryWrapper.lambda().orderByAsc(BizFsGrainOilStorageSummary::getId);
        List<BizFsGrainOilStorageSummary> list = this.list(queryWrapper);
        for(BizFsGrainOilStorageSummary bizFsGrainOilStorageSummary:list){
            OrgInfo orgInfo =  orgInfoMapper.selectById(bizFsGrainOilStorageSummary.getOrgId());
            bizFsGrainOilStorageSummary.setOrgName(orgInfo.getOrgName());
        }
        return list;
    }
}
