package com.pqs9900.controller.user;

import com.njcn.mapper.user.PermissionMapper;
import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.ZtreePojo;
import com.njcn.pojo.user.Permission;
import com.njcn.pojo.user.PermissionTree;
import com.njcn.service.log.UserLogDetailService;
import com.njcn.service.user.IPermissionService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import org.apache.commons.lang3.StringUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

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


@RequestMapping(value = "permission")
@Controller
public class PermissionController {

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

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    UserLogDetailService userLogDetailService;

    /**
     * 资源列表树
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "getTree", method = RequestMethod.POST)
    @ResponseBody
    public List<PermissionTree> getTree(HttpServletRequest request, HttpSession session) {
        List<PermissionTree> result = new ArrayList();
        result = permissionService.getTreeData();

        return result;
    }

    /**
     * 加载一级节点
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "getfirst", method = RequestMethod.POST)
    @ResponseBody
    public List<Permission> getfirst(HttpServletRequest request, HttpSession session) {
        List<Permission> result = new ArrayList();
        Permission tmp = new Permission();
        tmp.setParentNode(0);
        tmp.setSysType(TokenManager.getSysType());
        result = permissionMapper.select(tmp);

        return result;
    }

    /**
     * 加载二级节点
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "getsecond", method = RequestMethod.POST)
    @ResponseBody
    public List<Permission> getsecond(HttpServletRequest request, HttpSession session, Integer first) {
        List<Permission> result;
        Permission tmp = new Permission();
        try{
            tmp.setParentNode(first);
            tmp.setSysType(TokenManager.getSysType());
            result = permissionMapper.select(tmp);
            return result;
        }catch(Exception e){
            return new ArrayList<>();
        }

    }


    /**
     * 加载资源信息
     *
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "getInfo", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getInfo(HttpServletRequest request, HttpSession session, Integer index) {
        HttpResult result = new HttpResult();
        List<List> datalist;
        if (index == 0) {
            try {
                datalist = permissionService.getAllData();
                if (datalist.isEmpty()) {
                    result.setCode(500);
                    result.setMessage("没有配置信息");
                    logger.error("获取配置项信息失败");
                } else {
                    result.setCode(200);
                    result.setMessage("获取配置信息成功");
                    result.setBody(datalist);
                    logger.info("获取配置项信息成功");
                }
            } catch (Exception e) {
                logger.error("获取数据异常，异常为" + e.toString());
                result = PubUtils.assignmentResult(null, 500, "获取数据失败");
            }
        } else {
            try {
                datalist = permissionService.getData(index);
                if (datalist.isEmpty()) {
                    result.setCode(500);
                    result.setMessage("没有配置信息");
                    logger.error("获取配置项信息失败");
                } else {
                    result.setCode(200);
                    result.setMessage("获取配置信息成功");
                    result.setBody(datalist);
                    logger.info("获取配置项信息成功");
                }
            } catch (Exception e) {
                logger.error("获取数据异常，异常为" + e.toString());
                result = PubUtils.assignmentResult(null, 500, "获取数据失败");
            }

        }

        return result;
    }

    /**
     * 删除用户选择的资源
     */
    @RequestMapping(value = "deletePermission", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult deletePermission(HttpServletRequest request, String functionIndex) {
        HttpResult result = new HttpResult();
        try {
            String message = permissionService.deleteByIndex(functionIndex);
            if (message.equalsIgnoreCase("该资源下还有子资源，删除失败")) {
                result.setCode(500);
                result.setMessage(message);
            } else if (message.equalsIgnoreCase("并未找到该资源，删除失败")) {
                result.setCode(100);
                result.setMessage(message);
            } else if (message.equalsIgnoreCase("删除失败")) {
                result.setCode(300);
                result.setMessage(message);
            } else {
                result.setCode(200);
                result.setMessage(message);
            }
        } catch (Exception e) {
            logger.error("删除数据异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "删除数据失败");
        }
        return result;
    }


    /**
     * 新增资源
     */
    @RequestMapping(value = "addPermission", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult addPermission(HttpServletRequest request, String description, String name, String path, Integer first, Integer second) {
        HttpResult result = new HttpResult();
        if (StringUtils.isBlank(description)) {
            description = "暂无描述";
        }
        try {
            String message = permissionService.savePermission(description, name, path, first, second);
            if (message.equalsIgnoreCase("新增资源成功")) {
                result.setCode(200);
                result.setMessage(message);
            } else {
                result.setCode(500);
                result.setMessage(message);
            }
        } catch (Exception e) {
            logger.error("新增资源异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "新增资源失败");
        }
        return result;
    }

    /**
     * 回显角色信息以及拥有的资源
     */
    @RequestMapping(value = "getRolePermission", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getRolePermission(HttpServletRequest request) {
        HttpResult result = new HttpResult();
        try{
            List<List> permissionList = permissionService.getRolePermission();
            if (permissionList.isEmpty()) {
                result.setMessage("获取角色信息失败");
                result.setCode(500);
            } else {
                result.setCode(200);
                result.setMessage("获取角色信息成功");
                result.setBody(permissionList);
            }
        }catch (Exception e){
            logger.error("回显角色信息异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "回显角色信息失败");
        }
        return result;
    }

    /**
     * 根据角色获取其拥有的资源
     */
    @RequestMapping(value = "getPermissions", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult getPermissions(HttpServletRequest request, String roleIndex) {
        HttpResult result = new HttpResult();
        try {
            List<ZtreePojo> listsZ = permissionService.getPermissions(roleIndex);
            if (listsZ.isEmpty()) {
                result.setMessage("获取已配置资源失败");
                result.setCode(500);
            } else {
                result.setCode(200);
                result.setMessage("获取已配置资源成功");
                result.setBody(listsZ);
            }
        }catch (Exception e){
            logger.error("获取已配置资源异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取已配置资源失败");
        }
        return result;
    }

    /**
     * 根据角色获取其拥有的资源提供给用户重新分配
     */
    @RequestMapping(value = "destributePermission", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult destributePermission(HttpServletRequest request, String roleIndex) {
        HttpResult result = new HttpResult();
        try {
            List<ZtreePojo> listsZ = permissionService.destributePermission(roleIndex);
            result.setCode(200);
            result.setMessage("获取已配置资源成功");
            result.setBody(listsZ);
        }catch (Exception e){
            logger.error("获取已配置资源异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "获取已配置资源失败");
        }
        return result;
    }

    /**
     * 根据角色索引，分配资源
     */
    @RequestMapping(value = "disPer", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult disPer(HttpServletRequest request, String roleIndex, String permissionIndex) {
        HttpResult result = new HttpResult();
        try{
            String message = permissionService.disPer(roleIndex, permissionIndex);
            if (message.equalsIgnoreCase("重新分配资源成功")) {
                result.setCode(200);
                result.setMessage("重新分配资源成功");
            } else {
                result.setCode(500);
                result.setMessage("重新分配资源失败");
            }
        }catch (Exception e){
            logger.error("重新分配资源异常，异常为" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "重新分配资源失败");
        }

        return result;
    }


}

