package com.judong.chuanyiserver.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.judong.chuanyiserver.dao.MenuDao;
import com.judong.chuanyiserver.entity.Menu;
import com.judong.chuanyiserver.entity.Permission;
import com.judong.chuanyiserver.enums.ResultEnum;
import com.judong.chuanyiserver.service.MenuService;
import com.judong.chuanyiserver.util.Blank;
import com.judong.chuanyiserver.util.ConstantStr;
import com.judong.chuanyiserver.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    @Override
    public synchronized Result addMenu(Menu menu) {
        if (Blank.isEmpty(menu.getParentId(), menu.getMenuName(), menu.getMenuUrl())) {
            return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "父id，菜单名称，菜单路径不能为空");
        }
        if (menu.getParentId() == ConstantStr.TOP_LEVEL_MENU) {
            if (Blank.isNotEmpty(menuDao.getMenuByName(menu.getMenuName()))) {
                return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该顶级菜单名称已被使用，请更换其他顶级菜单名称");
            }
        } else {
            if (Blank.isNotEmpty(menuDao.getMenuByUrl(menu.getMenuUrl()))) {
                return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该菜单路径已被使用，请更换其他菜单路径");
            }
        }
        //新增菜单，默认为可用
        menu.setMenuStatus(ConstantStr.MENU_AVAILABLE);
        if (menuDao.addMenu(menu) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "新增失败");
        }
        return Result.ok("添加菜单成功");
    }

    @Override
    public Result updateMenu(Menu menu) {
        if (Blank.isEmpty(menu.getId(), menu.getMenuName(), menu.getMenuUrl(), menu.getMenuStatus())) {
            return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "id,菜单名称，菜单路径,菜单状态不能为空");
        }
        Menu oldMenu = menuDao.getMenuById(menu.getId());
        if (oldMenu.getParentId() == ConstantStr.TOP_LEVEL_MENU) {
            if (Blank.isNotEmpty(menuDao.getMenuByNoIdName(menu.getId(), menu.getMenuName()))) {
                return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "该顶级菜单名称已被使用，请更换其他顶级菜单名称");
            }
        } else {
            if (Blank.isNotEmpty(menuDao.getMenuByNoIdUrl(menu.getId(), menu.getMenuUrl()))) {
                return Result.no(ResultEnum.REQUEST_WRONGPARAMS.getRespCode(), "已存在该菜单路径，请更换菜单路径");
            }
        }
        if (menuDao.updateMenu(menu) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "修改菜单失败");
        }
        return Result.ok("修改菜单成功");
    }

    @Override
    public Result getMenuListByPage(Integer page, Integer limit, String menuName, String menuUrl, Integer menuStatus) {
        JSONObject jsonObject = new JSONObject();
        Long count = menuDao.getMenuCount(menuName, menuUrl, menuStatus);
        Long startNum = Long.valueOf((page - 1) * limit);
        List<Menu> menuList = menuDao.getMenuListByPage(startNum, Long.valueOf(limit), menuName, menuUrl, menuStatus);
        jsonObject.put("count", count);
        jsonObject.put("menuList", menuList);
        return Result.ok(jsonObject);
    }

    @Override
    public Result getMenuById(Integer id) {
        return Result.ok(menuDao.getMenuById(id));
    }

    @Override
    public Result deleteMenuById(Integer id) {
        if (menuDao.deleteMenuById(id) <= 0) {
            return Result.no(ResultEnum.SERVER_ERROR.getRespCode(), "删除菜单失败");
        }
        menuDao.deleteRoleMenuById(id);
        menuDao.deleteMenuPermissionByMenuId(id);
        return Result.ok("删除菜单成功");
    }

    @Override
    public Result assignPermission(Integer menuId, List<Permission> permissionList) {
        //查询出拥有新旧接口权限集合拥有的公共接口权限
        List<Permission> sharePermissionList = menuDao.getSharePermissionList(menuId, permissionList);
        //增加新增的接口权限信息
        List<Permission> newPermissionList = new ArrayList<>();
        if (Blank.isEmpty(sharePermissionList)) {
            newPermissionList = permissionList;
            //删除原来的接口权限
            menuDao.deleteMenuPermissionByMenuId(menuId);
        } else {
            for (int i = 0; i < permissionList.size(); i++) {
                Boolean flage = false;
                for (int j = 0; j < sharePermissionList.size(); j++) {
                    if (permissionList.get(i).getId() == sharePermissionList.get(j).getId()) {
                        flage = true;
                        break;
                    }
                }
                if (!flage) {
                    newPermissionList.add(permissionList.get(i));
                }
            }
            //删除不在公共菜单的旧接口权限id
            List<Permission> oldPermissionList = menuDao.getNoShareOldPermissionList(menuId, sharePermissionList);
            if (Blank.isNotEmpty(oldPermissionList)) {
                menuDao.deleteMenuPermission(menuId, oldPermissionList);
            }
        }
        if (Blank.isNotEmpty(newPermissionList)) {
            menuDao.addMenuPermissionList(menuId, newPermissionList);
        }
        return Result.ok("菜单分配接口权限成功");
    }

    @Override
    public Result getPermissionByMenuId(Integer menuId) {
        List<Menu> menuList = menuDao.getAllMenu(ConstantStr.MENU_AVAILABLE);
        List<Menu> childMenu = getChildMenu(menuList, new ArrayList<>(), menuId);
        childMenu.add(menuDao.getMenuById(menuId));
        return Result.ok(menuDao.getPermissionListByMenuList(childMenu));
    }

    public List<Menu> getChildMenu(List<Menu> menuList, List<Menu> newMenuList, Integer parentId) {
        if (Blank.isEmpty(menuList)) {
            return null;
        }
        for (Menu menu : menuList) {
            if (menu.getParentId() == parentId) {
                newMenuList.add(menu);
                getChildMenu(menuList, newMenuList, menu.getId());
            }
        }
        return newMenuList;
    }

}
