/*
 * 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.examine.modular.neassessmentScore.service.impl;

import cn.dev33.satoken.stp.StpUtil;
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.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.examine.modular.assessmentlevel.entity.AssessmentLevel;
import com.unis.examine.modular.assessmentlevel.service.AssessmentLevelService;
import com.unis.examine.modular.neassessmentScore.entity.VO.BizNeAssessmentScoreVO;
import com.unis.examine.modular.neassessmentScoreSum.entity.BizNeAssessmentScoreSum;
import com.unis.examine.modular.neassessmentScoreSum.mapper.BizNeAssessmentScoreSumMapper;
import com.unis.examine.modular.neassessmentScoreSum.service.BizNeAssessmentScoreSumService;
import com.unis.sys.modular.user.entity.SysUser;
import com.unis.sys.modular.user.service.SysUserService;
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.examine.modular.neassessmentScore.entity.BizNeAssessmentScore;
import com.unis.examine.modular.neassessmentScore.mapper.BizNeAssessmentScoreMapper;
import com.unis.examine.modular.neassessmentScore.param.BizNeAssessmentScoreAddParam;
import com.unis.examine.modular.neassessmentScore.param.BizNeAssessmentScoreEditParam;
import com.unis.examine.modular.neassessmentScore.param.BizNeAssessmentScoreIdParam;
import com.unis.examine.modular.neassessmentScore.param.BizNeAssessmentScorePageParam;
import com.unis.examine.modular.neassessmentScore.service.BizNeAssessmentScoreService;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.unis.examine.modular.assessmentManage.enums.AssessmentManageEnum.GK;

/**
 * 粮食安全责任制考核-考核评分表Service接口实现类
 *
 * @author ZeroLiYi
 * @date  2024/04/23 10:15
 **/
@Service
public class BizNeAssessmentScoreServiceImpl extends ServiceImpl<BizNeAssessmentScoreMapper, BizNeAssessmentScore> implements BizNeAssessmentScoreService {

    @Resource
    private BizNeAssessmentScoreSumMapper bizNeAssessmentScoreSumMapper;

    @Resource
    private AssessmentLevelService assessmentLevelService;

    @Resource
    private SysUserService sysUserService;
    @Resource
    private BizNeAssessmentScoreSumService bizNeAssessmentScoreSumService;

    @Resource
    private  BizNeAssessmentScoreService bizNeAssessmentScoreService;

