/*
 * 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.projectManagement.modular.pmStorageInvest.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.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.projectManagement.modular.pmStorageInvestAsset.entity.PmStorageInvestAsset;
import com.unis.projectManagement.modular.pmStorageInvestAsset.mapper.PmStorageInvestAssetMapper;
import com.unis.projectManagement.modular.pmStorageInvestAsset.service.PmStorageInvestAssetService;
import com.unis.projectManagement.modular.pmStorageInvestDistribution.entity.PmStorageInvestDistribution;
import com.unis.projectManagement.modular.pmStorageInvestDistribution.mapper.PmStorageInvestDistributionMapper;
import com.unis.projectManagement.modular.pmStorageInvestDistribution.service.PmStorageInvestDistributionService;
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.projectManagement.modular.pmStorageInvest.entity.PmStorageInvest;
import com.unis.projectManagement.modular.pmStorageInvest.mapper.PmStorageInvestMapper;
import com.unis.projectManagement.modular.pmStorageInvest.param.PmStorageInvestAddParam;
import com.unis.projectManagement.modular.pmStorageInvest.param.PmStorageInvestEditParam;
import com.unis.projectManagement.modular.pmStorageInvest.param.PmStorageInvestIdParam;
import com.unis.projectManagement.modular.pmStorageInvest.param.PmStorageInvestPageParam;
import com.unis.projectManagement.modular.pmStorageInvest.service.PmStorageInvestService;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 仓储设施投资表Service接口实现类
 *
 * @author hjc
 * @date  2024/05/29 19:17
 **/
@Service
public class PmStorageInvestServiceImpl extends ServiceImpl<PmStorageInvestMapper, PmStorageInvest> implements PmStorageInvestService {

    private static Map<String, Integer> sequenceNumbers = new HashMap<>(); // 映射：仓房代码到顺序号
    private static final int MAX_SEQUENCE_NUMBER = 1000; // 顺序号的最大值
    private static final String DATE_FORMAT = "yyyyMMdd";
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern(DATE_FORMAT);

    @Autowired
    private PmStorageInvestAssetMapper pmStorageInvestAssetMapper;

    @Autowired
    private PmStorageInvestDistributionMapper pmStorageInvestDistributionMapper;

