/*
 * 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.fsunrotatedgrainstorage.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.fsunrotatedgrainstorage.param.*;
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.fsunrotatedgrainstorage.entity.BizFsUnrotatedGrainStorage;
import com.unis.financialSupervision.modular.fsunrotatedgrainstorage.mapper.BizFsUnrotatedGrainStorageMapper;
import com.unis.financialSupervision.modular.fsunrotatedgrainstorage.service.BizFsUnrotatedGrainStorageService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Year;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 财务监管-（未轮换）分品种分库存情况表Service接口实现类
 *
 * @author shine
 * @date  2024/06/26 11:51
 **/
@Service
public class BizFsUnrotatedGrainStorageServiceImpl extends ServiceImpl<BizFsUnrotatedGrainStorageMapper, BizFsUnrotatedGrainStorage> implements BizFsUnrotatedGrainStorageService {

    @Resource
    private BizFsUnrotatedGrainStorageMapper bizFsUnrotatedGrainStorageMapper;

    @Resource
    private OrgInfoMapper orgInfoMapper;

    @Resource
    private BasicEnumMapper basicEnumMapper;

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

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizFsUnrotatedGrainStorageAddParam bizFsUnrotatedGrainStorageAddParam) {
        BizFsUnrotatedGrainStorage bizFsUnrotatedGrainStorage = BeanUtil.toBean(bizFsUnrotatedGrainStorageAddParam, BizFsUnrotatedGrainStorage.class);
        this.save(bizFsUnrotatedGrainStorage);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizFsUnrotatedGrainStorageEditParam bizFsUnrotatedGrainStorageEditParam) {
        BizFsUnrotatedGrainStorage bizFsUnrotatedGrainStorage = this.queryEntity(bizFsUnrotatedGrainStorageEditParam.getId());
        BeanUtil.copyProperties(bizFsUnrotatedGrainStorageEditParam, bizFsUnrotatedGrainStorage);
        this.updateById(bizFsUnrotatedGrainStorage);
    }

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

    @Override
    public BizFsUnrotatedGrainStorage detail(BizFsUnrotatedGrainStorageIdParam bizFsUnrotatedGrainStorageIdParam) {
        return this.queryEntity(bizFsUnrotatedGrainStorageIdParam.getId());
    }

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

    @Override
    public List<BizFsUnrotatedGrainStorage> getList(BizFsUnrotatedGrainStorageListParam bizFsUnrotatedGrainStorageListParam) {

        QueryWrapper<BizFsUnrotatedGrainStorage> queryWrapper = new QueryWrapper<>();

        if(ObjectUtil.isNotEmpty(bizFsUnrotatedGrainStorageListParam.getOrgId())) {
            queryWrapper.lambda().eq(BizFsUnrotatedGrainStorage::getOrgId, bizFsUnrotatedGrainStorageListParam.getOrgId());
        }

        if(ObjectUtil.isNotEmpty(bizFsUnrotatedGrainStorageListParam.getPlanYear())) {
            queryWrapper.lambda().eq(BizFsUnrotatedGrainStorage::getPlanYear, bizFsUnrotatedGrainStorageListParam.getPlanYear());
        }

        queryWrapper.lambda().orderByAsc(BizFsUnrotatedGrainStorage::getOrgId);

        List<BizFsUnrotatedGrainStorage> list = this.list(queryWrapper);
        for(BizFsUnrotatedGrainStorage bizFsUnrotatedGrainStorage:list){
           OrgInfo orgInfo =  orgInfoMapper.selectById(bizFsUnrotatedGrainStorage.getOrgId());
            bizFsUnrotatedGrainStorage.setOrgName(orgInfo.getOrgName());

            BasicEnum basicEnum = basicEnumMapper.selectById(bizFsUnrotatedGrainStorage.getGrainTypeOne());
            bizFsUnrotatedGrainStorage.setPzOneName(basicEnum.getEnumname());

            BasicEnum basicEnum1 = basicEnumMapper.selectById(bizFsUnrotatedGrainStorage.getGrainTypeTwo());
            bizFsUnrotatedGrainStorage.setPzTwoName(basicEnum1.getEnumname());

        }
        return list;
    }

    /**
     * 定时任务增加/修改数据到表里
     */
    @Override
    public void notRotatedData() {

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

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

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

        /**
         * 获取轮换计划没有下发的库区 当年的
         */
        List<OrgInfo> orgList = bizFsUnrotatedGrainStorageMapper.getOrgInfo(year);

        for(OrgInfo orgInfo:orgList){

            /**
             * 获取每个库区 当前年的储备规模数据
             * 粮食性质为  省(自治区、直辖市)级地方储备粮 --6877
             *     ■ 只添加或更新当前年的数据。
             *     ■ 已过去的年不用更新
             *
             */
            List<Map<String,Object>> cbgmList = bizFsUnrotatedGrainStorageMapper.getCbgmData(orgInfo.getOrgId());
            for(Map<String,Object> map:cbgmList){
                BizFsUnrotatedGrainStorage bizFsUnrotatedGrainStorage = new BizFsUnrotatedGrainStorage();

                bizFsUnrotatedGrainStorage.setOrgId(orgInfo.getOrgId());
                bizFsUnrotatedGrainStorage.setPlanYear(year);
                bizFsUnrotatedGrainStorage.setCreateTime(new Date());
                Integer pz = 0;
                BigDecimal cbgmsl = new BigDecimal(0);
                if(ObjectUtil.isNotNull(map) && ObjectUtil.isNotEmpty(map)){
                     pz = (Integer) map.get("pz");
                     cbgmsl = (BigDecimal) map.get("cbgmsl");
                }

                /**
                 * ********************品种 对应可能有问题
                 */
                BasicEnum basicEnum = basicEnumMapper.selectById(pz);
                BasicEnum basicEnum1 = basicEnumMapper.selectById(basicEnum.getParentid());
                bizFsUnrotatedGrainStorage.setGrainTypeOne(basicEnum1.getEnumid());
                bizFsUnrotatedGrainStorage.setGrainTypeTwo(pz);
                bizFsUnrotatedGrainStorage.setAverageStorageScale(cbgmsl);
                this.save(bizFsUnrotatedGrainStorage);
            }
        }
    }
}
