package com.controller;

import com.alibaba.fastjson.JSON;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.kit.HttpKit;
import com.model.Role;
import com.model.RoleUser;
import com.model.User;
import com.service.RoleService;
import com.service.UserService;
import com.tools.JwtUtils;
import com.validator.UserValidator;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ControllerInterface(path="/role")
public class RoleController extends BaseController {

    RoleService service = RoleService.me;

    public void index() {
        render("/view/userrole/role.html");
    }

    public void viewUserRole(){
        int userid =getParaToInt("userid");
        render("/view/userrole/viewuserrole.html");
    }

    public void findRoleByUser(){
        int userid =getParaToInt("userid");
        success(service.findRoleByUser(userid));
    }

    public void findNoOwnerRoleByUser(){
        int userid =getParaToInt("userid");
        success(service.findNoOwnerRoleByUser(userid));
    }

    public void addUserRole(){
        try{
            int userid = getParaToInt("userid");
            String rolejson = getPara("role");
            List<Role> roleList=  JSON.parseArray(rolejson, Role.class);
            List<RoleUser> roleUserList =new ArrayList<RoleUser>();
            for (Role role : roleList) {
                RoleUser roleUser = new RoleUser();
                roleUser.setUserid(userid);
                roleUser.setRoleid(role.getId());
                roleUserList.add(roleUser);
            }
            service.addUserRole(roleUserList);
            success();
        }catch (Exception e){
            fail();
        }
    }

    public void delUserRole(){
        try {
            int id = getParaToInt("id");
            service.delUserRole(id);
            success();
        }catch (Exception e) {
            fail();
        }
    }



    public void findRole(){
        success(service.findRole());
    }



    public void addOrUpdate(){
        Role role = getBean(Role.class,"bean");
        User user= getSessionAttr("userInfo");
        int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        role.setOperatorid(operatorid).setOrgid(user.getOrgid());
        service.addOrUpdate(role);
        success();
    }


    public void delRole(){
        try {
            int id = getParaToInt("id");

            if (service.roleHaveUser(id)){
                throw new Exception("请先删除该角色关联的用户");
            }
            if (service.roleHaveMenu(id)){
                throw new Exception("请先删除该角色关联的菜单");
            }
            service.delRole(id);
            success();
        }catch (Exception e) {
            fail(0,e.getMessage());
        }
    }


}
