package com.jeeplus.test.rank.controller;

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.jeeplus.aop.logging.annotation.ApiLog;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.constant.enums.LogTypeEnum;
import com.jeeplus.sys.domain.Post;
import com.jeeplus.sys.service.PostService;
import com.jeeplus.sys.service.dto.PostDTO;
import com.jeeplus.sys.service.mapstruct.PostWrapper;
import com.jeeplus.test.jobPosion.domain.Position;
import com.jeeplus.test.jobPosion.service.PositionService;
import com.jeeplus.test.jobPosion.service.dto.PositionDTO;
import com.jeeplus.test.jobPosion.service.mapstruct.PositionWrapper;
import com.jeeplus.test.rank.domain.*;
import com.jeeplus.test.rank.service.RankLevelService;
import com.jeeplus.test.rank.service.RankRstLevelService;
import com.jeeplus.test.rank.service.RankSequenceService;
import com.jeeplus.test.rank.service.RankSystemTableService;
import com.jeeplus.test.rank.service.dto.RankLevelDTO;
import com.jeeplus.test.rank.service.dto.RankSystemTableDTO;
import com.jeeplus.test.rank.service.mapstruct.RankLevelWrapper;
import com.jeeplus.test.rank.service.mapstruct.RankSystemTableWrapper;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Api("职级体系-体系表管理")
@RestController
@RequestMapping(value = "/rank/rank_system_table")
public class RankSystemTableController {

    @Autowired
    private RankSystemTableService rankSystemTableService;

    @Autowired
    private RankLevelService rankLevelService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private PostService postService;

    @Autowired
    private RankRstLevelService rankRstLevelService;

    @Autowired
    private RankSequenceService rankSequenceService;

    /**
     * 查询职层列表
     * @param rankSystemTableDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询列表")
    @PreAuthorize("hasAuthority('rank:rank_system_table:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<RankSystemTableDTO>> data(RankSystemTableDTO rankSystemTableDTO, Page<RankSystemTableDTO> page) throws Exception {
        RankSystemTable rankSystemTable = RankSystemTableWrapper.INSTANCE.toEntity(rankSystemTableDTO);
        QueryWrapper<RankSystemTable> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( rankSystemTable, RankSystemTable.class );
        if(ObjectUtil.isNotEmpty(rankSystemTableDTO)){
            if(StrUtil.isNotEmpty(rankSystemTableDTO.getLevelId())){
                List<RankRstLevel> rankRstLevels = rankRstLevelService.list(new QueryWrapper<RankRstLevel>().in("level_id", rankSystemTableDTO.getLevelId()));
                if(CollectionUtil.isEmpty(rankRstLevels)){
                    return ResponseEntity.ok (null);
                }
                List<RankSequence> list = rankSequenceService.list(new QueryWrapper<RankSequence>().eq("del_flag", "0").ne("parent_id", "0"));
                if(CollectionUtil.isNotEmpty(list)){
                    AtomicInteger num = new AtomicInteger();
                    num.set(0);
                    rankRstLevels.stream().forEach(item->{
                        if(num.get() !=0){
                            queryWrapper.or();
                        }
                        queryWrapper.eq("rc.id",item.getRcId()).eq("rs_c.id",item.getRsId()).eq("rst.id",item.getRstId());
                        num.set(num.get()+1);
                    });
                }else{
                    AtomicInteger num = new AtomicInteger();
                    num.set(0);
                    rankRstLevels.stream().forEach(item->{
                        if(num.get() !=0){
                            queryWrapper.or();
                        }
                        queryWrapper.eq("rc.id",item.getRcId()).eq("rs_p.id",item.getRsId()).eq("rst.id",item.getRstId());
                        num.set(num.get()+1);
                    });
                }

            }
        }
        if(StrUtil.isNotEmpty(rankSystemTableDTO.getRsId())){
            queryWrapper.eq("rs_p.id",rankSystemTableDTO.getRsId());
        }
        IPage<RankSystemTableDTO> result = this.rankSystemTableService.findList (page,queryWrapper);
        return ResponseEntity.ok (result);
    }



    /**
     * 添加职层
     * @param rankSystemTableDTO
     * @return
     */
    @ApiLog(value = "修改/新增体系表", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('rank:rank_system_table:save','rank:rank_system_table:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody RankSystemTableDTO rankSystemTableDTO, HttpServletRequest request) {
        this.rankSystemTableService.saveDate(rankSystemTableDTO);
        return ResponseEntity.ok ("保存体系表成功");
    }

    /**
     * 查询体系表数据
     * @return
     */
    @ApiLog("查询体系表数据")
    @PreAuthorize ("hasAnyAuthority('rank:rank_system_table:view','rank:rank_system_table:add','rank:rank_system_table:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("rankId") String rankId,@RequestParam("rcId") String rcId,@RequestParam("rsId") String rsId) {
        RankSystemTableDTO rankSystemTableDTO = rankSystemTableService.queryById ( rankId,rcId,rsId );
        return ResponseEntity.ok (rankSystemTableDTO);
    }

    /**
     * 查询所有职层
     * @return
     */
    @ApiLog("查询所有职层")
    @GetMapping("queryAllRankLevel")
    public ResponseEntity queryAllRankLevel() {
        List<RankLevelDTO> rankLevelDTOList = new ArrayList<>();
        List<RankLevel> list = rankLevelService.list();
        list.stream().forEach(item->{
            RankLevelDTO rankLevelDTO = RankLevelWrapper.INSTANCE.toDTO (item);
            rankLevelDTOList.add(rankLevelDTO);
        });
        return ResponseEntity.ok (rankLevelDTOList);
    }


    /**
     * 查询所有职务
     * @return
     */
    @ApiLog("查询所有职务")
    @GetMapping("queryAllPosition")
    public ResponseEntity queryAllPosition() {
        List<PositionDTO> positionDTOList = new ArrayList<>();
        List<Position> list = positionService.list();
        list.stream().forEach(item->{
            PositionDTO positionDTO = PositionWrapper.INSTANCE.toDTO (item);
            positionDTOList.add(positionDTO);
        });
        return ResponseEntity.ok (positionDTOList);
    }


    /**
     * 查询所有岗位
     * @return
     */
    @ApiLog("查询所有岗位")
    @GetMapping("queryAllPost")
    public ResponseEntity queryAllPost() {
        List<PostDTO> postDTOList = new ArrayList<>();
        List<Post> list = postService.list();
        list.stream().forEach(item->{
            PostDTO postDTO = PostWrapper.INSTANCE.toDTO (item);
            postDTOList.add(postDTO);
        });
        return ResponseEntity.ok (postDTOList);
    }



}
