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.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.service.mapstruct.JobPositionWrapper;
import com.jeeplus.test.rank.domain.RankRsOffice;
import com.jeeplus.test.rank.domain.RankSequence;
import com.jeeplus.test.rank.service.RankRsOfficeService;
import com.jeeplus.test.rank.service.RankSequenceService;
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 io.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
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_sequence")
public class RankSequenceController {

    @Autowired
    private RankSequenceService rankSequenceService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private RankRsOfficeService rankRsOfficeService;

    /**
     * 查询序列列表
     * @param rankSequenceDTO
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询序列列表")
    @PreAuthorize("hasAuthority('rank:rank_sequence:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<RankSequenceDTO>> data(RankSequenceDTO rankSequenceDTO, Page<RankSequenceDTO> page) throws Exception {
        RankSequence rankSequence = RankSequenceWrapper.INSTANCE.toEntity(rankSequenceDTO);
        QueryWrapper<RankSequence> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( rankSequence, RankSequence.class );
        if(ObjectUtil.isNotEmpty(rankSequenceDTO)){
            if(CollectionUtil.isNotEmpty(rankSequenceDTO.getOfficeIdList())){
                List<RankRsOffice> rankRsOffices = rankRsOfficeService.list(new QueryWrapper<RankRsOffice>().in("office_id", rankSequenceDTO.getOfficeIdList()));
                List<String> collect = rankRsOffices.stream().distinct().map(RankRsOffice::getRsId).collect(Collectors.toList());
                queryWrapper.in("rs.id",collect);
            }
        }
        IPage<RankSequenceDTO> result = rankSequenceService.findList (page,queryWrapper);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询序列列表
     * @param rankSequenceDTO
     * @return
     * @throws Exception
     */
    @ApiLog("查询序列列表")
    @PreAuthorize("hasAuthority('rank:rank_sequence:list')")
    @GetMapping("getList")
    public ResponseEntity<List<RankSequenceDTO>> getList(RankSequenceDTO rankSequenceDTO) throws Exception {
        RankSequence rankSequence = RankSequenceWrapper.INSTANCE.toEntity(rankSequenceDTO);
        QueryWrapper<RankSequence> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( rankSequence, RankSequence.class );
        if(ObjectUtil.isNotEmpty(rankSequenceDTO)){
            if(CollectionUtil.isNotEmpty(rankSequenceDTO.getOfficeIdList())){
                List<RankRsOffice> rankRsOffices = rankRsOfficeService.list(new QueryWrapper<RankRsOffice>().in("office_id", rankSequenceDTO.getOfficeIdList()));
                List<String> collect = rankRsOffices.stream().distinct().map(RankRsOffice::getRsId).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(collect)){
                    queryWrapper.eq("rs.id",collect);
                }else{
                    return ResponseEntity.ok (null);
                }
            }
        }
        List<RankSequenceDTO> result = rankSequenceService.getList (queryWrapper);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询序列数据
     * @param id
     * @return
     */
    @ApiLog("查询序列详情")
    @PreAuthorize ("hasAnyAuthority('rank:rank_sequence:view','rank:rank_sequence:add','rank:rank_sequence:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        RankSequenceDTO rankSequenceDTO = rankSequenceService.queryById ( id );
        return ResponseEntity.ok (rankSequenceDTO);
    }

    /**
     * 添加序列
     * @param rsSaveDTO
     * @return
     */
    @ApiLog(value = "修改/新增序列", type = LogTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('rank:rank_sequence:save','rank:rank_sequence:edit')")
    @PostMapping("save")
    public ResponseEntity save(@RequestBody RsSaveDTO rsSaveDTO) {
        return rankSequenceService.saveRankSequence(rsSaveDTO);
    }

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

    /**
     * 修改序列启用状态
     * @param ids
     * @return
     */
    @ApiLog(value = "修改序列启用状态", type = LogTypeEnum.SAVE)
    @PreAuthorize ("hasAnyAuthority('rank:rank_sequence:del','rank:rank_sequence:edit','rank:rank_sequence: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);
        rankSequenceService.updateUseFlagById(strings,useFlag);
        return ResponseEntity.ok ("修改职位状态成功");
    }

    /**
     * 根据所有公司
     * @return
     */
    @ApiLog("查询公司")
    @GetMapping("queryAllFirm")
    public ResponseEntity queryAllFirm() {
        List<OfficeDTO> officeDTOList = new ArrayList<>();
        List<Office> list = officeService.list(new QueryWrapper<Office>().eq("type","1").eq("useable","1"));
        list.stream().forEach(item->{
            OfficeDTO officeDTO = OfficeWrapper.INSTANCE.toDTO (item);
            officeDTOList.add(officeDTO);
        });
        return ResponseEntity.ok (officeDTOList);
    }
}
