/*
 * 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.fsstoragesubsidysettle.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.NumberUtil;
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.rotationPlan.info.modular.rpWarnThreshold.mapper.RpWarnThresholdMapper;
import io.swagger.annotations.ApiModelProperty;
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.fsstoragesubsidysettle.entity.FsStorageSubsidySettle;
import com.unis.financialSupervision.modular.fsstoragesubsidysettle.mapper.FsStorageSubsidySettleMapper;
import com.unis.financialSupervision.modular.fsstoragesubsidysettle.param.FsStorageSubsidySettleAddParam;
import com.unis.financialSupervision.modular.fsstoragesubsidysettle.param.FsStorageSubsidySettleEditParam;
import com.unis.financialSupervision.modular.fsstoragesubsidysettle.param.FsStorageSubsidySettleIdParam;
import com.unis.financialSupervision.modular.fsstoragesubsidysettle.param.FsStorageSubsidySettlePageParam;
import com.unis.financialSupervision.modular.fsstoragesubsidysettle.service.FsStorageSubsidySettleService;

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

/**
 * 财务监管-保管费用粮油补贴清算表Service接口实现类
 *
 * @author ZeroLiYi
 * @date  2024/06/27 09:28
 **/
@Service
public class FsStorageSubsidySettleServiceImpl extends ServiceImpl<FsStorageSubsidySettleMapper, FsStorageSubsidySettle> implements FsStorageSubsidySettleService {

    @Resource
    private FsStorageSubsidySettleMapper fsStorageSubsidySettleMapper;

