package com.jeeplus.test.jobPosion.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.utils.StringUtils;
import com.jeeplus.test.jobPosion.domain.JobPosition;
import com.jeeplus.test.jobPosion.domain.Position;
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.PositionDTO;
import com.jeeplus.test.jobPosion.service.dto.PositionLogDTO;
import com.jeeplus.test.jobPosion.service.mapstruct.PositionWrapper;
import com.jeeplus.test.jobPosion.utils.BeanUtils;
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;

@Api("职务管理")
@RestController
@RequestMapping(value = "/job/position")
public class PositionController {

    @Autowired
    private PositionService positionService;

    @Autowired
    private PositionCategoryService positionCategoryService;

    @Autowired
    private PositionLogService positionLogService;

    /**
     * 查询职务列表
     * @param position
     * @param page
     * @return
     * @throws Exception
     */
    @ApiLog("查询职务列表")
    @PreAuthorize("hasAuthority('job:position:list')")
    @GetMapping("list")
    public ResponseEntity<IPage<Position>> data(Position position, Page<Position> page) throws Exception {
        QueryWrapper<Position> queryWrapper = QueryWrapperGenerator.buildQueryCondition ( position, Position.class );
        IPage<Position> result = positionService.findList (page,queryWrapper);
        return ResponseEntity.ok (result);
    }

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

    /**
     * 查询全部职务类型
     * @return
     */
    @ApiLog("查询全部职务类型")
    @PreAuthorize ("hasAnyAuthority('job:position:view','job:position:add','job:position:edit')")
    @GetMapping("queryAllCategory")
    public ResponseEntity<List<PositionCategory>> queryAllCategory() {
        List<PositionCategory> list = positionCategoryService.list();
        return ResponseEntity.ok (list);
    }

    /**
     * 添加职务
     * @param positionDTO
     * @return
     */
    @ApiLog("添加职务")
    @PreAuthorize("hasAnyAuthority('job:position:save','job:position:edit')")
    @PostMapping("save")
    public ResponseEntity save(@Valid @RequestBody PositionDTO positionDTO, HttpServletRequest request) {
        PositionLogDTO positionLogDTO = new PositionLogDTO();
        Position position = PositionWrapper.INSTANCE.toEntity(positionDTO);
        Position oldPosition = null;
        if(StringUtils.isNotBlank(positionDTO.getId())){
            List<Position> positions = positionService.list(new QueryWrapper<Position>()
                    .ne("id",positionDTO.getId()).eq("name", positionDTO.getName()));
            if(CollectionUtil.isNotEmpty(positions)){
                return ResponseEntity.badRequest().body("职务名称不可以重复");
            }
            oldPosition = positionService.getById(positionDTO.getId());
            if(ObjectUtil.isNotEmpty(oldPosition)){
                if(StringUtils.isNotBlank(oldPosition.getCategoryId())){
                    PositionCategory byId = positionCategoryService.getById(oldPosition.getCategoryId());
                    if(ObjectUtil.isNotEmpty(byId)){
                        if(StringUtils.isNotBlank(byId.getName())){
                            oldPosition.setCategoryId(byId.getName());
                        }
                    }
                }
            }
            positionLogDTO.setType(PositionTypeEnum.POSITION.getValue());
            positionLogDTO.setOperationType("修改职务");

        }else{
            List<Position> positions = positionService.list(new QueryWrapper<Position>()
                    .eq("name", positionDTO.getName()));
            if(CollectionUtil.isNotEmpty(positions)){
                return ResponseEntity.badRequest().body("职务名称不可以重复");
            }
            positionLogDTO.setType(PositionTypeEnum.POSITION.getValue());
            positionLogDTO.setOperationType("新建职务");
            positionLogDTO.setOperationContent("新建职务: "+positionDTO.getName());
        }
        try{
            positionService.saveOrUpdate(position);
        }catch (Exception e){
            if(StringUtils.isNotBlank(positionDTO.getId())){
                String changedFields = BeanUtils.getChangedFields(position, new Position());
                positionLogDTO.setOperationContent(changedFields);
            }
            positionLogDTO.setOperationResult("失败");
            positionLogService.saveLog(positionLogDTO,request);
            return ResponseEntity.badRequest().body  ("职务保存失败");
        }

        if (StringUtils.isNotBlank(positionDTO.getId())){
            Position byId = positionService.getById(positionDTO.getId());
            if(ObjectUtil.isNotEmpty(byId)){
                if(StringUtils.isNotBlank(byId.getCategoryId())){
                    PositionCategory byId1 = positionCategoryService.getById(byId.getCategoryId());
                    if(ObjectUtil.isNotEmpty(byId1)){
                        byId.setCategoryId(byId1.getName());
                    }
                }
            }

            String changedFields = BeanUtils.getChangedFields(byId, oldPosition);
            positionLogDTO.setOperationContent(changedFields);
        }
        positionLogDTO.setOperationResult("成功");
        positionLogService.saveLog(positionLogDTO,request);

        return ResponseEntity.ok ("保存职务成功");
    }

    /**
     * 删除职务
     * @param ids
     * @return
     */
    @ApiLog("删除职务")
    @PreAuthorize ("hasAuthority('job:position:del')")
    @DeleteMapping("delete")
    public ResponseEntity delete(String ids,HttpServletRequest request) {
        List<PositionLogDTO> positionLogDTOList = new ArrayList<>();
        String idArray[] =ids.split(",");
        List<Position> positions = positionService.listByIds(Lists.newArrayList(idArray));
        positions.stream().forEach(item->{
            PositionLogDTO positionLogDTO = new PositionLogDTO();
            positionLogDTO.setType(PositionTypeEnum.POSITION.getValue());
            positionLogDTO.setOperationType("删除职务");
            positionLogDTO.setOperationContent("删除职务: "+item.getName());
            positionLogDTOList.add(positionLogDTO);
        });
        try{
            positionService.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 positionDTOList
     * @return
     */
    @ApiLog("修改职务分类顺序")
    @PreAuthorize("hasAnyAuthority('job:position:view')")
    @PostMapping("updateSort")
    public ResponseEntity updateSortById(@RequestBody List<PositionDTO> positionDTOList) {
        positionService.updateSortByIdList(positionDTOList);
        return ResponseEntity.ok ("保存职务排序成功");
    }
}
