/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package easydo.technology.system.rest;

import easydo.technology.annotation.WebLog;
import easydo.technology.exception.BadRequestException;
import easydo.technology.system.domain.Role;
import easydo.technology.system.dto.RoleDto;
import easydo.technology.system.dto.RoleQueryParam;
import easydo.technology.system.dto.RoleSmallDto;
import easydo.technology.system.service.RoleService;
import easydo.technology.utils.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/roles")
public class RoleController {

    private final RoleService roleService;

    private static final String ENTITY_NAME = "role";

    @WebLog
    @GetMapping(value = "/{id}")
    public ResponseEntity<Object> query(@PathVariable Long id) {
        return new ResponseEntity<>(roleService.findById(id), HttpStatus.OK);
    }

    @WebLog
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, RoleQueryParam criteria) throws IOException {
        roleService.download(roleService.queryAll(criteria), response);
    }

    @WebLog
    @GetMapping(value = "/all")
    public ResponseEntity<Object> query() {
        return new ResponseEntity<>(roleService.queryAll(), HttpStatus.OK);
    }

    @WebLog
    @GetMapping
    public ResponseEntity<Object> query(RoleQueryParam criteria, Pageable pageable) {
        return new ResponseEntity<>(roleService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @WebLog
    @GetMapping(value = "/level")
    public ResponseEntity<Object> getLevel() {
        Map<String, Object> map = new HashMap<>();
        map.put("level", getLevels(null));
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @WebLog
    @PostMapping
    public ResponseEntity<Object> create(@Validated @RequestBody RoleDto resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        getLevels(resources.getLevel());
        roleService.save(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @WebLog
    @PutMapping
    public ResponseEntity<Object> update(@Validated(Role.Update.class) @RequestBody RoleDto resources) {
        getLevels(resources.getLevel());
        roleService.updateById(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @WebLog
    @PutMapping(value = "/menu")
    public ResponseEntity<Object> updateMenu(@RequestBody RoleDto resources) {
        RoleDto role = roleService.findById(resources.getId());
        getLevels(role.getLevel());
        roleService.updateMenu(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @WebLog
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
        for (Long id : ids) {
            RoleDto role = roleService.findById(id);
            getLevels(role.getLevel());
        }
        // 验证是否被用户关联
        roleService.verification(ids);
        roleService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 获取用户的角色级别
     * 
     * @return /
     */
    private int getLevels(Integer level) {
        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream()
                .map(RoleSmallDto::getLevel).collect(Collectors.toList());
        int min = Collections.min(levels);
        if (level != null) {
            if (level < min) {
                throw new BadRequestException("权限不足，你的角色级别：" + min + "，低于操作的角色级别：" + level);
            }
        }
        return min;
    }
}