    @Override
    public Page<PmStorageInvest> page(PmStorageInvestPageParam pmStorageInvestPageParam) {
        QueryWrapper<PmStorageInvest> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(pmStorageInvestPageParam.getProjectName())){
            queryWrapper.like("project_name",pmStorageInvestPageParam.getProjectName());
        }
        if(ObjectUtil.isAllNotEmpty(pmStorageInvestPageParam.getSortField(), pmStorageInvestPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(pmStorageInvestPageParam.getSortOrder());
            queryWrapper.orderBy(true, pmStorageInvestPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(pmStorageInvestPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(PmStorageInvest::getCreateTime);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(PmStorageInvestAddParam pmStorageInvestAddParam) {

        PmStorageInvest pmStorageInvest = BeanUtil.toBean(pmStorageInvestAddParam, PmStorageInvest.class);


        sequenceNumbers.putIfAbsent("CCSSTZ", 0);
        // 增加当前货位的顺序号，并在达到最大值时重置为0
        int sequenceNumber = (sequenceNumbers.get("CCSSTZ") + 1) % MAX_SEQUENCE_NUMBER;
        sequenceNumbers.put("CCSSTZ", sequenceNumber);
        // 确保顺序号是4位数
        String formattedSequenceNumber = String.format("%04d", sequenceNumber);
        // 获取当前日期并格式化为yyyyMMdd
        String currentDate = LocalDate.now().format(DATE_FORMATTER);
        // 合并、日期和顺序号
        String projectCode = "CCSSTZ" + currentDate + formattedSequenceNumber;

        pmStorageInvest.setProjectCode(projectCode);

        this.save(pmStorageInvest);

        //添加资产情况数据
        List<PmStorageInvestAsset> pmStorageInvestAssetList = pmStorageInvestAddParam.getPmStorageInvestAssetList();
        for (PmStorageInvestAsset pmStorageInvestAsset : pmStorageInvestAssetList) {
            pmStorageInvestAsset.setPmStorageInvestId(pmStorageInvest.getId());
            pmStorageInvestAssetMapper.insert(pmStorageInvestAsset);

        }

        //添加分布情况
        List<PmStorageInvestDistribution> pmStorageInvestDistributionList = pmStorageInvestAddParam.getPmStorageInvestDistributionList();
        for (PmStorageInvestDistribution pmStorageInvestDistribution : pmStorageInvestDistributionList) {
            pmStorageInvestDistribution.setPmStorageInvestId(pmStorageInvest.getId());
            pmStorageInvestDistributionMapper.insert(pmStorageInvestDistribution);
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(PmStorageInvestEditParam pmStorageInvestEditParam) {

        PmStorageInvest pmStorageInvest = this.queryEntity(pmStorageInvestEditParam.getId());
        BeanUtil.copyProperties(pmStorageInvestEditParam, pmStorageInvest);
        this.updateById(pmStorageInvest);

        //将之前的资产情况和分布情况删除 在进行添加
        pmStorageInvestAssetMapper.delete(Wrappers.lambdaQuery(PmStorageInvestAsset.class)
                .in(PmStorageInvestAsset::getPmStorageInvestId,pmStorageInvest.getId()));
        pmStorageInvestDistributionMapper.delete(Wrappers.lambdaQuery(PmStorageInvestDistribution.class)
                .in(PmStorageInvestDistribution::getPmStorageInvestId,pmStorageInvest.getId()));


        //添加资产情况数据
        List<PmStorageInvestAsset> pmStorageInvestAssetList = pmStorageInvestEditParam.getPmStorageInvestAssetList();
        for (PmStorageInvestAsset pmStorageInvestAsset : pmStorageInvestAssetList) {
            pmStorageInvestAsset.setPmStorageInvestId(pmStorageInvest.getId());
            pmStorageInvestAssetMapper.insert(pmStorageInvestAsset);

        }

        //添加分布情况
        List<PmStorageInvestDistribution> pmStorageInvestDistributionList = pmStorageInvestEditParam.getPmStorageInvestDistributionList();
        for (PmStorageInvestDistribution pmStorageInvestDistribution : pmStorageInvestDistributionList) {
            pmStorageInvestDistribution.setPmStorageInvestId(pmStorageInvest.getId());
            pmStorageInvestDistributionMapper.insert(pmStorageInvestDistribution);
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<PmStorageInvestIdParam> pmStorageInvestIdParamList) {

        PmStorageInvest pmStorageInvest = this.queryEntity(pmStorageInvestIdParamList.get(0).getId());

        //将资产情况和分布情况删除
        pmStorageInvestAssetMapper.delete(Wrappers.lambdaQuery(PmStorageInvestAsset.class)
                .in(PmStorageInvestAsset::getPmStorageInvestId,pmStorageInvest.getId()));
        pmStorageInvestDistributionMapper.delete(Wrappers.lambdaQuery(PmStorageInvestDistribution.class)
                .in(PmStorageInvestDistribution::getPmStorageInvestId,pmStorageInvest.getId()));

        // 执行删除
        this.removeByIds(CollStreamUtil.toList(pmStorageInvestIdParamList, PmStorageInvestIdParam::getId));


    }

    @Override
    public JSONObject detail(PmStorageInvestIdParam pmStorageInvestIdParam) {

        //获取仓储设置投资数据
        JSONObject jsonObject = new JSONObject();
        PmStorageInvest pmStorageInvest = this.queryEntity(pmStorageInvestIdParam.getId());
        jsonObject.put("pmStorageInvest",pmStorageInvest);

        //资产情况数据
        List<PmStorageInvestAsset> pmStorageInvestAssetList = pmStorageInvestAssetMapper.selectList(Wrappers.lambdaQuery(PmStorageInvestAsset.class)
                .eq(PmStorageInvestAsset::getPmStorageInvestId, pmStorageInvest.getId()));
        jsonObject.put("pmStorageInvestAssetList",pmStorageInvestAssetList);

        //获取分布情况数据
        List<PmStorageInvestDistribution> pmStorageInvestDistributionList = pmStorageInvestDistributionMapper.selectList(Wrappers.lambdaQuery(PmStorageInvestDistribution.class)
                .eq(PmStorageInvestDistribution::getPmStorageInvestId, pmStorageInvest.getId()));
        jsonObject.put("pmStorageInvestDistributionList",pmStorageInvestDistributionList);


        return jsonObject;
    }

    @Override
    public PmStorageInvest queryEntity(String id) {
        PmStorageInvest pmStorageInvest = this.getById(id);
        if(ObjectUtil.isEmpty(pmStorageInvest)) {
            throw new CommonException("仓储设施投资表不存在，id值为：{}", id);
        }
        return pmStorageInvest;
    }
}