    @Resource
    private RpWarnThresholdMapper rpWarnThresholdMapper;

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(FsStorageSubsidySettleAddParam fsStorageSubsidySettleAddParam) {
        FsStorageSubsidySettle fsStorageSubsidySettle = BeanUtil.toBean(fsStorageSubsidySettleAddParam, FsStorageSubsidySettle.class);
        this.save(fsStorageSubsidySettle);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(FsStorageSubsidySettleEditParam fsStorageSubsidySettleEditParam) {
        FsStorageSubsidySettle fsStorageSubsidySettle = this.queryEntity(fsStorageSubsidySettleEditParam.getId());
        BeanUtil.copyProperties(fsStorageSubsidySettleEditParam, fsStorageSubsidySettle);
        this.updateById(fsStorageSubsidySettle);
    }

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

    @Override
    public FsStorageSubsidySettle detail(FsStorageSubsidySettleIdParam fsStorageSubsidySettleIdParam) {
        return this.queryEntity(fsStorageSubsidySettleIdParam.getId());
    }

    @Override
    public FsStorageSubsidySettle queryEntity(String id) {
        FsStorageSubsidySettle fsStorageSubsidySettle = this.getById(id);
        if(ObjectUtil.isEmpty(fsStorageSubsidySettle)) {
            throw new CommonException("财务监管-保管费用粮油补贴清算表不存在，id值为：{}", id);
        }
        return fsStorageSubsidySettle;
    }

    /**
     * 定时添加保管费用补贴清算表
     */
    @Override
    public void addFsStorageSubsidySettle() {
        int year = LocalDate.now().getYear();

        LocalDate today = LocalDate.now();

        // 获取当前月份
        int ys = today.getMonthValue();
        //查询data_kcgl_kcyjd_default单位

        List<Map<String, Object>> listOrg = fsStorageSubsidySettleMapper.selectOrgInfo();

        for (int i = 0; i < listOrg.size(); i++) {
            Map<String, Object> mapOrg = listOrg.get(i);
            String orgId = mapOrg.getOrDefault("orgId", "").toString();

            /**
             * 原粮
             */
            FsStorageSubsidySettle fsStorageSubsidySettle = new FsStorageSubsidySettle();

            BigDecimal averageRawGrainInventoryEmpty = new BigDecimal(0.0);/** 储备粮-原粮平均库存数量-平均正常轮空期内轮空数量 */
            BigDecimal averageRawGrainInventory = new BigDecimal(0.00);    /** 储备粮-原粮平均库存数量-小计 */
            BigDecimal averageRawGrainInventoryPhysical = new BigDecimal(0.0);/** 储备粮-原粮平均库存数量-平均月末实物库存 */
            List<Map<String, Object>> listyy = fsStorageSubsidySettleMapper.getOrgAndKcSum(year,orgId);
            for (int j = 0; j < listyy.size(); j++) {
                Map<String, Object> map = listyy.get(j);

                // 获取 qmkc 的值，如果没有则默认为 0.0
                BigDecimal qmkc = NumberUtil.toBigDecimal(map.getOrDefault("qmkc", "0.0").toString());

                // 获取 ys 的值，如果没有则默认为 1（避免除以零）
                //int ys = Integer.parseInt(map.getOrDefault("ys", "1").toString());

                // 计算平均库存，如果 ys 不为零则进行除法运算
                if (ys != 0) {
                    averageRawGrainInventoryPhysical = qmkc.divide(BigDecimal.valueOf(ys), 2, BigDecimal.ROUND_HALF_UP);
                }

                fsStorageSubsidySettle.setAverageInventory(averageRawGrainInventoryPhysical); //平均月末实物库存

                //根据单位 和 日期 查询架空期
                Map<String, Object> staetAndEnd = fsStorageSubsidySettleMapper.getStaetAndEnd(orgId, year);
                LocalDateTime startTime = (LocalDateTime) map.getOrDefault("rotationStart", LocalDateTime.now()); //开始时间
                LocalDateTime endTime = (LocalDateTime) map.getOrDefault("rotationEnd", LocalDateTime.now()); //截至时间
                // 获取 quantity 的值，如果没有则默认为 0.0
                BigDecimal quantity = NumberUtil.toBigDecimal(map.getOrDefault("quantity", "0.0").toString());

                if (ys != 0) {
                    averageRawGrainInventoryEmpty = quantity.divide(BigDecimal.valueOf(ys), 2, BigDecimal.ROUND_HALF_UP);
                }
                fsStorageSubsidySettle.setAverageRawGrainInventoryEmpty(averageRawGrainInventoryEmpty);//平均正常轮空期内轮空数量
                averageRawGrainInventory = averageRawGrainInventoryPhysical.add(averageRawGrainInventoryEmpty);
                averageRawGrainInventory = averageRawGrainInventory.multiply(new BigDecimal("0.2"));
                fsStorageSubsidySettle.setAverageRawGrainInventory(averageRawGrainInventory);//(1)
            }



            /**
             * 成品粮
             *
             */
            BigDecimal averageProcessedGrainInventoryEmpty = new BigDecimal(0.0); /** 储备粮-成品粮平均库存数量-平均正常轮空期内轮空数量 */
            //根据年度和orgId 查询 -成品粮购销计划
            List<Map<String, Object>> list1 = rpWarnThresholdMapper.getGopsPlans(year, orgId);
            BigDecimal sjlcsl = new BigDecimal(0.0);
            BigDecimal sjsysl = new BigDecimal(0.0);
            for (int j1 = 0; j1 < list1.size(); j1++) {
                Map<String, Object> map1 = list1.get(j1);
                LocalDateTime firstTime = (LocalDateTime) map1.getOrDefault("startTime", LocalDateTime.now()); //第一车出库时间
                LocalDateTime firstDayOfNextMonth = firstTime.plusMonths(1).withDayOfMonth(1);
                LocalDateTime futureDate = firstDayOfNextMonth.plusMonths(4);
                LocalDateTime endTime = (LocalDateTime) map1.get("endTime");
                if (endTime != null && endTime.isBefore(futureDate)) {
                    BigDecimal wcsl = (BigDecimal) map1.getOrDefault("wcsl", BigDecimal.ZERO);
                    sjlcsl = sjlcsl.add(wcsl);
                    BigDecimal sysl = (BigDecimal) map1.getOrDefault("sysl", BigDecimal.ZERO);
                    sjsysl = sjsysl.add(sysl);
                }

            }
            if (ys != 0) {
                averageProcessedGrainInventoryEmpty = sjlcsl.divide(BigDecimal.valueOf(ys), 2, BigDecimal.ROUND_HALF_UP);
            }
            fsStorageSubsidySettle.setAverageProcessedGrainInventoryEmpty(averageProcessedGrainInventoryEmpty);/** 储备粮-成品粮平均库存数量-平均正常轮空期内轮空数量 */

            BigDecimal averageProcessedGrainInventoryPhysical = new BigDecimal(0.0); /** 储备粮-成品粮平均库存数量-平均月末实物库存 */
            if (ys != 0) {
                averageProcessedGrainInventoryPhysical = sjsysl.divide(BigDecimal.valueOf(ys), 2, BigDecimal.ROUND_HALF_UP);
            }
            fsStorageSubsidySettle.setAverageProcessedGrainInventoryPhysical(averageProcessedGrainInventoryPhysical);/** 储备粮-成品粮平均库存数量-平均月末实物库存 */

            BigDecimal averageProcessedGrainInventory = new BigDecimal(0.0);//(2)  /** 储备粮-成品粮平均库存数量-小计 */


            BigDecimal averageInventory = new BigDecimal(0.0);/** 储备粮平均库存数量 */
            averageInventory = averageRawGrainInventory.add(averageProcessedGrainInventoryEmpty);
            fsStorageSubsidySettle.setAverageOilInventory(averageInventory);//(1)+(2)

            /**
             * 保管费用补贴
             */
            BigDecimal storageSubsidyStandardRawGrain = new BigDecimal(0.0);//(1) /** 储备粮-原粮保管费用补贴（标准：0.12元/公斤）应拨数 */
            storageSubsidyStandardRawGrain = averageRawGrainInventory.multiply(new BigDecimal("0.12"));//单位：万元
            fsStorageSubsidySettle.setStorageSubsidyRawGrain(storageSubsidyStandardRawGrain);

            BigDecimal storageSubsidyProcessedGrain = new BigDecimal(0.0);/** 储备粮-成品粮保管费用补贴（标准：0.20元/公斤）应拨数 */
            storageSubsidyProcessedGrain = averageProcessedGrainInventory.multiply(new BigDecimal("0.20"));//单位：万元
            fsStorageSubsidySettle.setStorageSubsidyProcessedGrain(storageSubsidyProcessedGrain);

            BigDecimal storageSubsidyRawGrain = new BigDecimal(0.0);//(3)+(4) /** 储备粮-原粮保管费用补贴应拨数 */

            storageSubsidyRawGrain = storageSubsidyStandardRawGrain.add(storageSubsidyProcessedGrain);
            fsStorageSubsidySettle.setStorageSubsidyRawGrain(storageSubsidyRawGrain);
            /**
             * 储备油
             */
            BigDecimal averageOilInventoryPhysical = new BigDecimal(0.0);/** 储备油-储油平均库存数量-平均月末实物库存 */
            BigDecimal averageOilInventoryEmpty = new BigDecimal(0.0);/** 储备油-储油平均库存数量-平均正常轮空期内轮空数量 */
            BigDecimal averageOilInventory = new BigDecimal(0.0);/** 储备油-储油平均库存数量-小计 */
            List<Map<String, Object>> list2 = fsStorageSubsidySettleMapper.getOrgAndYlKcSum(year, orgId);
            for (int j2 = 0; j2< list2.size(); j2++) {
                Map<String, Object> mapy = listyy.get(j2);
                // 获取 qmkc 的值，如果没有则默认为 0.0
                BigDecimal qmkc = NumberUtil.toBigDecimal(mapy.getOrDefault("qmkc", "0.0").toString());

                // 获取 ys 的值，如果没有则默认为 1（避免除以零）
                //int ys = Integer.parseInt(map.getOrDefault("ys", "1").toString());

                // 计算平均库存，如果 ys 不为零则进行除法运算
                if (ys != 0) {
                    averageOilInventoryPhysical = qmkc.divide(BigDecimal.valueOf(ys), 2, BigDecimal.ROUND_HALF_UP);
                }

                fsStorageSubsidySettle.setAverageOilInventoryPhysical(averageOilInventoryPhysical); //平均月末实物库存

                //根据单位 和 日期 查询架空期
                Map<String, Object> staetAndEnd = fsStorageSubsidySettleMapper.getStaetAndEnd(orgId, year);
                LocalDateTime startTime = (LocalDateTime) mapy.getOrDefault("rotationStart", LocalDateTime.now()); //开始时间
                LocalDateTime endTime = (LocalDateTime) mapy.getOrDefault("rotationEnd", LocalDateTime.now()); //截至时间
                // 获取 quantity 的值，如果没有则默认为 0.0
                BigDecimal quantity = NumberUtil.toBigDecimal(mapy.getOrDefault("quantity", "0.0").toString());

                if (ys != 0) {
                    averageOilInventoryEmpty = quantity.divide(BigDecimal.valueOf(ys), 2, BigDecimal.ROUND_HALF_UP);
                }
                fsStorageSubsidySettle.setAverageOilInventoryEmpty(averageOilInventoryEmpty);//平均正常轮空期内轮空数量
                averageOilInventory = averageOilInventoryPhysical.add(averageOilInventoryEmpty);

                BigDecimal storageSubsidyOil = new BigDecimal(0.0);/** 储备油-油料保管费用补贴（标准：0.40元/公斤）应拨数 */
                storageSubsidyOil = averageOilInventory.multiply(new BigDecimal("0.2"));
                fsStorageSubsidySettle.setStorageSubsidyOil(storageSubsidyOil);//(5)

            }
            this.save(fsStorageSubsidySettle);
        }

    }
}
