package com.jeeplus.test.jobPosion.controller;

import cn.hutool.core.collection.CollectionUtil;
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.utils.StringUtils;
import com.jeeplus.test.jobPosion.domain.PositionCategory;
import com.jeeplus.test.jobPosion.enums.PositionTypeEnum;
import com.jeeplus.test.jobPosion.service.PositionCategoryService;
import com.jeeplus.test.jobPosion.service.PositionLogService;
import com.jeeplus.test.jobPosion.service.PositionService;
import com.jeeplus.test.jobPosion.service.dto.PositionCategoryDTO;
import com.jeeplus.test.jobPosion.service.dto.PositionLogDTO;
import com.jeeplus.test.jobPosion.service.mapstruct.PositionCategoryWrapper;
import com.jeeplus.test.projectRecords.domain.Project;
import io.swagger.annotations.Api;
import org.checkerframework.checker.units.qual.A;
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 = "/job/position_category")
public class PositionCategoryController {

    @Autowired
    private PositionCategoryService positionCategoryService;

    @Autowired
    private PositionLogService positionLogService;

    /**
     * 查询职务分类列表
     * @param positionCategory
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询职务分类列表")
    @PreAuthorize("hasAuthority('job:position_category:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<PositionCategory>> data(PositionCategory positionCategory, Page<PositionCategory> page) throws Exception {
        QueryWrapper<PositionCategory> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( positionCategory, PositionCategory.class );
        queryWrapper.orderByAsc("sort").orderByDesc("create_date");
        IPage<PositionCategory> result = positionCategoryService.page (page,queryWrapper);
        return ResponseEntity.ok (result);
    }

    /**
     * 查询职务分类数据
     * @param id
     * @return
     */
    @ApiLog("查询职务分类详情")
    @PreAuthorize ("hasAnyAuthority('job:position_category:view','job:position_category:add','job:position_category:edit')")
    @GetMapping("queryById")
    public ResponseEntity queryById(@RequestParam("id") String id) {
        PositionCategory positionCategory = positionCategoryService.getById ( id );
        return ResponseEntity.ok (positionCategory);
    }

    /**
     * 添加职务分类
     * @param positionCategoryDTO
     * @return
     */
    @ApiLog("添加职务分类")
    @PreAuthorize("hasAnyAuthority('job:position_category:save','job:position_category:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody PositionCategoryDTO positionCategoryDTO, HttpServletRequest request) {
        PositionLogDTO positionLogDTO = new PositionLogDTO();
        PositionCategory positionCategory = PositionCategoryWrapper.INSTANCE.toEntity(positionCategoryDTO);
        if(StringUtils.isNotBlank(positionCategoryDTO.getId())){
            List<PositionCategory> positionCategories = positionCategoryService.list(new QueryWrapper<PositionCategory>()
                    .ne("id",positionCategoryDTO.getId()).eq("name", positionCategoryDTO.getName()));
            if(CollectionUtil.isNotEmpty(positionCategories)){
                return ResponseEntity.badRequest().body("职务分类名称不可以重复");
            }
            PositionCategory byId = positionCategoryService.getById(positionCategoryDTO.getId());
            positionLogDTO.setType(PositionTypeEnum.POSITION_CATEGORY.getValue());
            positionLogDTO.setOperationType("编辑职务分类");
            positionLogDTO.setOperationContent("编辑职务分类: 职务分类名称由“"+byId.getName()+"”变更为“"+positionCategoryDTO.getName()+"”");
        }else{
            List<PositionCategory> positionCategories = positionCategoryService.list(new QueryWrapper<PositionCategory>()
                        .eq("name", positionCategoryDTO.getName()));
            if(CollectionUtil.isNotEmpty(positionCategories)){
                return ResponseEntity.badRequest().body("职务分类名称不可以重复");
            }
            positionLogDTO.setType(PositionTypeEnum.POSITION_CATEGORY.getValue());
            positionLogDTO.setOperationType("创建职务分类");
            positionLogDTO.setOperationContent("创建职务分类: "+positionCategoryDTO.getName());
        }
        try{
            positionCategoryService.saveOrUpdate(positionCategory);
        }catch (Exception e){
            positionLogDTO.setOperationResult("失败");
            positionLogService.saveLog(positionLogDTO,request);
            return ResponseEntity.badRequest().body  ("保存职务分类失败");
        }
        positionLogDTO.setOperationResult("成功");
        positionLogService.saveLog(positionLogDTO,request);
        return ResponseEntity.ok ("保存职务分类成功");
    }

    /**
     * 删除职务分类
     * @param ids
     * @return
     */
    @ApiLog("删除职务分类")
    @PreAuthorize ("hasAuthority('job:position_category:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids,HttpServletRequest request) {
        List<PositionLogDTO> positionLogDTOList = new ArrayList<>();
        String idArray[] =ids.split(",");
        List<PositionCategory> positionCategories = positionCategoryService.listByIds(Lists.newArrayList(idArray));
        positionCategories.stream().forEach(item->{
            PositionLogDTO positionLogDTO = new PositionLogDTO();
            positionLogDTO.setType(PositionTypeEnum.POSITION_CATEGORY.getValue());
            positionLogDTO.setOperationType("删除职务分类");
            positionLogDTO.setOperationContent("删除职务分类: "+item.getName());
            positionLogDTOList.add(positionLogDTO);
        });
        try{
            positionCategoryService.removeByIds (Lists.newArrayList (idArray));
        }catch (Exception e){
            positionLogDTOList.stream().forEach(item->{
                item.setOperationResult("失败");
            });
            positionLogService.saveLogBatch(positionLogDTOList,request);
            return ResponseEntity.badRequest().body  ("删除职务分类失败");
        }

        positionLogDTOList.stream().forEach(item->{
            item.setOperationResult("成功");
        });
        positionLogService.saveLogBatch(positionLogDTOList,request);
        return ResponseEntity.ok ("删除职务分类成功");
    }
    /**
     * 修改职务分类顺序
     * @param positionCategoryDTOList
     * @return
     */
    @ApiLog("修改职务分类顺序")
    @PreAuthorize("hasAnyAuthority('job:position_category:view')")
    @PostMapping("updateSort")
    public ResponseEntity updateSortById(@RequestBody List<PositionCategoryDTO> positionCategoryDTOList) {
        positionCategoryService.updateSortByIdList(positionCategoryDTOList);
        return ResponseEntity.ok ("保存职务分类排序成功");
    }

}
