package com.wb.permission.domain;

import com.alibaba.fastjson.JSON;
import com.wb.common.WbComUtil;
import com.wb.permission.pojo.*;
import com.wb.util.SysUtil;
import com.wb.util.WebUtil;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* Description:权限
* Author: wangll
* Version: 1.0
* Create Date: 2020-03-05 11:33:48
*/
@Component
public class PermissionService {
    /**
     * 部门
     */
    @Autowired
    WbDeptBO wbDeptBO;
    /**
     * 组
     */
    @Autowired
    WbGroupResourceBO wbGroupResourceBO;
    /**
     * 用户
     */
    @Autowired
    WbUserBO wbUserBO;
    /**
     * 角色
     */
    @Autowired
    WbRoleBO wbRoleBO;
    /**
     * 用户与角色关系
     */
    @Autowired
    WbUserRoleBO wbUserRoleBO;
    /**
     * 菜单
     */
    @Autowired
    WbMenuBO wbMenuBO;
    /**
     * 菜单按钮
     */
    @Autowired
    WbMenuResBO wbMenuResBO;
    /**
     *租户信息
     */
    @Autowired
    WbTenancyBO wbTenancyBO;
    /**
     *角色菜单
     */
    @Autowired
    WbRoleResourceBO wbRoleResourceBO;

    /**
     * 图标数组
     */
    static String[] iconarr={"fa-home","fa-laptop","fa-book","fa-cogs","fa-bullhorn","fa-envelope","fa-tasks","fa-bar-chart-o","fa-th-list","fa-map-marker","fa-file-text"};

    /**
    * Description:部门保存方法
    * @param object
    * @param response
    * @param request
    * @return Note: Nothing much.
    */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbDeptMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        WbDept wbDept = JSON.parseObject(object.getString("wbDeptData"), WbDept.class);
        //设置创建人时间等相关信息
        WbComUtil.setParameterValue(wbDept,request);