    @Resource
    private BizNeAssessmentScoreMapper bizNeAssessmentScoreMapper;
    @Override
    public Page<BizNeAssessmentScore> page(BizNeAssessmentScorePageParam bizNeAssessmentScorePageParam) {
        QueryWrapper<BizNeAssessmentScore> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(bizNeAssessmentScorePageParam.getSortField(), bizNeAssessmentScorePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizNeAssessmentScorePageParam.getSortOrder());
            queryWrapper.orderBy(true, bizNeAssessmentScorePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizNeAssessmentScorePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizNeAssessmentScore::getId);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(List<BizNeAssessmentScoreAddParam> bizNeAssessmentScoreAddParams) {
        int sum = 0;
        int[] sumHolder = new int[]{0};
        SysUser user =sysUserService.queryEntity(StpUtil.getLoginIdAsString());
        for (BizNeAssessmentScoreAddParam bizNeAssessmentScoreAddParam:bizNeAssessmentScoreAddParams) {


        List<BizNeAssessmentScoreEditParam> assessmentScorelist = bizNeAssessmentScoreAddParam.getAssessmentScoreList();
        String aMid = assessmentScorelist.get(0).getAssessmentManageId();
        Integer pcType = assessmentScorelist.get(0).getPcType();
        //根据 单位 aMid pc_type  看是否有数据
        QueryWrapper<BizNeAssessmentScore> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("assessment_manage_id",aMid);
        if(pcType.equals(1)){
            queryWrapper.eq("pc_type",1);
        }else{
            queryWrapper.ne("pc_type",pcType);
        }

        List<BizNeAssessmentScore> bnaslist= bizNeAssessmentScoreMapper.selectList(queryWrapper);
        List<BizNeAssessmentScore> newScores = convertToBizNeAssessmentScores(assessmentScorelist);

        if(!bnaslist.isEmpty()){
                //评分表有数据
            bizNeAssessmentScoreMapper.deleteBatchIds(bnaslist.stream().map(BizNeAssessmentScore::getId).collect(Collectors.toList()));
                //评分表没数据
            saveAndAccumulateScores(newScores, sumHolder);
        }else{

            saveAndAccumulateScores(newScores, sumHolder);
        }

        // Update or insert the sum in BizNeAssessmentScoreSum
        handleSum(aMid, pcType, user, sumHolder);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizNeAssessmentScoreEditParam bizNeAssessmentScoreEditParam) {
        List<BizNeAssessmentScoreEditParam> assessmentScorelist = bizNeAssessmentScoreEditParam.getAssessmentScoreList();
        for (BizNeAssessmentScoreEditParam bse:assessmentScorelist) {
            if(bse.getStatus()==1){
                throw new CommonException("该条考核评分数据已上传，不能进行修改");
            }
            BizNeAssessmentScore bizNeAssessmentScore = this.queryEntity(bse.getId());
            BeanUtil.copyProperties(bse, bizNeAssessmentScore);
            this.updateById(bizNeAssessmentScore);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStutas(List<BizNeAssessmentScore>  bnasepList) {
        this.updateBatchById(bnasepList);
    }


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

    @Override
    public BizNeAssessmentScore detail(BizNeAssessmentScoreIdParam bizNeAssessmentScoreIdParam) {
        return this.queryEntity(bizNeAssessmentScoreIdParam.getId());
    }

    @Override
    public BizNeAssessmentScore queryEntity(String id) {
        BizNeAssessmentScore bizNeAssessmentScore = this.getById(id);
        if(ObjectUtil.isEmpty(bizNeAssessmentScore)) {
            throw new CommonException("粮食安全责任制考核-考核评分表不存在，id值为：{}", id);
        }
        return bizNeAssessmentScore;
    }

    @Override
    public List<BizNeAssessmentScoreVO> findByDetail(BizNeAssessmentScorePageParam bizNeAssessmentScorePageParam){
    //条形查询器
    QueryWrapper<BizNeAssessmentScoreVO> queryWrapper = new QueryWrapper<>();
        SysUser user =sysUserService.queryEntity(StpUtil.getLoginIdAsString());
        if(user==null){
            throw new CommonException("获取不到当前用户，请登陆后再试");
        }
        queryWrapper.eq("tar.sys_org_id", user.getOrgId());
            queryWrapper.eq("nam.assessment_type",2);
            queryWrapper.eq("nam.status",2);
            queryWrapper.eq("nam.id",bizNeAssessmentScorePageParam.getAssessmentManageId());


        List<BizNeAssessmentScoreVO> page = bizNeAssessmentScoreMapper.selectMyMapsPage(queryWrapper);
        return page;
    }

    public void uploading(List<BizNeAssessmentScorePageParam>  bizNeAssessmentScorePageParams) {
        int sum =0;
        int[] sumHolder = new int[]{0};
        for(BizNeAssessmentScorePageParam biz:bizNeAssessmentScorePageParams){
            BizNeAssessmentScore bizNeAssessmentScore1 = BeanUtil.toBean(biz, BizNeAssessmentScore.class);

            Integer pcType =biz.getPcType();
            Integer score =biz.getScore();
            Integer deduction =biz.getDeduction();
            String reasonForDeduction =biz.getReasonForDeduction();
            String aMid = biz.getAssessmentManageId();
            Integer status = biz.getStatus();
            SysUser user =sysUserService.queryEntity(StpUtil.getLoginIdAsString());

            QueryWrapper<BizNeAssessmentScore> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("assessment_manage_id",aMid);
            queryWrapper.eq("pc_type", pcType);
            List<BizNeAssessmentScore> existingScores  = bizNeAssessmentScoreService.list(queryWrapper);
            List<BizNeAssessmentScore>  bnasepList =new ArrayList<BizNeAssessmentScore>();
            BizNeAssessmentScore bizNeAssessmentScore = new BizNeAssessmentScore();
            if(!existingScores .isEmpty()){
                for (BizNeAssessmentScore existingScore :existingScores) {
                    existingScore.setStatus(status);
                    existingScore.setScore(existingScore.getScore() + score);
                    existingScore.setDeduction(deduction);
                    existingScore.setReasonForDeduction(reasonForDeduction);
                    bizNeAssessmentScoreService.updateById(existingScore);
                    sumHolder[0] += existingScore.getScore();
                }
                handleSum(aMid, pcType, user, sumHolder);

            }else {
                bizNeAssessmentScore1.setScore(score);
                bizNeAssessmentScore1.setDeduction(deduction);
                bizNeAssessmentScore1.setReasonForDeduction(reasonForDeduction);
                bizNeAssessmentScore1.setStatus(status);
                bizNeAssessmentScoreService.save(bizNeAssessmentScore1);
                sumHolder[0] += score;
                handleSum(aMid, pcType, user, sumHolder);
            }
        }


    }

    @Override
    public List<BizNeAssessmentScoreVO> findByScoreDetail(BizNeAssessmentScorePageParam bizNeAssessmentScorePageParam) {
        //条形查询器
        QueryWrapper<BizNeAssessmentScoreVO> queryWrapper = new QueryWrapper<>();
        SysUser user =sysUserService.queryEntity(StpUtil.getLoginIdAsString());
        queryWrapper.eq("nam.assessment_type",2);
        queryWrapper.eq("nam.status",2);
        queryWrapper.eq("nam.id",bizNeAssessmentScorePageParam.getAssessmentManageId());


        List<BizNeAssessmentScoreVO> page = bizNeAssessmentScoreMapper.selectMyMapsPage(queryWrapper);
        return page;
    }

    private List<BizNeAssessmentScore> convertToBizNeAssessmentScores(List<BizNeAssessmentScoreEditParam> editParams) {
        return editParams.stream()
                .map(editParam -> BeanUtil.toBean(editParam, BizNeAssessmentScore.class))
                .collect(Collectors.toList());
    }
    private void saveAndAccumulateScores(List<BizNeAssessmentScore> scores, int[] sumHolder) {
        for (BizNeAssessmentScore score : scores) {
            this.save(score);
            sumHolder[0] += score.getScore();
        }
    }

    private void handleSum(String aMid, Integer pcType, SysUser user,int[] sumHolder) {
        if (sumHolder[0] > 0) {
            List<BizNeAssessmentScoreSum> scoreSumList = bizNeAssessmentScoreSumService.findByAssessmentManageId(aMid,pcType);

            if (!scoreSumList.isEmpty()) {
                // Update existing sum
                BizNeAssessmentScoreSum existingSum = getExistingSum(scoreSumList, aMid, pcType, user.getOrgId());
                existingSum.setSumScore( sumHolder[0]);
                bizNeAssessmentScoreSumService.updateById(existingSum);
            } else {
                // Insert new sum
                AssessmentLevel assessmentLevel = assessmentLevelService.maxandMin(sumHolder[0], aMid);
                BizNeAssessmentScoreSum newSum = createNewSum(user, aMid, pcType, sumHolder, assessmentLevel);
                bizNeAssessmentScoreSumService.save(newSum);
            }
        }
    }

    private BizNeAssessmentScoreSum getExistingSum(List<BizNeAssessmentScoreSum> scoreSumList, String aMid, Integer pcType, String orgId) {
        QueryWrapper<BizNeAssessmentScoreSum> sumQueryWrapper = new QueryWrapper<>();
        sumQueryWrapper.eq("assessment_manage_id", aMid);

        if (pcType==1) {
            sumQueryWrapper.eq("pc_type", 1);
        } else {
            sumQueryWrapper.ne("pc_type", pcType);
        }

        return bizNeAssessmentScoreSumMapper.selectOne(sumQueryWrapper);
    }

    private BizNeAssessmentScoreSum createNewSum(SysUser user, String aMid, Integer pcType,int[] sumHolder, AssessmentLevel assessmentLevel) {
        BizNeAssessmentScoreSum newSum = new BizNeAssessmentScoreSum();
        newSum.setDeleteFlag("NOT_DELETE");
        newSum.setCreateUser(user.getId());
        newSum.setUpdateUser(user.getId());
        newSum.setPcType(pcType);
        newSum.setAssessmentManageId(aMid);
        newSum.setSumScore(sumHolder[0]);
        newSum.setAssessmentLevelId(assessmentLevel.getId());
        return newSum;
    }



}
