package com.fjs.scenic.controller.system;

import com.fjs.scenic.controller.common.BaseController;
import com.fjs.scenic.entity.system.Role;
import com.fjs.scenic.entity.system.RolePermission;
import com.fjs.scenic.service.system.RolePermissionService;
import com.fjs.scenic.service.system.RoleService;
import com.fjs.scenic.service.system.impl.RoleServiceImpl;
import com.fjs.scenic.utils.ReturnResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/role")
public class RoleController extends BaseController<Role> {

    @Autowired
    private RoleService roleService;

    @Autowired
    private RolePermissionService rolePermissionService;

    @GetMapping("/index")
    public ModelAndView sceniclist(HttpSession session) {
        return new ModelAndView("/system/role");
    }

    @GetMapping("/getAll")
    public ReturnResult getAll(){
        return ReturnResult.ok(roleService.getAll());
    }

    @PostMapping("/addRole")
    public ReturnResult addRole( String pids , Role role) {
        List<RolePermission>  rolePermissionList = new ArrayList<>();
        roleService.add(role);
        for(String permissionId: pids.split(",")){
            RolePermission rolePermission = new RolePermission(role.getId(),Integer.parseInt(permissionId));
            rolePermissionList.add(rolePermission);
        }
        return ReturnResult.ok(rolePermissionService.adds(rolePermissionList));
    }

    @PostMapping("/updateRole")
    public ReturnResult updateRole( String pids , Role role) {
        List<RolePermission>  rolePermissionList = new ArrayList<>();
        roleService.update(role);
        for(String permissionId: pids.split(",")){
            RolePermission rolePermission = new RolePermission(role.getId(),Integer.parseInt(permissionId));
            rolePermissionList.add(rolePermission);
        }
        return ReturnResult.ok(rolePermissionService.updates(rolePermissionList));
    }

    @GetMapping("/selectByRoleId/{id}")
    public ReturnResult selectByRoleId(@PathVariable("id") Integer id) {
        return ReturnResult.ok(rolePermissionService.selectByRoleId(id));
    }

    @PostMapping("/dels")
    public ReturnResult dels(int id) {
        roleService.del(id);
        return ReturnResult.ok(rolePermissionService.delByRoleId(id));
    }
}