        //调用保存方法
        wbDeptBO.save(wbDept);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:部门删除方法
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbDeptMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        String deptIds = request.getParameter("deptIds");
        //调用保存方法
        wbDeptBO.delWbDeptByDeptIds(deptIds);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:保存组于组之间关系
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbGroupMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        List<WbGroupResource> groupResourceList = wbGroupResourceBO.proWbGroup(request);
        if (StringUtils.isEmpty(groupResourceList) || groupResourceList.size()<1){
            return;
        }
        String tenancyId = (String) request.getSession().getAttribute("sys.tenancyId");
        String groupCode = request.getParameter("groupCode");
        wbGroupResourceBO.delWbGroupResourceByGroupCode(tenancyId,groupCode,null);
        for (WbGroupResource wbGroupResource:groupResourceList) {
            wbGroupResourceBO.save(wbGroupResource);
        }
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除组于组之间关系
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbGroupMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        List<WbGroupResource> groupResourceList = wbGroupResourceBO.proWbGroup(request);
        if (StringUtils.isEmpty(groupResourceList) || groupResourceList.size()<1){
            return;
        }
        for (WbGroupResource wbGroupResource:groupResourceList) {
            String tenancyId = wbGroupResource.getTenancyId();
            String groupCode = wbGroupResource.getGroupCode();
            String relationGroupCode = wbGroupResource.getRelationGroupCode();
            wbGroupResourceBO.delWbGroupResourceByGroupCode(tenancyId,groupCode,relationGroupCode);
        }
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:保存用户信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbUserMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        WbUser wbUser = JSON.parseObject(object.getString("wbUserData"), WbUser.class);
        //设置创建人时间等相关信息
        WbComUtil.setParameterValue(wbUser, request);
        String result = null;
        //查询判断用户是否存在
        List wbUserList = wbUserBO.listWbUser(wbUser);
        if (StringUtils.isEmpty(wbUserList) || wbUserList.size()==0) {
            //调用保存方法
            wbUserBO.save(wbUser);
            //处理用户角色关系
            wbUserRoleBO.deleteByUserId(wbUser.getTenancyId(), wbUser.getUserId());
            List<WbUserRole> wbUserRoleList = wbUserRoleBO.proWbUserRole(request,wbUser.getTenancyId(), wbUser.getUserId());
            for (WbUserRole wbUserRole : wbUserRoleList) {
                wbUserRoleBO.insert(wbUserRole);
            }
            result = "1";
        }else{
            result = "2";
        }
        try {
            WebUtil.send(response,result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除组于组之间关系
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbUserMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        String userId = request.getParameter("userId");
        String tenancyId = request.getParameter("tenancyId");
        wbUserRoleBO.deleteByUserId(tenancyId,userId);
        wbUserBO.delete(userId);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:保存角色信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbRoleMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        WbRole wbRole = JSON.parseObject(object.getString("wbRoleData"), WbRole.class);
        //设置创建人时间等相关信息
        WbComUtil.setParameterValue(wbRole,request);
        String type = request.getParameter("type");
        //调用保存方法
        wbRoleBO.save(wbRole,type);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除角色信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbRoleMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
       String roleId = request.getParameter("roleId");
        wbRoleBO.delete(roleId);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除角色信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void grantWbMenuMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        String newTenancyId = request.getParameter("newTenancyId");
        String oldTenancyId = request.getParameter("oldTenancyId");
        String menuId = request.getParameter("menuId");
        //调用保存方法
        List<WbMenu> listMenu = wbMenuBO.selectGrantMenu(oldTenancyId,menuId);
        for (WbMenu wbMenu:listMenu){
            wbMenu.setId(SysUtil.getId());
            wbMenu.setTenancyId(newTenancyId);
            WbComUtil.setParameterValue(wbMenu,request,true);
            wbMenuBO.insertMenu(wbMenu);
        }
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除角色信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbMenuMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        WbMenu wbMenu = JSON.parseObject(object.getString("wbMenuData"), WbMenu.class);
        //设置创建人时间等相关信息
        WbComUtil.setParameterValue(wbMenu,request);
        //调用保存方法
        wbMenuBO.save(wbMenu);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除菜单信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbMenuMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        String id = request.getParameter("id");
        String tenancyId = request.getParameter("tenancyId");
        //菜单按钮
        wbMenuResBO.deleteByMenuId(tenancyId,id);
        //菜单
        wbMenuBO.delete(id);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除角色信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbMenuResMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        List<WbMenuRes> createList = WbComUtil.getBeanlist(object, "WbMenuResTable", "create", WbMenuRes.class);
        List<WbMenuRes> updateList = WbComUtil.getBeanlist(object, "WbMenuResTable", "update", WbMenuRes.class);
        List<WbMenuRes> destroyList = WbComUtil.getBeanlist(object, "WbMenuResTable", "destroy", WbMenuRes.class);
        for (WbMenuRes wbMenuRes:createList){
            WbComUtil.setParameterValue(wbMenuRes,request);
            wbMenuResBO.insert(wbMenuRes);
        }
        for (WbMenuRes wbMenuRes:updateList){
            WbComUtil.setParameterValue(wbMenuRes,request);
            wbMenuResBO.update(wbMenuRes);
        }
        for (WbMenuRes wbMenuRes:destroyList) {
            wbMenuResBO.delete(wbMenuRes.getMenuResId());
        }
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除角色信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbTenancyMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        WbTenancy wbTenancy = JSON.parseObject(object.getString("wbTenancyData"), WbTenancy.class);
        //设置创建人时间等相关信息
        WbComUtil.setParameterValue(wbTenancy,request,true);
        //调用保存方法
        wbTenancyBO.save(wbTenancy);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * Description:删除租户信息
     * @param object
     * @param response
     * @param request
     * @return Note: Nothing much.
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbTenancyMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request) {
        String tenancyId = request.getParameter("tenancyId");
        //租户
        wbTenancyBO.delete(tenancyId);
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 授权 ：面板和按钮
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveWbRoleResourceMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request){
        //角色
        String roleId = request.getParameter("roleId");
        //菜单
        String menuIds = request.getParameter("menuIds");
        String[] menuIdArray = menuIds.split(",");
        for (String aMenuIdArray : menuIdArray) {
            WbRoleResource wbRoleResource = new WbRoleResource();
            wbRoleResource.setRoleId(roleId);
            wbRoleResource.setMenuId(aMenuIdArray);
            WbComUtil.setParameterValue(wbRoleResource, request, true);
            //删除角色菜单关系，按照租户
            wbRoleResourceBO.deleteByRoleMenu(wbRoleResource);
            //插入角色菜单关系
            wbRoleResource.setWrrId(SysUtil.getId());
            wbRoleResourceBO.insert(wbRoleResource);
        }
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消授权：面板和按钮
     */
    @Transactional(rollbackFor = Exception.class)
    public void delWbRoleResourceMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request){
        //角色
        String roleId = request.getParameter("roleId");
        //菜单
        String menuIds = request.getParameter("menuIds");
        String[] menuIdArray = menuIds.split(",");
        for (String aMenuIdArray : menuIdArray) {
            WbRoleResource wbRoleResource = new WbRoleResource();
            wbRoleResource.setRoleId(roleId);
            wbRoleResource.setMenuId(aMenuIdArray);
            WbComUtil.setParameterValue(wbRoleResource, request, true);
            //删除角色菜单关系，按照租户
            wbRoleResourceBO.deleteByRoleMenu(wbRoleResource);
        }
        try {
            WebUtil.send(response,null);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void listWbmenuMethod(JSONObject object, HttpServletResponse response, HttpServletRequest request){
        String menuid=request.getParameter("subsId");
        request.getSession().setAttribute("menuid",menuid);
        if(StringUtils.isEmpty(menuid)) {
            menuid = (String) request.getSession().getAttribute("menuid");
        }
        //租户id
        String tenancyId = (String) request.getSession().getAttribute("sys.tenancyId");
        //用户id
        String userid= (String) request.getSession().getAttribute("sys.user");

        StringBuilder sb = new StringBuilder();
        List<WbMenu> wbMenuList = wbMenuBO.listWbMenu(tenancyId,userid,"0",menuid);
        for (int i=0;i<wbMenuList.size();i++){
            WbMenu wbMenu = wbMenuList.get(i);
            String icon="fa-book";
            if(iconarr[i]==null){
                icon="fa-book";
            }else{
                icon=iconarr[i];
            }
            sb.append("<li class=\"menu-list\">");
            sb.append("<a>");
            sb.append("<i class=\"fa "+icon+"\"></i>");
            sb.append("<span>"+wbMenu.getMenuName()+"</span>");
            sb.append("<span class=\"pull-right-container\"><i class=\"fa fa-angle-left pull-right\"></i></span>");
            sb.append("</a>");
            List<WbMenu> menuList = wbMenuBO.listWbMenu(tenancyId,userid,"1",wbMenu.getMenuId());
            sb.append("<ul class=\"sub-menu-list\">");
            for (WbMenu menu:menuList){
                sb.append("<li>");
                sb.append("<a onclick=\"changeurl('" + menu.getMenuUrl()+ "','" + menu.getMenuName() + "','',false,'null' )\">"
                        +"<i class=\"fa fa-circle-o\"></i>"+ menu.getMenuName() + "</a>");
                sb.append("</li>");
            }
            sb.append("</ul>");
            sb.append("</li>");
        }
        request.getSession().setAttribute("basicsLust", sb.toString());
        try {
            WebUtil.send(response,sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}