package com.jeeplus.test.rank.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
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.google.common.collect.Lists;
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.Office;
import com.jeeplus.sys.service.OfficeService;
import com.jeeplus.sys.service.dto.OfficeDTO;
import com.jeeplus.sys.service.mapstruct.OfficeWrapper;
import com.jeeplus.test.jobPosion.domain.JobPosition;
import com.jeeplus.test.rank.domain.Rank;
import com.jeeplus.test.rank.domain.RankRRs;
import com.jeeplus.test.rank.domain.RankRsOffice;
import com.jeeplus.test.rank.domain.RankSequence;
import com.jeeplus.test.rank.service.RankRRSService;
import com.jeeplus.test.rank.service.RankRsOfficeService;
import com.jeeplus.test.rank.service.RankSequenceService;
import com.jeeplus.test.rank.service.RankService;
import com.jeeplus.test.rank.service.dto.RankDTO;
import com.jeeplus.test.rank.service.dto.RankSequenceDTO;
import com.jeeplus.test.rank.service.mapstruct.RankSequenceWrapper;
import com.jeeplus.test.rank.service.mapstruct.RankWrapper;
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.stream.Collectors;

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

    @Autowired
    private RankSequenceService rankSequenceService;

    @Autowired
    private RankService rankService;

    @Autowired
    private RankRRSService rankRRSService;

    /**
     * 查询序列列表
     * @param rankDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询职级列表")
    @PreAuthorize("hasAuthority('rank:rank:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<RankDTO>> data(RankDTO rankDTO, Page<RankDTO> page) throws Exception {
        Rank rank = RankWrapper.INSTANCE.toEntity(rankDTO);
        QueryWrapper<Rank> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( rank, Rank.class );
        if(ObjectUtil.isNotEmpty(rankDTO)){
            if(CollectionUtil.isNotEmpty(rankDTO.getSequenceIdList())){
                List<RankRRs> rankRRs = rankRRSService.list(new QueryWrapper<RankRRs>().in("rs_id", rankDTO.getSequenceIdList()));
                List<String> collect = rankRRs.stream().distinct().map(RankRRs::getRankId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(collect)){
                    queryWrapper.in("r.id",collect);
                }else{
                    return ResponseEntity.ok (null);
                }
            }
        }
        IPage<RankDTO> result = rankService.findList (page,queryWrapper);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询职级数据
     * @param id
     * @return
     */
    @ApiLog("查询职级详情")
    @PreAuthorize ("hasAnyAuthority('rank:rank:view','rank:rank:add','rank:rank:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        RankDTO rankDTO = rankService.queryById ( id );
        return ResponseEntity.ok (rankDTO);
    }

    /**
     * 添加职级
     * @param rankDTO
     * @return
     */
    @ApiLog(value = "修改/新增职级", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('rank:rank:save','rank:rank:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody RankDTO rankDTO, HttpServletRequest request) {
        return rankService.saveRank(rankDTO);
    }

    /**
     * 删除职级
     * @param ids
     * @return
     */
    @ApiLog(value = "删除职级", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAuthority('rank:rank:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids,HttpServletRequest request) {
        String idArray[] =ids.split(",");
        rankService.removeByIds (Lists.newArrayList (idArray));
        return ResponseEntity.ok ("删除职级成功");
    }

    /**
     * 修改职级启用状态
     * @param ids
     * @return
     */
    @ApiLog(value = "修改职级启用状态", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAnyAuthority('rank:rank:del','rank:rank:edit','rank:rank:add')")
    @PostMapping("changeUseFlag/{useFlag}")
    public ResponseEntity changeUseFlag(String ids,@PathVariable("useFlag") String useFlag,HttpServletRequest request) {
        String idArray[] =ids.split(",");
        ArrayList<String> strings = Lists.newArrayList(idArray);
        rankService.updateUseFlagById(strings,useFlag);
        return ResponseEntity.ok ("修改职级状态成功");
    }

    /**
     * 根据所有一级序列
     * @return
     */
    @ApiLog("查询一级序列")
    @GetMapping("queryAllSequence")
    public ResponseEntity queryAllFirm() {
        List<RankSequenceDTO> rankSequenceDTOS = new ArrayList<>();
        List<RankSequence> list = rankSequenceService.list(new QueryWrapper<RankSequence>().eq("parent_id","0"));
        list.stream().forEach(item->{
            RankSequenceDTO rankSequenceDTO = RankSequenceWrapper.INSTANCE.toDTO (item);
            rankSequenceDTOS.add(rankSequenceDTO);
        });
        return ResponseEntity.ok (rankSequenceDTOS);
    }

    @GetMapping("getRankByPosition")
    public ResponseEntity getRankByPosition(String id){
        List<RankDTO> rankList = rankService.getRankByPosition(id);
        return ResponseEntity.ok(rankList);
    }
}
