package com.tykj.dev.device.user.subject.controller;

import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.user.base.ret.RoleVo;
import com.tykj.dev.device.user.subject.entity.Role;
import com.tykj.dev.device.user.subject.entity.RolePermissions;
import com.tykj.dev.device.user.subject.service.RolePermissionsService;
import com.tykj.dev.device.user.subject.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName RoleController.java
 * @Description TODO
 * @createTime 2020年07月28日 09:03:00
 */
@RestController
@AutoDocument
@Api(tags = "角色模块", description = "提供角色相关的接口")
@RequestMapping("/sys/role")
public class RoleController {

    @Autowired
    RoleService roleService;

    @Autowired
    RolePermissionsService rolePermissionsService;

    @PostMapping(value = "/save")
    @ApiOperation(value = "角色添加和修改接口，新增不需要传id，修改必须传id", notes = "成功返回角色对象")
    public ResponseEntity addRole(@RequestBody RoleVo roleVo) {
        Role role = roleService.save(roleVo.toDo());
        if (rolePermissionsService.findAllByRoleId(role.getRoleId()).size() != 0) {
            rolePermissionsService.deleteFindRoleId(role.getRoleId());

        }
        List<Integer> list = roleVo.getPermissionsIds();
        if (list != null && list.size() != 0) {
            list.forEach(integer -> {
                rolePermissionsService.save(new RolePermissions(null, role.getRoleId(), integer));
            });

        }
        return ResponseEntity.ok(role);
    }


    @GetMapping(value = "/detail/{roleId}")
    @ApiOperation(value = "查询角色详情", notes = "成功返回角色对象")
    public ResponseEntity selectPage(@PathVariable Integer roleId) {

        return ResponseEntity.ok(roleService.findById(roleId));
    }


    @GetMapping(value = "/summary/page/{page}/{size}")
    @ApiOperation(value = "查询角色列表", notes = "成功返回角色对象")
    public ResponseEntity selectPage(@PathVariable Integer page, @PathVariable Integer size) {

        return ResponseEntity.ok(roleService.findByUserRolePage(page, size));
    }

}
