/*
 * 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.fsrotatedgrainstorage.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.enumInfo.mapper.BasicEnumMapper;
import com.unis.basic.info.modular.orgInfo.entity.OrgInfo;
import com.unis.basic.info.modular.orgInfo.mapper.OrgInfoMapper;
import com.unis.financialSupervision.modular.fsrotatedgrainstorage.param.*;
import com.unis.financialSupervision.modular.fsunrotatedgrainstorage.entity.BizFsUnrotatedGrainStorage;
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.fsrotatedgrainstorage.entity.BizFsRotatedGrainStorage;
import com.unis.financialSupervision.modular.fsrotatedgrainstorage.mapper.BizFsRotatedGrainStorageMapper;
import com.unis.financialSupervision.modular.fsrotatedgrainstorage.service.BizFsRotatedGrainStorageService;

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 10:36
 **/
@Service
public class BizFsRotatedGrainStorageServiceImpl extends ServiceImpl<BizFsRotatedGrainStorageMapper, BizFsRotatedGrainStorage> implements BizFsRotatedGrainStorageService {

    @Resource
    private BizFsRotatedGrainStorageMapper bizFsRotatedGrainStorageMapper;

    @Resource
    private OrgInfoMapper orgInfoMapper;

    @Resource
    private BasicEnumMapper basicEnumMapper;

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFsRotatedGrainStorageAddParam bizFsRotatedGrainStorageAddParam) {
        BizFsRotatedGrainStorage bizFsRotatedGrainStorage = BeanUtil.toBean(bizFsRotatedGrainStorageAddParam, BizFsRotatedGrainStorage.class);
        this.save(bizFsRotatedGrainStorage);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFsRotatedGrainStorageEditParam bizFsRotatedGrainStorageEditParam) {
        BizFsRotatedGrainStorage bizFsRotatedGrainStorage = this.queryEntity(bizFsRotatedGrainStorageEditParam.getId());
        BeanUtil.copyProperties(bizFsRotatedGrainStorageEditParam, bizFsRotatedGrainStorage);
        this.updateById(bizFsRotatedGrainStorage);
    }

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

    @Override
    public BizFsRotatedGrainStorage detail(BizFsRotatedGrainStorageIdParam bizFsRotatedGrainStorageIdParam) {
        return this.queryEntity(bizFsRotatedGrainStorageIdParam.getId());
    }

    @Override
    public BizFsRotatedGrainStorage queryEntity(String id) {
        BizFsRotatedGrainStorage bizFsRotatedGrainStorage = this.getById(id);
        if(ObjectUtil.isEmpty(bizFsRotatedGrainStorage)) {
            throw new CommonException("财务监管-轮换分品种分库存情况表不存在，id值为：{}", id);
        }
        return bizFsRotatedGrainStorage;
    }

    @Override
    public List<BizFsRotatedGrainStorage> getList(BizFsRotatedGrainStorageListParam bizFsRotatedGrainStorageListParam) {
        QueryWrapper<BizFsRotatedGrainStorage> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizFsRotatedGrainStorageListParam.getOrgId())) {
            queryWrapper.lambda().eq(BizFsRotatedGrainStorage::getOrgId, bizFsRotatedGrainStorageListParam.getOrgId());
        }
        if(ObjectUtil.isNotEmpty(bizFsRotatedGrainStorageListParam.getYear())) {
            queryWrapper.lambda().eq(BizFsRotatedGrainStorage::getPlanYear, bizFsRotatedGrainStorageListParam.getYear());
        }
        queryWrapper.lambda().orderByAsc(BizFsRotatedGrainStorage::getId);
        List<BizFsRotatedGrainStorage> list = this.list(queryWrapper);
        for(BizFsRotatedGrainStorage bizFsRotatedGrainStorage:list){
            OrgInfo orgInfo =  orgInfoMapper.selectById(bizFsRotatedGrainStorage.getOrgId());
            bizFsRotatedGrainStorage.setOrgName(orgInfo.getOrgName());

            BasicEnum basicEnum = basicEnumMapper.selectById(bizFsRotatedGrainStorage.getGrainVarietyId());
            bizFsRotatedGrainStorage.setPzName(basicEnum.getEnumname());
        }
        return list;
    }

    @Override
    public List<OrgInfo> getRpOrgInfoList() {
        //当前年
        LocalDate localDate = LocalDate.now();
        int year = localDate.getYear();
        return bizFsRotatedGrainStorageMapper.getRpOrgInfo(year);
    }


    @Override
    public void rotatedData() {

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

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

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

        /**
         * 查询当年轮换下发的库区
         */
        List<OrgInfo> orgList = bizFsRotatedGrainStorageMapper.getRpOrgInfo(year);
        for(OrgInfo orgInfo:orgList){

            Integer orgId = orgInfo.getOrgId();
            /**
             * 查询 库存月结单 品种
             */
            Map<String,Object> tjMap = new HashMap<>();
            tjMap.put("year",year);
            tjMap.put("orgId",orgId);

            List<Map<String,Object>> pzList = bizFsRotatedGrainStorageMapper.getKcyjdPz(tjMap);
            if(pzList.size()>0){
                for(Map<String,Object> map:pzList){
                    String pz = (String)map.get("pz");
                    /**
                     * 查询月末实物库存
                     */
                    tjMap.put("pz",pz);
                    List<Map<String,Object>> ymswkcList = bizFsRotatedGrainStorageMapper.getYmswkc(tjMap);

                    for(Map<String,Object> ymswkcMap:ymswkcList){

                        BizFsRotatedGrainStorage bizFsRotatedGrainStorage =  new BizFsRotatedGrainStorage();
                        bizFsRotatedGrainStorage.setOrgId(orgId);
                        bizFsRotatedGrainStorage.setPlanYear(year);
                        int yf = 0;
                        Double qmkc = 0.0;
                        if(null != ymswkcMap.get("qmkc") && null != ymswkcMap.get("yf")){
                            qmkc = (Double)ymswkcMap.get("qmkc");
                            yf = (Integer)ymswkcMap.get("yf");
                        }

                        bizFsRotatedGrainStorage.setMonth(yf);
                        bizFsRotatedGrainStorage.setGrainVarietyId(Integer.valueOf(pz));
                        bizFsRotatedGrainStorage.setPhysicalInventory(new BigDecimal(qmkc));

                        /**
                         * 查询储备规模
                         */
                        tjMap.put("yf",yf);
                        List<Map<String,Object>> cbgmList = bizFsRotatedGrainStorageMapper.getCbgm(tjMap);
                        if(cbgmList.size()>0 && null != cbgmList.get(0)){
                            BigDecimal cbgmsl = (BigDecimal) cbgmList.get(0).get("cbgmsl");
                            bizFsRotatedGrainStorage.setReserveScale(cbgmsl);
                            BigDecimal physicalInventoryRate = new BigDecimal(qmkc).divide(cbgmsl).multiply(new BigDecimal(100));
                            bizFsRotatedGrainStorage.setPhysicalInventoryRate(physicalInventoryRate);
                        }else{
                            bizFsRotatedGrainStorage.setReserveScale(new BigDecimal(0));
                            bizFsRotatedGrainStorage.setPhysicalInventoryRate(new BigDecimal(0));

                        }

                        /**
                         * 查询正常轮空期内轮空数量
                         */
                        //查询架空期的时间  ● 正常轮空期内轮空数量=在架空期内的轮出数量
                        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);
                                    //查询数量  正常轮空期内轮空数量
                                    List<Map<String,Object>> zclkqslList = bizFsRotatedGrainStorageMapper.getZclkqsl(tjMap);
                                    if(zclkqslList.size()>0 && null != zclkqslList.get(0)){
                                        BigDecimal normalEmptyQuantity = (BigDecimal)zclkqslList.get(0).get("zclkqnlksl");
                                        bizFsRotatedGrainStorage.setNormalEmptyQuantity(normalEmptyQuantity);
                                    }else{
                                        bizFsRotatedGrainStorage.setNormalEmptyQuantity(new BigDecimal(0));
                                    }

                                    //超轮空期数量
                                    List<Map<String,Object>> clkqsllList = bizFsRotatedGrainStorageMapper.getClkqsl(tjMap);
                                    if(clkqsllList.size()>0 && null != zclkqslList.get(0)){
                                        BigDecimal overdueEmptyQuantity = (BigDecimal)zclkqslList.get(0).get("clkqsl");
                                        bizFsRotatedGrainStorage.setOverdueEmptyQuantity(overdueEmptyQuantity);
                                    }else{
                                        bizFsRotatedGrainStorage.setOverdueEmptyQuantity(new BigDecimal(0));
                                    }
                                }else{
                                    bizFsRotatedGrainStorage.setOverdueEmptyQuantity(new BigDecimal(0));
                                    bizFsRotatedGrainStorage.setNormalEmptyQuantity(new BigDecimal(0));
                                }
                            }
                        }else{
                            bizFsRotatedGrainStorage.setOverdueEmptyQuantity(new BigDecimal(0));
                            bizFsRotatedGrainStorage.setNormalEmptyQuantity(new BigDecimal(0));
                        }
                        this.save(bizFsRotatedGrainStorage);
                    }

                }
            }
        }

    }
}
