package com.jeeplus.test.rank.service;

import cn.afterturn.easypoi.excel.annotation.Excel;
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.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.RankRsOffice;
import com.jeeplus.test.rank.domain.RankRstPosition;
import com.jeeplus.test.rank.domain.RankSequence;
import com.jeeplus.test.rank.domain.RankSystemTable;
import com.jeeplus.test.rank.mapper.*;
import com.jeeplus.test.rank.service.dto.RankSequenceDTO;
import com.jeeplus.test.rank.service.dto.RsSaveDTO;
import com.jeeplus.test.rank.service.mapstruct.RankSequenceWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional(rollbackFor = Exception.class)
public class RankSequenceService extends ServiceImpl<RankSequenceMapper,RankSequence> {

    @Autowired
    private RankSequenceMapper rankSequenceMapper;

    @Autowired
    private RankRsOfficeMapper rankRsOfficeMapper;

    @Autowired
    private RankRstPositionMapper rankRstPositionMapper;

    @Autowired
    private RankRstPostMapper rankRstPostMapper;

    @Autowired
    private RankSystemTableService rankSystemTableService;

    @Autowired
    private RankRstLevelMapper rankRstLevelMapper;

    public ResponseEntity saveRankSequence(RsSaveDTO rsSaveDTO){
        List<RankSequenceDTO> rankSequenceDTOList = rsSaveDTO.getRankSequenceDTOList();
        Boolean change = rsSaveDTO.getChange();
        if(change == true){
            rankRstPositionMapper.delete(new QueryWrapper<>());
            rankRstPostMapper.delete(new QueryWrapper<>());
            rankRstLevelMapper.delete(new QueryWrapper<>());
        }
        HashMap<String,Object> hashMap = new HashMap<>();
        AtomicReference<Integer> listSize = new AtomicReference<>(rankSequenceDTOList.size());
        List<String> ids = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(rankSequenceDTOList)){
            rankSequenceDTOList.stream().forEach(item->{
                if(StringUtils.isNotBlank(item.getId())){
                    ids.add(item.getId());
                }
                if(StringUtils.isNotBlank(item.getName())){
                    hashMap.put(item.getName(),null);
                }
                if(CollectionUtil.isNotEmpty(item.getRankSequenceDTOList())){
                    listSize.set(listSize.get()+item.getRankSequenceDTOList().size());
                    item.getRankSequenceDTOList().stream().forEach(item2->{
                        if(StringUtils.isNotBlank(item2.getId())){
                            ids.add(item2.getId());
                        }
                        if(StringUtils.isNotBlank(item2.getName())){
                            hashMap.put(item2.getName(),null);
                        }
                    });
                }
            });
        }
        if(!Integer.valueOf(hashMap.size()).equals(listSize.get())){
            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseEntity.badRequest().body("不可以存在重复的序列");
        }
        this.rankSequenceMapper.delete(new QueryWrapper<RankSequence>().notIn("id",ids));
        if(CollectionUtil.isNotEmpty(rankSequenceDTOList)){
            rankSequenceDTOList.stream().forEach(item->{
                RankSequence rankSequence = RankSequenceWrapper.INSTANCE.toEntity(item);
                rankSequence.setParentId("0");
                this.saveOrUpdate(rankSequence);
                if(CollectionUtil.isNotEmpty(item.getRankSequenceDTOList())){
                    item.getRankSequenceDTOList().stream().forEach(item2->{
                        RankSequence rankSequence2 = RankSequenceWrapper.INSTANCE.toEntity(item2);
                        rankSequence2.setParentId(rankSequence.getId());
                        this.saveOrUpdate(rankSequence2);
                    });
                }
                if(ObjectUtil.isNotEmpty(item)){
                    if(StringUtils.isNotBlank(item.getId())){
                        rankRsOfficeMapper.delete(new QueryWrapper<RankRsOffice>().eq("rs_id",item.getId()));
                        if(CollectionUtil.isNotEmpty(item.getOfficeIdList())){
                            rankRsOfficeMapper.insertListById(item.getId(),item, UserUtils.getCurrentUserDTO().getId());
                        }
                    }else{
                        if(CollectionUtil.isNotEmpty(item.getOfficeIdList())){
                            rankRsOfficeMapper.insertListById(rankSequence.getId(),item, UserUtils.getCurrentUserDTO().getId());
                        }
                    }
                }
            });
        }

        return ResponseEntity.ok("保存序列成功");
    }

    public IPage<RankSequenceDTO> findList(Page<RankSequenceDTO> page, QueryWrapper<RankSequence> queryWrapper){
        queryWrapper.eq("rs.parent_id","0")
                .eq("rs.del_flag","0")
                .orderByAsc("rs.sort")
                .orderByDesc("rs.create_date");
        return rankSequenceMapper.findList(page,queryWrapper);
    }

    public List<RankSequenceDTO> getList(QueryWrapper<RankSequence> queryWrapper){
        queryWrapper.eq("rs.parent_id","0")
                .eq("rs.del_flag","0")
                .orderByAsc("rs.sort")
                .orderByDesc("rs.create_date");
        return rankSequenceMapper.getList(queryWrapper);
    }

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

    public RankSequenceDTO queryById(String id){
        return rankSequenceMapper.queryById(id);
    }
}