package com.lightinit.hsdataplatformresdir.controller.admin;

import com.lightinit.hsdataplatformresdir.common.RoleModulesUtilsPro;
import com.lightinit.hsdataplatformresdir.dictionary.DicResourceState;
import com.lightinit.hsdataplatformresdir.entity.BaseExample;
import com.lightinit.hsdataplatformresdir.entity.RoleModule;
import com.lightinit.hsdataplatformresdir.entity.SentryRole;
import com.lightinit.hsdataplatformresdir.entity.SentryRoleAction;
import com.lightinit.hsdataplatformresdir.model.ResultState;
import com.lightinit.hsdataplatformresdir.model.ResultStateCode;
import com.lightinit.hsdataplatformresdir.model.admin.*;
import com.lightinit.hsdataplatformresdir.service.IRoleService;
import com.lightinit.hsdataplatformresdir.service.IShiroPermissionsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author WangYao
 * @date 2018/6/21 13:30
 * @description 角色管理控制器
 */
@Controller
@RequestMapping("/admin/role_mgr")
public class RoleMgrController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(RoleMgrController.class);

    @Autowired
    private IRoleService roleService;
    @Autowired
    private RoleModulesUtilsPro roleModulesUtilsPro;
    @Autowired
    private IShiroPermissionsService shiroPermissionsService;

    @RequestMapping(value = "index.htm")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("admin/role_mgr/index");
        modelAndView.addObject("dicResourceState", DicResourceState.getInstacne().getDicMap());
        return modelAndView;
    }

    @RequestMapping(value = "list.action")
    public ModelAndView list(@RequestParam(defaultValue = "1") int pageNo) {
        ModelAndView modelAndView = new ModelAndView("admin/role_mgr/list");
        BaseExample.Page pager = new BaseExample.Page(pageNo, 10);
        List<SentryRole> outputModel = roleService.QueryList(pager.getPageNo(), pager.getPageSize(),null);
        pager.setTotal(roleService.QueryCount(null));
        modelAndView.addObject("list", outputModel);
        modelAndView.addObject("pager", pager);
        return modelAndView;
    }

    @RequestMapping(value = "add.htm")
    public ModelAndView add(){
        ModelAndView modelAndView = new ModelAndView("admin/role_mgr/add");
        return modelAndView;
    }

    @RequestMapping(value = "add.action")
    @ResponseBody
    public ResultState doAdd(HttpSession session, @Valid RoleMgrDataModel inputModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        if (roleService.IsExitsRole(inputModel.getRolecode())) {
            return buildInvalidResultState(ResultStateCode.INVALID_DATA, "角色代码已存在");
        }
        SentryRole sentryRole = new SentryRole();
        BeanUtils.copyProperties(inputModel, sentryRole);
        sentryRole.setAddtiime(new Date());
        boolean success = roleService.InsertRole(sentryRole);
        ResultState resultState = new ResultState();
        if (!success){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("添加角色失败");
        }

        return resultState;
    }

    @RequestMapping(value = "edit.htm/{id}")
    public ModelAndView edit(@PathVariable long id){
        SentryRole busiModel = roleService.QueryOne(id);
        if(busiModel == null){
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("admin/role_mgr/edit");
        modelAndView.addObject("busiModel", busiModel);
        return modelAndView;
    }

    @RequestMapping(value = "edit.action")
    @ResponseBody
    public ResultState doEdit(@Valid RoleMgrDataModel inputModel, BindingResult bindingResult){
        if (bindingResult.hasErrors()){
            return getAllFieldInvalidResultState(inputModel, bindingResult);
        }
        SentryRole role = roleService.QueryOne(inputModel.getId());
        if(role == null){
            return buildInvalidResultState(ResultStateCode.INVALID_DATA, "当前角色不存在");
        }
        role.setParentid(inputModel.getParentid());
        role.setRolecode(inputModel.getRolecode().toLowerCase());
        role.setRolename(inputModel.getRolename());
        boolean success = roleService.UpdateRole(role);
        ResultState resultState = new ResultState();
        if (!success){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("编辑角色失败");
        }
        return resultState;
    }

    @RequestMapping(value = "auth.htm/{id}")
    public ModelAndView auth(@PathVariable long id){
        SentryRole busiModel = roleService.QueryOne(id);
        if(busiModel == null){
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("admin/role_mgr/auth");
        modelAndView.addObject("busiModel", busiModel);
        List<RoleModule> roleModuleList = roleService.QueryModuleList(id);
        modelAndView.addObject("selectedModuleList", roleModuleList);
        SentryRole role = roleService.QueryOne(id);
        List<String> roleCodeList = new ArrayList<>();
        roleCodeList.add(role.getRolecode());
        List<SentryRoleAction> selectedActionList = shiroPermissionsService.selectSentryRoleAction(roleCodeList);
        modelAndView.addObject("selectedActionList", selectedActionList);
        return modelAndView;
    }

    @RequestMapping(value = "auth.action")
    @ResponseBody
    public ResultState doAuth(@RequestBody RoleMgrModuleDataModel inputModel){
        if (inputModel == null || inputModel.getRoleId() == null || inputModel.getRoleId() <= 0){
            return buildInvalidResultState(ResultStateCode.INVALID_DATA, "参数错误");
        }
        SentryRole role = roleService.QueryOne(inputModel.getRoleId());
        if(role == null){
            return buildInvalidResultState(ResultStateCode.INVALID_DATA, "当前角色不存在");
        }
        boolean success = roleService.SaveRoleModule(inputModel.getRoleId(), inputModel.getSelectedModuleIds(), inputModel.getSelectedActionIds());
        ResultState resultState = new ResultState();
        if (!success){
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("授权失败");
        }
        return resultState;
    }

    @RequestMapping(value = "delete.action/{id}")
    @ResponseBody
    public ResultState delete(@PathVariable long id){
        ResultState<Long> resultState = new ResultState<>();
        boolean success=false;
        if (id > 0) {
            SentryRole item = roleService.QueryOne(id);
            if(item == null){
                resultState.setStateCode(ResultStateCode.INVALID_DATA);
                resultState.setMsg("当前角色已不存在");
            }else if(item.getChildren()!=null && item.getChildren().size()>0){
                resultState.setStateCode(ResultStateCode.INVALID_DATA);
                resultState.setMsg("角色【"+item.getRolename()+"】还有子角色，当前角色不能删除");
            }else {
                List<Long> roleIds=roleModulesUtilsPro.RoleIds(item);
                if(roleIds.size()==0){
                    resultState.setStateCode(ResultStateCode.INVALID_DATA);
                    resultState.setMsg("参数错误");
                }else {
                    if (roleService.CheckRoleHasModules(roleIds)) {
                        resultState.setStateCode(ResultStateCode.INVALID_DATA);
                        resultState.setMsg("角色【"+item.getRolename()+"】已经分配权限，当前角色不能删除");
                    }else if (roleService.CheckRoleHasUser(roleIds)) {
                        resultState.setStateCode(ResultStateCode.INVALID_DATA);
                        resultState.setMsg("角色【"+item.getRolename()+"】已经分配用户，当前角色不能删除");
                    }else{
                        if(roleService.DeleteRole(id)){
                            /*resultState.setStateCode(ResultStateCode.SUCCESS);
                            resultState.setMsg("角色【"+item.getRolename()+"】删除成功");*/
                        }else{
                            resultState.setStateCode(ResultStateCode.INVALID_DATA);
                            resultState.setMsg("角色【"+item.getRolename()+"】删除失败");
                        }
                    }
                }
            }
        } else {
            resultState.setStateCode(ResultStateCode.INVALID_DATA);
            resultState.setMsg("参数错误");
        }
        return resultState;
    }

}
