package cn.palmte.work.controller.backend;

import cn.palmte.work.bean.Constant;
import cn.palmte.work.bean.ResponseMsg;
import cn.palmte.work.model.SysRole;
import cn.palmte.work.pojo.PermissionNode;
import cn.palmte.work.pojo.RoleBean;
import cn.palmte.work.service.AdminService;
import cn.palmte.work.service.SysRoleService;
import cn.palmte.work.utils.InterfaceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 角色管理
 * @author nsp
 */
@Controller
@RequestMapping("/role")
public class SysRoleController extends BaseController{

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private AdminService adminService;

    private static final Logger logger = LoggerFactory.getLogger(SysRoleController.class);
    private static final int[]  ROLE_TYPE_ARRAY  = new int[] { Constant.ROLE_TYPE_CMCC_ADMIN,Constant.ROLE_TYPE_ZJPT_ADMIN};

    @RequestMapping("/list")
    public String list(@RequestParam(value = "keywords",required = false) String keywords,
                       @RequestParam(value = PAGE_NUMBER, defaultValue = DEFAULT_PAGE_NUMBER) int pageNumber,
                       @RequestParam(value = PAGE_SIZE, defaultValue = DEFAULT_PAGE_SIZE) int pageSize,
                       Map<String, Object> model) {
        logger.info("获取角色列表");
        //当前登录人的角色类型
        model.put("keywords",keywords);
        SysRole adminSysRole=adminService.getRole(InterfaceUtil.getAdminId()+"");
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo(keywords,model);
        model.put("pager",sysRoleService.list(searchInfo,pageNumber,pageSize));
        return "admin/role_list";
    }

    @GetMapping(value = "/add")
    public String add( Map<String, Object> model){
        //当前登录人的角色
        SysRole adminSysRole=adminService.getRole(InterfaceUtil.getAdminId()+"");
        PermissionNode root= sysRoleService.getPermissionNodeTree(adminSysRole.getId());
        List<RoleBean> roleLevels = getRoleLevels(adminSysRole.getId(), 0);
        List<RoleBean> roleTypes = getRoleTypes(adminSysRole.getId(), adminSysRole.getType(),0);
        SysRole role = new SysRole();
        model.put("permnode",root);
        model.put("roleID",-1);
        model.put("isActive",1);
        model.put("level",roleLevels);//默认 省级
        model.put("type",roleTypes);//角色类型
        model.put("role",role);
        //model.put("selectedType",roleLevels.get(0).getValue());

        return "/admin/role_input";
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam(value = "id")int id, Map<String, Object> model){
        //当前登录人的角色
        SysRole adminSysRole=adminService.getRole(InterfaceUtil.getAdminId()+"");
        SysRole role = sysRoleService.fingSysRoleById(id);
        PermissionNode root = sysRoleService.getPermissionNodeTreeForEdit(adminSysRole.getId(), id);
        List<RoleBean> roleLevels = getRoleLevels(adminSysRole.getId(), role.getLevel());
        List<RoleBean> roleTypes = getRoleTypes(adminSysRole.getId(),adminSysRole.getType(), role.getType());
        model.put("permnode",root);
        model.put("roleID",id);
        model.put("roleName",role.getName());
        model.put("level",roleLevels);
        model.put("type",roleTypes);
        //model.put("selectedType",role.getType());
        model.put("role",role);
        return "admin/role_input";
    }

    @RequestMapping("/save")
    public String save(@RequestParam Map<String, Object> reqMap,@RequestParam(value = "roleID")int roleID
                     ) {
        logger.info("新增编辑保存,roleID="+roleID);
        sysRoleService.addOrUpdatePermission(reqMap,roleID);
        return "redirect:/role/list";
    }

    @RequestMapping("/check")
    @ResponseBody
    public ResponseMsg check(@RequestParam(value = "role_id")String role_id, @RequestParam(value = "role_name")String role_name,
                             HttpServletResponse response) throws Exception{
        int result=sysRoleService.cheakRoleName(Integer.parseInt(role_id),role_name);
        ResponseMsg responseMsg=new ResponseMsg();
        if (result>0){
            responseMsg.setStatus(0);
            responseMsg.setMsg("该角色名已存在,请重新输入！");
        }else {
            responseMsg.setStatus(1);
            responseMsg.setMsg("");
        }
        return responseMsg;
    }


