package com.jeeplus.test.rank.service;

import cn.hutool.core.collection.CollectionUtil;
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.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.rank.domain.*;
import com.jeeplus.test.rank.mapper.RankChildrenMapper;
import com.jeeplus.test.rank.mapper.RankMapper;
import com.jeeplus.test.rank.mapper.RankRRsMapper;
import com.jeeplus.test.rank.service.dto.RankDTO;
import com.jeeplus.test.rank.service.dto.RankSystemTableDTO;
import com.jeeplus.test.rank.service.mapstruct.RankChildrenWrapper;
import com.jeeplus.test.rank.service.mapstruct.RankWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Service
@Transactional
public class RankService extends ServiceImpl<RankMapper, Rank> {

    @Autowired
    private RankMapper rankMapper;

    @Autowired
    private RankRRsMapper rankRRsMapper;

    @Autowired
    private RankChildrenMapper rankChildrenMapper;

    @Autowired
    private RankSystemTableService rankSystemTableService;

    public IPage<RankDTO> findList(Page<RankDTO> page, QueryWrapper<Rank> queryWrapper){
        queryWrapper.eq("r.del_flag","0");
        return rankMapper.findList(page,queryWrapper);
    }

    public RankDTO queryById(String id){
        return rankMapper.getById(id);
    }

    public ResponseEntity saveRank(RankDTO rankDTO){
        Rank rank = RankWrapper.INSTANCE.toEntity(rankDTO);
        if(ObjectUtil.isNotEmpty(rank)){
            if(StringUtils.isNotBlank(rank.getId())){
                if("2".equals(rank.getUseFlag())){
                    List<RankSystemTable> rank_id = rankSystemTableService.list(new QueryWrapper<RankSystemTable>().eq("rank_id", rank.getId()));
                    if(CollectionUtil.isNotEmpty(rank_id)){
                        return ResponseEntity.badRequest().body("职级已被体系表引用，不可以修改状态为“禁用”");
                    }
                }
            }
            if(StringUtils.isNotBlank(rank.getId())&&StringUtils.isNotBlank(rank.getGroupName())){
                List<Rank> rank1 = rankMapper.selectList(new QueryWrapper<Rank>().ne("id", rank.getId()).eq("group_name", rank.getGroupName()));
                if(CollectionUtil.isNotEmpty(rank1)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ResponseEntity.badRequest().body("分组名称已存在");
                }
            }else if(StrUtil.isEmpty(rank.getId())&&StringUtils.isNotBlank(rank.getGroupName())){
                List<Rank> rank2 = rankMapper.selectList(new QueryWrapper<Rank>().eq("group_name", rank.getGroupName()));
                if(CollectionUtil.isNotEmpty(rank2)){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ResponseEntity.badRequest().body("分组名称已存在");
                }
            }
        }else{
            return ResponseEntity.badRequest().body("要保存的数据不正确");
        }
        this.saveOrUpdate(rank);
        if(StringUtils.isNotBlank(rank.getUseFlag())){
            if("1".equals(rank.getUseFlag())){
                List<RankSystemTable> rank_id = rankSystemTableService.list(new QueryWrapper<RankSystemTable>().eq("rank_id", rank.getId()));
                if(CollectionUtil.isEmpty(rank_id)){
                    RankSystemTableDTO rankSystemTableDTO = new RankSystemTableDTO();
                    rankSystemTableDTO.setRankId(rank.getId());
                    rankSystemTableDTO.setUseFlag("1");
                    rankSystemTableService.saveDate(rankSystemTableDTO);
                }
            }
        }
        if(ObjectUtil.isNotEmpty(rankDTO)){
            if(StringUtils.isNotBlank(rankDTO.getId())){
                rankChildrenMapper.delete(new QueryWrapper<RankChildren>().eq("rank_id",rankDTO.getId()));
                rankRRsMapper.delete(new QueryWrapper<RankRRs>().eq("rank_id",rankDTO.getId()));
                if(CollectionUtil.isNotEmpty(rankDTO.getSequenceIdList())){
                    rankRRsMapper.insertListById(rankDTO.getId(),rankDTO, UserUtils.getCurrentUserDTO().getId());
                }
            }else{
                rankRRsMapper.insertListById(rank.getId(),rankDTO, UserUtils.getCurrentUserDTO().getId());
            }

            if(CollectionUtil.isNotEmpty(rankDTO.getRankList())){
                HashMap<String,Object> rankList = new HashMap<>();
                AtomicReference<String> err = new AtomicReference<>("");
                rankDTO.getRankList().stream().forEach(item->{
                    rankList.put(item.getName(),null);
                    if(CollectionUtil.isNotEmpty(item.getRankListChildren())){
                        HashMap<String,Object> childrenList = new HashMap<>();
                        item.getRankListChildren().stream().forEach(item2->{
                            childrenList.put(item2.getName(),null);
                        });
                        if(childrenList.size() != item.getRankListChildren().size()){
                            err.set("职级“"+item.getName()+"”下有子职级重复");
                            return;
                        }
                    }
                });
                if(StringUtils.isNotBlank(err.get())){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ResponseEntity.badRequest().body(err.get());
                }
                if(rankList.size() != rankDTO.getRankList().size()){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                   return ResponseEntity.badRequest().body("含有重复职级");
                }
            }


            if(CollectionUtil.isNotEmpty(rankDTO.getRankList())){
                rankDTO.getRankList().stream().forEach(item->{
                    if(ObjectUtil.isNotEmpty(item)){
                        RankChildren rankChildren = new RankChildren();
                        rankChildren.setName(item.getName());
                            rankChildren.setRankLevel("1");
                            rankChildren.setRankId(rank.getId());
                            rankChildren.setRankParent("0");
                            rankChildrenMapper.insert(rankChildren);
                            if(CollectionUtil.isNotEmpty(item.getRankListChildren())){
                                item.getRankListChildren().stream().forEach(item2->{
                                    RankChildren rankChildren2 = new RankChildren();
                                    rankChildren2.setName(item2.getName());
                                    rankChildren2.setRankLevel("2");
                                    rankChildren2.setRankId(rank.getId());
                                    rankChildren2.setRankParent(rankChildren.getId());
                                    rankChildrenMapper.insert(rankChildren2);
                                });
                            }
                        }
                    /*}*/
                });
            }
        }
        return ResponseEntity.ok("保存职级成功");
    }

    public void updateUseFlagById(List<String> ids, String useFlag){
        rankMapper.updateUseFlagById(ids,useFlag);
    }

    public List<RankDTO> getRankByPosition(String id){
        return rankMapper.getRankByPosition(id);
    }
}