package com.roma.romaapi.service;

import com.roma.romaapi.dao.ApiDao;
import com.roma.romaapi.dao.PageDao;
import com.roma.romaapi.utils.CommonUtil;
import com.roma.romaapi.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import com.roma.romaapi.utils.SecurityUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class ApiService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private ApiDao apiDao;
    @Autowired
    PageDao pageDao;  // 引入dao层
    @Autowired
    SecurityUtils securityUtils;
    @Autowired
    JWTUtil jwtUtil;
    @Autowired
    CommonUtil commonUtil;
    // 登录方法
    public Map<String, Object> login(Map<String, String[]> maps) {
        // 请求参数,获取验证码,验证码token,用户名,密码
        String userName = maps.get("api_name")[0]; // 用户名
        String password = maps.get("api_password")[0]; // 密码
        String captcha = maps.get("api_captcha")[0]; // 用户输入验证码
        String captchaToken = maps.get("captchaToken")[0]; // 验证码token,获取验证码的值
        String captchaTokenValue = redisTemplate.opsForValue().get(captchaToken); // 缓存中验证码的值
        Map<String, Object> loginResult = new HashMap<>();
//        String aa = securityUtils.encodePassword(password); // 加密密码
        // 判断是否存在此用户,用户密码是否正确
        Map<String, Object> UserInfo = apiDao.adminInfoQueryForMap(userName);
        if(UserInfo.containsKey("sysErrorCode")) {
            loginResult.put("sysErrorCode", "500");
            loginResult.put("sysErrorMessage", "账号或密码错误");

            return loginResult;
        }
        Object adminPassword = UserInfo.get("admin_password");
        String stringAdminPassword = adminPassword.toString();
        // 校验密码是否正确
        if(!securityUtils.matchesPassword(password,stringAdminPassword)) {
            // 校验密码是否正确 密码不正确,返回错误
            loginResult.put("sysErrorCode", "500");
            loginResult.put("sysErrorMessage", "账号或密码错误");

            return loginResult;
        }
        // 校验图形验证码
        if(!Boolean.TRUE.equals(redisTemplate.hasKey(captchaToken)) || !Objects.equals(captchaTokenValue, captcha)){
            loginResult.put("sysErrorCode", "500");
            loginResult.put("sysErrorMessage", "验证码错误");

            return loginResult;
        }

        // 通过密码,验证码校验,发放token
        Map<String, Object> jwtInfo = new HashMap<>();
        Object userId = UserInfo.get("id");
        String stringUserId = userId.toString();
        jwtInfo.put("id", stringUserId);
        jwtInfo.put("loginTime", System.currentTimeMillis()/1000+"");
        jwtInfo.put("name", userName);
        String jwtToken = jwtUtil.getToken(jwtInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("loginToken", jwtToken);

        return map;
    }

    // 通过头部,获取用户信息
    public Map<String, Object> userInfo(String headerToken) {
        String userId = commonUtil.getUserIdByHeaderAuthorization(headerToken);
        Map<String, Object> map = new HashMap<>();
        if (userId.length() > 0) {
            // 获取用户信息
            Map<String, Object> userInfo = apiDao.userInfoByIdQueryForMap(userId);
            if (userInfo.containsKey("admin_name")) {
                map.put("userName", userInfo.get("admin_name"));
            }
        }

        return map;
    }

    // 通过用户id,获取用户信息
    public Map<String, Object> getUserInfoById(Map params) {
        Map<String, Object> map = new HashMap<>();
        String userId = params.get("id").toString();
        if (userId.length() > 0) {
            // 获取用户信息
            Map<String, Object> userInfo = apiDao.enableAndNoEnableUserInfoByIdQueryForMap(userId);
            map.put("admin_name", userInfo.get("admin_name"));
            map.put("api_upload_pic", userInfo.get("admin_avatar"));
            map.put("is_enable", userInfo.get("is_enable"));
            map.put("admin_email", userInfo.get("admin_email"));
            map.put("admin_phone", userInfo.get("admin_phone"));
            // 获取此用户所有角色
            List<Map<String, Object>> userAllRole = apiDao.getAllRoleByUserId(userId);
            String userAllRoleString = "";
            if (userAllRole.size() > 0) {
                for (int i = 0; i < userAllRole.size(); i++) {
                    Map nowRole = userAllRole.get(i);
                    String permissionId = nowRole.get("role_id").toString();
                    userAllRoleString += permissionId + ",";
                }
                userAllRoleString = commonUtil.trimFirstAndLastChar(userAllRoleString, ",");
            }

            map.put("user_role", userAllRoleString);
        }

        return map;
    }

    // 退出登录
    public Map<String, Object> logout(String headerToken) {
        Boolean logout = commonUtil.logoutDeleteRedisToken(headerToken);
        Map<String, Object> map = new HashMap<>();
        map.put("sysErrorCode","50000");
        return map;
    }

    // 获取全部菜单
    public List permissionList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getAllMenuForList(); // 获取全部菜单数据
        List<Map<String, Object>> treeMenu = this.treeMenu(menuData);  // 生成树结构

        return treeMenu;
    }

    // 获取Page全部数据-权限添加使用
    public List selectPermissionList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getPageMenuForList(); // 获取page数据
        List<Map<String, Object>> treeMenu = this.treeMenu(menuData);  // 生成树结构

        return treeMenu;
    }

    // 获取全部角色
    public Map roleList(Map<String, String> maps) {
        String page = "1"; // 页数
        String perPage = "15"; // 显示多少条
        Map res = new HashMap<>();
        Map bindData = commonUtil.filterApiBindParams(maps);
        if(maps.containsKey("page")) {
            page = maps.get("page");
        }
        if(maps.containsKey("perPage")) {
            perPage = maps.get("perPage");
        }
        Integer count = apiDao.getAllRoleListHasPagingCount(bindData);
        List info = apiDao.getAllRoleListHasPaging(bindData, page, perPage, count);
        res.put("count", count);
        res.put("rows", info);

        return res;
    }

    // 获取角色详情
    public Map roleDetailById(Map params) {
        String id = params.get("id").toString();
        Map info = apiDao.getDetailsInfoByIdAndType("roma_roles", id);
        // 获取此角色下的全部详情数据,并用,分割成字符串 permission_info
        List<Map<String, Object>> roleAllPermission = apiDao.getAllPermissionByRoleId(id);
        String permissionAllString = "";
        if (roleAllPermission.size() > 0) {
            for (int i = 0; i < roleAllPermission.size(); i++) {
                Map map = roleAllPermission.get(i);
                String permissionId = map.get("permission_id").toString();
                permissionAllString += permissionId + ",";
            }
            permissionAllString = commonUtil.trimFirstAndLastChar(permissionAllString, ",");
        }
        info.put("permission_info", permissionAllString);

        return info;
    }

    // 获取sql详情
    public Map sqlDetailById(Map params) {
        String id = params.get("id").toString();
        Map info = apiDao.getDetailsInfoByIdAndType("sql_details", id);
        // 判断,如果是update行为,则默认is_list的值为1
        if(info.get("sql_type").toString().equals("update") && info.get("is_list").toString().equals("0")) {
            info.put("is_list", "1");
        }

        return info;
    }

    // 删除对应基础表数据
    public Map delDetailById(Map params) {
        Map ret = new HashMap<>();
        String id = params.get("id").toString();
        String action = params.get("action").toString();
        String table = "";
        // 判断是否还有权限在使用此基础数据,如果有则不能删除
        if (action.equals("sql")) {
            table = "sql_details";
        } else if (action.equals("item")) {
            table = "item_details";
        } else if (action.equals("api")) {
            table = "api_details";
        } else if (action.equals("page")) {
            table = "page_details";
        }
        Map hasUsedByPermission = new HashMap<>();
        hasUsedByPermission.put("objectType", action);
        hasUsedByPermission.put("objectId", id);
        Boolean isUsedPermission = apiDao.usedPermissionByObjectId(hasUsedByPermission);
        if(!isUsedPermission) {
            // 如果有被权限引用,则提示不能删除
            ret.put("sysErrorCode", "51000");
            ret.put("sysErrorMessage", "此数据被权限使用中,无法删除");

            return ret;
        }
        // 删除基础表数据
        Map deleteParams = new HashMap<>();
        deleteParams.put("id", id);
        Integer delRet = apiDao.deleteDetailsDataByTableNameAndId(deleteParams, table);
        if (delRet < 1) {
            ret.put("sysErrorCode", "51000");
        }

        return ret;
    }

    // 删除具体权限
    public Map deletePermissionById(Map params) {
        Map ret = new HashMap<>();
        String id = params.get("id").toString();
        // 权限可以删除，删除的时候如果有子节点，则得一个个删除，如果存在子节点，提示请先删除所有子节点。不需要判断权限是否有基础details关联。
        Map hasParams = new HashMap<>();
        hasParams.put("id", id);
        Boolean hasRet = apiDao.hasSonPermissionById(hasParams);
        // 如果有,则提示先删除下级
        if(!hasRet) {
            // 如果有被权限引用,则提示不能删除
            ret.put("sysErrorCode", "51000");
            ret.put("sysErrorMessage", "此权限下有子权限,请先删除子权限");

            return ret;
        }
        // 删除具体的权限值
        Integer deleteData = apiDao.deletePermissionById(hasParams);
        if (deleteData < 1) {
            ret.put("sysErrorCode", "51000");
        }

        return ret;
    }

    // 获取全部page_details---配置权限关联page使用,无分页
    public List pageList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getAllPageList(); // 获取全部page_details表数据
        for (Map<String, Object> tmp : menuData) {
            tmp.put("show_name", tmp.get("page_code")+" / " + tmp.get("page_name"));
        }

        return menuData;
    }

    // page管理列表-获取带分页的page数据
    public Map pageListHasPaging(Map<String, String> maps) {
        String page = "1"; // 页数
        String perPage = "15"; // 显示多少条
        Map res = new HashMap<>();
        Map bindData = commonUtil.filterApiBindParams(maps);
        if(maps.containsKey("page")) {
            page = maps.get("page");
        }
        if(maps.containsKey("perPage")) {
            perPage = maps.get("perPage");
        }
        Integer count = pageDao.getAllPageListHasPagingCount(bindData);
        List info = pageDao.getAllPageListHasPaging(bindData, page, perPage, count);
        res.put("count", count);
        res.put("rows", info);

        return res;
    }

    // sql管理列表-获取带分页的page数据
    public Map sqlListHasPaging(Map<String, String> maps) {
        String page = "1"; // 页数
        String perPage = "15"; // 显示多少条
        Map res = new HashMap<>();
        Map bindData = commonUtil.filterApiBindParams(maps);
        if(maps.containsKey("page")) {
            page = maps.get("page");
        }
        if(maps.containsKey("perPage")) {
            perPage = maps.get("perPage");
        }
        Integer count = pageDao.getAllSqlListHasPagingCount(bindData);
        List info = pageDao.getAllSqlListHasPaging(bindData, page, perPage, count);
        res.put("count", count);
        res.put("rows", info);

        return res;
    }

    // api管理列表-获取带分页的page数据
    public Map apiListHasPaging(Map<String, String> maps) {
        String page = "1"; // 页数
        String perPage = "15"; // 显示多少条
        Map res = new HashMap<>();
        Map bindData = commonUtil.filterApiBindParams(maps);
        if(maps.containsKey("page")) {
            page = maps.get("page");
        }
        if(maps.containsKey("perPage")) {
            perPage = maps.get("perPage");
        }
        Integer count = pageDao.getAllApiListHasPagingCount(bindData);
        List info = pageDao.getAllApiListHasPaging(bindData, page, perPage, count);
        res.put("count", count);
        res.put("rows", info);

        return res;
    }

    // api管理列表-获取带分页的page数据
    public Map itemListHasPaging(Map<String, String> maps) {
        String page = "1"; // 页数
        String perPage = "15"; // 显示多少条
        Map res = new HashMap<>();
        Map bindData = commonUtil.filterApiBindParams(maps);
        if(maps.containsKey("page")) {
            page = maps.get("page");
        }
        if(maps.containsKey("perPage")) {
            perPage = maps.get("perPage");
        }
        Integer count = pageDao.getAllItemListHasPagingCount(bindData);
        List info = pageDao.getAllItemListHasPaging(bindData, page, perPage, count);
        res.put("count", count);
        res.put("rows", info);

        return res;
    }

    // 获取全部sql_details
    public List sqlList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getAllSqlList(); // 获取全部page_details表数据
        for (Map<String, Object> tmp : menuData) {
            tmp.put("show_name", tmp.get("sql_code")+" / " + tmp.get("sql_name"));
        }

        return menuData;
    }

    // 获取全部api_details---配置权限关联api使用,无分页
    public List apiList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getAllApiList(); // 获取全部page_details表数据
        for (Map<String, Object> tmp : menuData) {
            tmp.put("show_name", tmp.get("api_code")+" / " + tmp.get("api_name"));
        }

        return menuData;
    }

    // 获取全部roma_roles---用户分配角色使用,无分页
    public List roleList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getAllRoleList();

        return menuData;
    }

    // 获取全部sql_details---配置权限关联item使用,无分页
    public List itemList() {
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> menuData = pageDao.getAllItemList(); // 获取全部page_details表数据
        for (Map<String, Object> tmp : menuData) {
            tmp.put("show_name", tmp.get("item_code")+" / " + tmp.get("item_name"));
        }

        return menuData;
    }

    // 新建权限
    public Map addPermissions(Map maps) {
        Map ret = new HashMap<>();
        if (!maps.containsKey("object_type")) {
            // 如果不存在类型,返回错误
            ret.put("sysErrorCode", "51000");

            return ret;
        }

        ret = this.handlePagePermission(maps);


        return ret;
    }

    // 整理page的添加和编辑权限项目
    private Map handlePagePermission(Map params) {
        // 肯定存在的参数字段
        String isEnable = "1"; //params.get("is_enable").toString();
        String objectType = params.get("object_type").toString();
        // 以下参数可能不存在
        String isVisible = "0"; // 当是菜单的时候,是否可见
        String isMenu = "0";
        String menuName = ""; // 菜单名称,page_details表有数据,则此字段可能不存在
        String objectId = "0"; // 关联的基础details表id
        String parentId = "0";// 上级id,顶级菜单,此字段可能不传
        String permissionDescribe = ""; // 描述非必填
        String permissionSort = "0";
        String permissionsIcon = "";
        // 是否为目录
        String isDir = "0"; // 1是目录  2不是目录
        String id = ""; // 编辑的id
        // 如果是目录，则icon给默认的。 如果不是目录，则可以自己输入，如果不输入，则给默认一个。
        if (params.containsKey("is_dir")) {
            isDir = params.get("is_dir").toString();
            if (isDir.equals("1") || isDir.equals("2")) {
                isMenu = isDir;
            }
            if (isDir.equals("1")) {
                permissionsIcon = "ri-folder-2-line";
            } else {
                permissionsIcon = params.get("permissions_icon").toString();
            }
        }

        if (params.containsKey("id")) {
            id = params.get("id").toString();
        }
        if (params.containsKey("is_visible")) {
            isVisible = params.get("is_visible").toString();
        }
        if (params.containsKey("is_menu")) {
            isMenu = params.get("is_menu").toString();
        }
        if(params.containsKey("menu_name")) {
            menuName = params.get("menu_name").toString();
        }
        if (objectType.equals("page")) {
            if(params.containsKey("page_id")) {
                objectId = params.get("page_id").toString();
            }
        } else if (objectType.equals("sql")) {
            if(params.containsKey("sql_id")) {
                objectId = params.get("sql_id").toString();
            }
        } else if (objectType.equals("api")) {
            if(params.containsKey("api_id")) {
                objectId = params.get("api_id").toString();
            }
        } else if (objectType.equals("item")) {
            if(params.containsKey("item_id")) {
                objectId = params.get("item_id").toString();
            }
        }

        if(params.containsKey("parent_id")) {
            parentId = params.get("parent_id").toString();
        }
        if(params.containsKey("permission_describe")) {
            permissionDescribe = params.get("permission_describe").toString();
        }
        if(params.containsKey("permission_sort")) {
            permissionSort = params.get("permission_sort").toString();
        }

        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> bindVal = new HashMap<>();
        bindVal.put("isEnable", isEnable);
        bindVal.put("isMenu", isMenu);
        bindVal.put("isVisible", isVisible);
        bindVal.put("objectType", objectType);
        bindVal.put("menuName", menuName);
        bindVal.put("objectId", objectId);
        bindVal.put("parentId", parentId);
        bindVal.put("permissionDescribe", permissionDescribe);
        bindVal.put("permissionSort", permissionSort);
        bindVal.put("permissionsIcon", permissionsIcon);
        bindVal.put("createdAt", createdAt);
        Integer savePermission = apiDao.savePermission(bindVal, id);
        Map ret = new HashMap<>();
        if(savePermission < 1) {
            ret.put("sysErrorCode", "51000");
        }

        return ret;
    }

    // 添加角色
    public Map addRole(Map maps) {
        Map retInfo = new HashMap<>(); // 返回信息
        // 添加和编辑公用此方法
        String id = "";
        if (maps.containsKey("id")) {
            id = maps.get("id").toString();
        }
        // 角色名,是否启用,是必填的
        String isEnable = maps.get("is_enable").toString();
        String roleName = maps.get("role_name").toString();
        String roleDesc = "";
        if (maps.containsKey("role_desc")) {
            roleDesc = maps.get("role_desc").toString();
        } else if (maps.containsKey("role_description")) {
            roleDesc = maps.get("role_description").toString();
        }
        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> addRolePamars = new HashMap<>();
        addRolePamars.put("roleName", roleName);
        addRolePamars.put("isEnable", isEnable);
        addRolePamars.put("roleDesc", roleDesc);
        if (id.length()>0) {
            // 如果是编辑角色,则增加id参数
            addRolePamars.put("id", id);
        } else {
            // 如果是添加角色,则增加创建时间字段
            addRolePamars.put("createdAt", createdAt);
        }
        Integer roleId = 0;
        if (id.length() > 0) {
            // 编辑角色
            Integer editRoleRet = apiDao.editRole(addRolePamars);
            if (editRoleRet < 1) {
                // 如果角色信息编辑失败,则直接返回错误,不进行权限编辑
                retInfo.put("sysErrorCode", "500");

                return retInfo;
            }
            roleId = Integer.valueOf(id);
        } else {
            // 添加角色
            roleId = apiDao.addRole(addRolePamars);
        }

        // 判断是否给角色勾选的权限
        Boolean hasPermission = maps.containsKey("permission_info");
        Integer addRolePermissionRet = 0;
        if(hasPermission) {
            String allPermission = maps.get("permission_info").toString();
            // 如果有权限,则添加完角色后,再添加角色和权限的关联表数据
            LinkedHashSet<String> unPermission = new LinkedHashSet<String>();
            for(String s : allPermission.split(",")) {
                unPermission.add(s);
            }
            // 循环去重后的数据
            String values = "";
            for(String val: unPermission) {
                values += " ("+roleId+","+val+"),";
            }
            values = commonUtil.trimFirstAndLastChar(values, ",");
            if (id.length() > 0) {
                // 编辑权限
                addRolePermissionRet = apiDao.editRolePermission(values, id);
            } else {
                // 添加权限
                addRolePermissionRet = apiDao.addRolePermission(values);
            }
        }

        if((hasPermission && addRolePermissionRet>0 && roleId>0) || (!hasPermission && roleId>0)) {

        } else {
            retInfo.put("sysErrorCode", "500");
        }
        return retInfo;
    }

    // 编辑page,获取page单条数据详情
    public Map pageDetailById(Map params) {
        String id = params.get("id").toString();
        Map info = apiDao.getDetailsInfoByIdAndType("page_details", id);

        return info;
    }

    // 编辑permission,获取单条数据详情
    public Map permissionDetailById(Map params) {
        String id = params.get("id").toString();
        Map info = apiDao.getDetailsInfoByIdAndType("roma_permissions", id);

        String isVisible = info.get("is_visible").toString();
        if (isVisible.equals("0")) {
            info.put("is_visible", "1");
        }
        String isDir = info.get("is_menu").toString();
        if(isDir.equals("0")) {
            info.put("is_dir", "1");
        }

        return info;
    }

    // 添加page_details表数据
    public Map addPage(Map maps) {
        String pageDesc = "";
        String frontPath = "";//maps.get("front_path").toString();
        String isEnable = "1";//maps.get("is_enable").toString();
        String pageCode = maps.get("page_code").toString();
        String pageName = maps.get("page_name").toString();
        String pageJson = maps.get("page_json").toString();
//        if (maps.containsKey("role_desc")) {
//            roleDesc = maps.get("role_desc").toString();
//        }
        if(maps.containsKey("page_desc")) {
            pageDesc = maps.get("page_desc").toString();
        } else if(maps.containsKey("page_description")){
            pageDesc = maps.get("page_description").toString();
        }
        // 通过是否存在id,判读是新增还是修改
        String editId = "";
        if (maps.containsKey("id")) {
            editId = maps.get("id").toString();
        }
        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> addPagePamars = new HashMap<>();
        addPagePamars.put("frontPath", frontPath);
        addPagePamars.put("isEnable", isEnable);
        addPagePamars.put("pageCode", pageCode);
        addPagePamars.put("pageDesc", pageDesc);
        addPagePamars.put("pageName", pageName);
        addPagePamars.put("pageJson", pageJson);
        if (editId.length()==0) {
            // 如果不存在说明是新增
            addPagePamars.put("createdAt", createdAt);
        }
        // 添加Page
        Integer pageId = apiDao.addPageDetails(addPagePamars, editId);
        Map retInfo = new HashMap<>();
        if(pageId <= 0){
            retInfo.put("sysErrorCode", "500");
        }
        return retInfo;
    }

    // 添加sql_details表数据
    public Map addSql(Map maps, String authorization) {
        String sqlDesc = "";
        String isList = "0";
        if (maps.containsKey("is_list")) {
            isList = maps.get("is_list").toString();
        }
        String sqlType = maps.get("sql_type").toString();
        String isEnable = "1";//maps.get("is_enable").toString();
        String sqlCode = maps.get("sql_code").toString();
        String sqlName = maps.get("sql_name").toString();
        String sqlString = maps.get("sql_string").toString();
        if(maps.containsKey("sql_description")) {
            sqlDesc = maps.get("sql_description").toString();
        }
        // 通过是否存在id,判读是新增还是修改
        String editId = "";
        if (maps.containsKey("id")) {
            editId = maps.get("id").toString();
        }
        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> addPagePamars = new HashMap<>();
        addPagePamars.put("isList", isList);
        addPagePamars.put("sqlType", sqlType);
        addPagePamars.put("isEnable", isEnable);
        addPagePamars.put("sqlCode", sqlCode);
        addPagePamars.put("sqlName", sqlName);
        addPagePamars.put("sqlString", sqlString);
        addPagePamars.put("sqlDesc", sqlDesc);
        Map<String, Object> loginResult = this.userInfo(authorization);
        addPagePamars.put("actionUser", loginResult.get("userName")); // 获取当前用户信息
        if (editId.length()==0) {
            // 如果不存在说明是新增
            addPagePamars.put("createdAt", createdAt);
        }
        // 添加/编辑Sql
        Integer pageId = apiDao.addSqlDetails(addPagePamars, editId);
        Map retInfo = new HashMap<>();
        if(pageId <= 0){
            retInfo.put("sysErrorCode", "500");
        }
        return retInfo;
    }

    // 添加/编辑api_details表数据
    public Map saveApi(Map maps, String authorization) {
        String apiDesc = "";
        String isEnable = "1";
        String apiCode = maps.get("api_code").toString();
        String apiName = maps.get("api_name").toString();
        if(maps.containsKey("api_description")) {
            apiDesc = maps.get("api_description").toString();
        }
        // 通过是否存在id,判读是新增还是修改
        String editId = "";
        if (maps.containsKey("id")) {
            editId = maps.get("id").toString();
        }
        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> addPagePamars = new HashMap<>();
        addPagePamars.put("isEnable", isEnable);
        addPagePamars.put("apiCode", apiCode);
        addPagePamars.put("apiName", apiName);
        addPagePamars.put("apiDesc", apiDesc);
//        Map<String, Object> loginResult = this.userInfo(authorization);
//        addPagePamars.put("actionUser", loginResult.get("userName")); // 获取当前用户信息
        if (editId.length()==0) {
            // 如果不存在说明是新增
            addPagePamars.put("createdAt", createdAt);
        }
        // 添加/编辑
        Integer pageId = apiDao.saveApiDetails(addPagePamars, editId);
        Map retInfo = new HashMap<>();
        if(pageId <= 0){
            retInfo.put("sysErrorCode", "500");
        }
        return retInfo;
    }

    // 获取api详情
    public Map apiDetailById(Map params) {
        String id = params.get("id").toString();
        Map info = apiDao.getDetailsInfoByIdAndType("api_details", id);

        return info;
    }

    // 获取item详情
    public Map itemDetailById(Map params) {
        String id = params.get("id").toString();
        Map info = apiDao.getDetailsInfoByIdAndType("item_details", id);

        return info;
    }

    // 添加/编辑item_details表数据
    public Map saveItem(Map maps, String authorization) {
        String itemDesc = "";
        String isEnable = "1"; //maps.get("is_enable").toString();
        String itemCode = maps.get("item_code").toString();
        String itemName = maps.get("item_name").toString();
        if(maps.containsKey("item_description")) {
            itemDesc = maps.get("item_description").toString();
        }
        // 通过是否存在id,判读是新增还是修改
        String editId = "";
        if (maps.containsKey("id")) {
            editId = maps.get("id").toString();
        }
        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> addPagePamars = new HashMap<>();
        addPagePamars.put("isEnable", isEnable);
        addPagePamars.put("itemCode", itemCode);
        addPagePamars.put("itemName", itemName);
        addPagePamars.put("itemDesc", itemDesc);
//        Map<String, Object> loginResult = this.userInfo(authorization);
//        addPagePamars.put("actionUser", loginResult.get("userName")); // 获取当前用户信息
        if (editId.length()==0) {
            // 如果不存在说明是新增
            addPagePamars.put("createdAt", createdAt);
        }
        // 添加/编辑
        Integer pageId = apiDao.saveItemDetails(addPagePamars, editId);
        Map retInfo = new HashMap<>();
        if(pageId <= 0){
            retInfo.put("sysErrorCode", "500");
        }
        return retInfo;
    }

    // 用户管理列表-获取带分页的page数据
    public Map userListHasPaging(Map<String, String> maps) {
        String page = "1"; // 页数
        String perPage = "15"; // 显示多少条
        Map res = new HashMap<>();
        Map bindData = commonUtil.filterApiBindParams(maps);
        if(maps.containsKey("page")) {
            page = maps.get("page");
        }
        if(maps.containsKey("perPage")) {
            perPage = maps.get("perPage");
        }
        Integer count = pageDao.getAllUserListHasPagingCount(bindData);
        List info = pageDao.getAllUserListHasPaging(bindData, page, perPage, count);
        res.put("count", count);
        res.put("rows", info);

        return res;
    }

    // 添加用户信息
    public Map userSave(Map maps, String authorization) {
        String isEnable = maps.get("is_enable").toString();
        String adminName = maps.get("admin_name").toString();
        String userId = "";
        String adminPassword = "";
        if(maps.containsKey("id")) {
            userId = maps.get("id").toString();
        } else {
            // 添加用户,才会传密码字段
            adminPassword = maps.get("admin_password").toString();
        }

        // 如果是添加用户密码要加密,编辑用户则没有密码字段.编辑密码单独一个功能
        // 角色/email/phone/头像 可能不存在
        String adminEmail = "";
        String adminPhone = "";
        String userRole = "";
        String apiUploadPic = "";
        if (maps.containsKey("admin_email")) {
            adminEmail = maps.get("admin_email").toString();
        }
        if (maps.containsKey("admin_phone")) {
            adminPhone = maps.get("admin_phone").toString();
        }
        if (maps.containsKey("api_upload_pic")) {
            apiUploadPic = maps.get("api_upload_pic").toString();
        }
        if (maps.containsKey("user_role")) {
            userRole = maps.get("user_role").toString();
        }
        String createdAt = commonUtil.getNowYYMMDDHHIISS();
        Map<String, Object> addPagePamars = new HashMap<>();
        adminPassword = securityUtils.encodePassword(adminPassword); // 加密密码
        addPagePamars.put("isEnable", isEnable);
        addPagePamars.put("adminName", adminName);
        addPagePamars.put("adminPassword", adminPassword);
        addPagePamars.put("adminEmail", adminEmail);
        addPagePamars.put("adminPhone", adminPhone);
        addPagePamars.put("apiUploadPic", apiUploadPic);
        if (userId.length() > 0) {
            // 如果是编辑用户
        } else {
            // 如果是添加用户
            addPagePamars.put("createdAt", createdAt);
        }

        // 添加
        Integer pageId = apiDao.saveUser(addPagePamars, userRole, userId);
        Map retInfo = new HashMap<>();
        if(pageId <= 0){
            retInfo.put("sysErrorCode", "500");
        }
        return retInfo;
    }

    // 转换tree结构数据
    private List<Map<String, Object>> treeMenu(List<Map<String, Object>> renderMenu){
        // 处理的数据存在
        List<Map<String, Object>> pList = new ArrayList<Map<String, Object>>();// eTree
        // 获取父节点
        for (Map<String, Object> tmp : renderMenu) {
            // 塞个8
            tmp.put("hidden_user_permission", "8");
            Object parentId =  tmp.get("parent_id");
            String stringParentId = parentId.toString();// 上级id
            Object dataId = tmp.get("id");
            String stringDataId = dataId.toString();// 主键id
            if (stringParentId.equals("0")) {
                // 组装子节点，开始循环去获取子节点
                List<?> children = menuChild(stringDataId, renderMenu);
                if(children == null || children.size() == 0) {
                    tmp.put("leaf", true); // 如果不存在子元素
                } else {
                    tmp.put("children", children); // 存在子元素,则添加
                }

                pList.add(tmp);
            }
        }

        return pList;
    }

    /**
     * 处理子节点
     * @param id
     * @param data
     * @return
     */
    private List<?> menuChild(String id, List<Map<String, Object>> data) {
        List<Object> lists = new ArrayList<Object>();
        for (Map<String, Object> map : data) {
            Object parentId =  map.get("parent_id");
            String stringParentId = parentId.toString(); // 上级id
            Object dataId = map.get("id");
            String stringDataId = dataId.toString(); // 主键id

            // 新增字段:权限项名称 权限项路径
            Object objectId = map.get("object_id");
            Object objectType = map.get("object_type");
            String stringObjectId = objectId.toString();
            String stringObjectType = objectType.toString();
            // 获取菜单名称
            Object objectMenuName = map.get("menu_name");
            String stringMenuName = objectMenuName.toString();
            Map permissionDetails = this.getPermissionDetails(stringObjectType, stringObjectId, stringMenuName);
            if (permissionDetails.containsKey("permission_path")) {
                map.put("permission_path", permissionDetails.get("permission_path"));
            }
            if (permissionDetails.containsKey("permission_name")) {
                map.put("permission_name", permissionDetails.get("permission_name"));
            }
            if (permissionDetails.containsKey("show_name")) {
                map.put("show_name", permissionDetails.get("show_name"));
            }
            if (stringParentId.equals(id)) {
                // 组装子节点，开始循环去获取子节点
                List<?> children = menuChild(stringDataId, data);
                if(children == null || children.size() == 0) {
                    map.put("leaf", true); // 如果不存在子元素
                } else {
                    map.put("children", children); // 存在子元素,则添加
                }
                lists.add(map);
            }
        }
        return lists;
    }

    private Map getPermissionDetails(String stringObjectType, String stringObjectId, String stringMenuName) {
        String separator = " / ";
        Map map = new HashMap<>();
        if (stringObjectType.equals("page")) {
            if(stringObjectId.equals("0")) {
                // 如果是菜单目录,则无路径,无权限名称只有菜单名称
                map.put("permission_name", stringMenuName);
                map.put("show_name", stringMenuName);
            } else {
                // 获取page_details表数据,编码,和权限名称
                Map pageInfo = apiDao.getDetailsInfoByIdAndType("page_details", stringObjectId);
                map.put("permission_path", "/page/"+pageInfo.get("page_code"));
                map.put("permission_name", pageInfo.get("page_name"));
                map.put("show_name", pageInfo.get("page_code").toString() + separator + pageInfo.get("page_name"));
            }
        } else if (stringObjectType.equals("sql") && !stringObjectId.equals("0")) {
            Map pageInfo = apiDao.getDetailsInfoByIdAndType("sql_details", stringObjectId);
            map.put("permission_path", "/dbapi/"+pageInfo.get("sql_code"));
            map.put("permission_name", pageInfo.get("sql_name"));
            map.put("show_name", pageInfo.get("sql_code").toString() + separator + pageInfo.get("sql_name"));
        } else if (stringObjectType.equals("api") && !stringObjectId.equals("0")) {
            Map pageInfo = apiDao.getDetailsInfoByIdAndType("api_details", stringObjectId);
            map.put("permission_path", "/api/"+pageInfo.get("api_code"));
            map.put("permission_name", pageInfo.get("api_name"));
            map.put("show_name", pageInfo.get("api_code").toString() + separator + pageInfo.get("api_name"));
        } else if (stringObjectType.equals("item") && !stringObjectId.equals("0")) {
            Map pageInfo = apiDao.getDetailsInfoByIdAndType("item_details", stringObjectId);
            map.put("permission_path", "/api/"+pageInfo.get("item_code"));
            map.put("permission_name", pageInfo.get("item_name"));
            map.put("show_name", pageInfo.get("item_code").toString() + separator + pageInfo.get("item_name"));
        }

         return map;
    }
}