    @GetMapping(value = "/delete")
    @ResponseBody
    public ResponseMsg delete(@RequestParam("ids") String ids){
        ResponseMsg responseMsge=new ResponseMsg();
        if ("".equals(ids)){
            responseMsge.setStatus(1);
            responseMsge.setMsg("删除失败，无选中项！");
        }else {
            String[] deleteIds=ids.split("#%#");
            String msg = sysRoleService.deleteSelectedPermission(deleteIds);
            responseMsge.setStatus(0);
            responseMsge.setMsg(msg);
        }
        return responseMsge;
    }




    /**
     * @Title: 根据当前管理员所属角色的等级，获取角色等级列表
     * @Description:角色等级(省级1>地级市级2>区县级3>网点级4),获取角色等级列表时，只能获取级别小于等于当前级别的
     * @param adminRoleId
     *            当前管理员角色ID
     * @param selectedLevel
     *            默认选中等级
     * @return List<PermissionLevel>
     */
    private List<RoleBean> getRoleLevels(int adminRoleId, int selectedLevel){
        SysRole role = sysRoleService.fingSysRoleById(adminRoleId);
        int adminLevel = role.getLevel();
        if(selectedLevel == 0){
            selectedLevel = adminLevel;
        }
        List<RoleBean> roleLevels = new ArrayList<RoleBean>(3);
        for(int i = adminLevel; i <= 3; i++){
            String name = getRoleLevelName(i);
            if(null != name){
                RoleBean permissionLevel = new RoleBean(name, i);
                if(selectedLevel == i){
                    permissionLevel.setSelected(true);
                }
                roleLevels.add(permissionLevel);
            }
        }
        return roleLevels;
    }


    /**
     * 获取角色类型列表
     * @param adminRoleId
     * @param selectedType
     * @return
     */
    private List<RoleBean> getRoleTypes(int adminRoleId,int adminRoleType, int selectedType){
        SysRole role = sysRoleService.fingSysRoleById(adminRoleId);
        int roleType = role.getType();
        if(selectedType == 0){
            selectedType = roleType;
        }
        List<RoleBean> roleLevels = new ArrayList<RoleBean>(4);
        for(int i = 0; i < ROLE_TYPE_ARRAY.length; i++){
            if (adminRoleType<ROLE_TYPE_ARRAY[i]){
                String name = getRoleTypeName(ROLE_TYPE_ARRAY[i]);
                if(null != name){
                    RoleBean roleTypeBean = new RoleBean(name, ROLE_TYPE_ARRAY[i]);
                    if(selectedType == ROLE_TYPE_ARRAY[i]){
                        roleTypeBean.setSelected(true);
                    }
                    roleLevels.add(roleTypeBean);
                }
            }
        }
        return roleLevels;
    }



    /**
     * 目前末梢渠道中默认都为省级
     * 根据type值获取角色类型名称
     * @param type
     * @return
     */
    private String getRoleTypeName(int type){
        String typeName = null;
        switch(type){
            case Constant.ROLE_TYPE_CMCC_ADMIN:
                typeName = "移动管理员";
                break;
            case Constant.ROLE_TYPE_ZJPT_ADMIN:
                typeName = "资金平台管理员";
                break;
            default:typeName = null;
        }
        return typeName;
    }


    /**
     * 根据Level值获取角色等级名称
     * @param level
     * @return
     */
    private String getRoleLevelName(int level){
        String levelName = null;
        switch(level){
            case 1:
                levelName = "省级";
                break;
            /*case 2:
                levelName = "地市级";
                break;
            case 3:
                levelName = "区县级";
                break;
            case 4:
                levelName = "网点级";
                break;*/
            default:levelName = null;
        }
        return levelName;
    }

    /**
     * 启用 禁用
     */
    @RequestMapping("/enableOrDisable")
    @ResponseBody
    public ResponseMsg enableOrDisable(@RequestParam("id") int id,
                                       @RequestParam("enabled") int status, RedirectAttributes attr) {
        boolean isSuccess = false;
        try {
            isSuccess = sysRoleService.enableOrDisable(status, id);
        } catch (Exception e) {
            e.getMessage();
        }
        if (isSuccess) {
            return ResponseMsg.buildSuccessMsg("操作成功");
        } else {
            return ResponseMsg.buildSuccessMsg("操作失败");
        }
    }

}
