/*
 * Copyright (c) 2020 yifu4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.yifu.cloud.plus.v1.yifu.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysMenu;
import com.yifu.cloud.plus.v1.yifu.admin.api.entity.SysRoleMenu;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysMenuMapper;
import com.yifu.cloud.plus.v1.yifu.admin.mapper.SysRoleMenuMapper;
import com.yifu.cloud.plus.v1.yifu.admin.service.SysMenuService;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CacheConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.enums.MenuTypeEnum;
import com.yifu.cloud.plus.v1.yifu.common.core.exception.ErrorCodes;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.MsgUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author fxj
 * @Description 
 * @Date 10:28 2022/6/14
**/
@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {

	private final SysRoleMenuMapper sysRoleMenuMapper;

	/**
	 * @Author fxj
	 * @Description 
	 * @Date 10:28 2022/6/14
	 * @Param 
	 * @return 
	**/
	@Override
	@Cacheable(value = CacheConstants.MENU_DETAILS, key = "#roleId  + '_menu'", unless = "#result == null")
	public Set<SysMenu> findMenuByRoleId(Long roleId) {
		return baseMapper.listMenusByRoleId(roleId);
	}

	/**
	 * 级联删除菜单
	 * @param id 菜单ID
	 * @return true成功, false失败
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public Boolean removeMenuById(Long id) {
		// 查询父节点为当前节点的节点
		List<SysMenu> menuList = this.list(Wrappers.<SysMenu>query().lambda().eq(SysMenu::getParentId, id));

		Assert.isTrue(CollUtil.isEmpty(menuList), MsgUtils.getMessage(ErrorCodes.SYS_MENU_DELETE_EXISTING));

		SysMenu sysMenu = this.getById(id);
		// 系统内置
		Assert.state(!MenuTypeEnum.SYSTEM.getType().equals(sysMenu.getSystemFlag()),
				MsgUtils.getMessage(ErrorCodes.SYS_MENU_DELETE_SYSTEM));

		sysRoleMenuMapper.delete(Wrappers.<SysRoleMenu>query().lambda().eq(SysRoleMenu::getMenuId, id));
		// 删除当前菜单及其子菜单
		return this.removeById(id);
	}

	@Override
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public Boolean updateMenuById(SysMenu sysMenu) {
		return this.updateById(sysMenu);
	}

	/**
	 * 构建树查询 1. 不是懒加载情况，查询全部 2. 是懒加载，根据parentId 查询 2.1 父节点为空，则查询ID -1
	 * @param lazy 是否是懒加载
	 * @param parentId 父节点ID
	 * @return
	 */
	@Override
	public List<Tree<Long>> treeMenu(boolean lazy, Long parentId) {
		if (!lazy) {
			List<TreeNode<Long>> collect = baseMapper
					.selectList(Wrappers.<SysMenu>lambdaQuery().orderByAsc(SysMenu::getSortOrder)).stream()
					.map(getNodeFunction()).collect(Collectors.toList());

			return TreeUtil.build(collect, CommonConstants.MENU_TREE_ROOT_ID);
		}

		Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;

		List<TreeNode<Long>> collect = baseMapper
				.selectList(Wrappers.<SysMenu>lambdaQuery().eq(SysMenu::getParentId, parent)
						.orderByAsc(SysMenu::getSortOrder))
				.stream().map(getNodeFunction()).collect(Collectors.toList());

		return TreeUtil.build(collect, parent);
	}

	/**
	 * 查询菜单
	 * @param all 全部菜单
	 * @param parentId 父节点ID
	 * @return
	 */
	@Override
	public List<Tree<Long>> filterMenu(Set<SysMenu> all, Long parentId) {
		List<TreeNode<Long>> collect = all.stream()
				.filter(menu -> MenuTypeEnum.LEFT_MENU.getType().equals(menu.getType()))
				.filter(menu -> StrUtil.isNotBlank(menu.getPath())).map(getNodeFunction()).collect(Collectors.toList());
		Long parent = parentId == null ? CommonConstants.MENU_TREE_ROOT_ID : parentId;
		return TreeUtil.build(collect, parent);
	}

	@Override
	@CacheEvict(value = CacheConstants.MENU_DETAILS, allEntries = true)
	public void clearMenuCache() {

	}

	/**
	 * 菜单分页数据
	 * @author fxj
	 * @param page
	 * @param sysMenu
	 * @return
	 */
	@Override
	public IPage<List<SysMenu>> getMenuPage(Page page, SysMenu sysMenu) {
		sysMenu.setDelFlag(CommonConstants.STATUS_NORMAL);
		return baseMapper.selectPage(page,buildQueryWrapper(sysMenu));
	}
	/**
	 * 列表菜单数据
	 * @author fxj
	 * @param sysMenu
	 * @return
	 */
	@Override
	public List<SysMenu> listOfPageMenu(SysMenu sysMenu) {
		sysMenu.setDelFlag(CommonConstants.STATUS_NORMAL);
		return baseMapper.selectList(buildQueryWrapper(sysMenu));
	}

	/**
	 * @author fxj
	 * @Date 2022-06-14
	 * @param sysMenu
	 * @return
	 */
	@Override
	public SysMenu saveAsso(SysMenu sysMenu) {
		if (Common.isNotNull(sysMenu) && Common.isNotNull(sysMenu.getParentId())){
			SysMenu menu = baseMapper.selectById(sysMenu.getParentId());
			if (Common.isNotNull(menu) && CommonConstants.ONE_STRING.equals(menu.getFlag())){
				Assert.state(!MenuTypeEnum.DATA_FLAG.getType().equals(sysMenu.getSystemFlag()),
						MsgUtils.getMessage(ErrorCodes.SYS_MENU_ADD_PARENT_ERROR));
			}
		}
		this.save(sysMenu);
		return sysMenu;
	}

	/**
	 * 构建查询的 wrapper
	 * @param sysMenu 查询条件
	 * @return LambdaQueryWrapper
	 */
	private LambdaQueryWrapper buildQueryWrapper(SysMenu sysMenu) {
		LambdaQueryWrapper<SysMenu> wrapper = Wrappers.lambdaQuery();
		if (StrUtil.isNotBlank(sysMenu.getFlag())) {
			wrapper.eq(SysMenu::getFlag, sysMenu.getFlag());
		}
		if (StrUtil.isNotBlank(sysMenu.getName())){
			wrapper.eq(SysMenu::getName,sysMenu.getMenuId());
		}
		if (StrUtil.isNotBlank(sysMenu.getSystemFlag())){
			wrapper.eq(SysMenu::getSystemFlag,sysMenu.getSystemFlag());
		}
		if (StrUtil.isNotBlank(sysMenu.getType())){
			wrapper.eq(SysMenu::getType,sysMenu.getType());
		}
		if (StrUtil.isNotBlank(sysMenu.getDelFlag())){
			wrapper.eq(SysMenu::getDelFlag,sysMenu.getDelFlag());
		}
		return wrapper;
	}

	@NotNull
	private Function<SysMenu, TreeNode<Long>> getNodeFunction() {
		return menu -> {
			TreeNode<Long> node = new TreeNode<>();
			node.setId(menu.getMenuId());
			node.setName(menu.getName());
			node.setParentId(menu.getParentId());
			node.setWeight(menu.getSortOrder());
			// 扩展属性
			Map<String, Object> extra = new HashMap<>();
			extra.put("icon", menu.getIcon());
			extra.put("path", menu.getPath());
			extra.put("type", menu.getType());
			extra.put("permission", menu.getPermission());
			extra.put("label", menu.getName());
			extra.put("sortOrder", menu.getSortOrder());
			extra.put("keepAlive", menu.getKeepAlive());
			extra.put("systemFlag",menu.getSystemFlag());
			extra.put("flag",menu.getFlag());
			node.setExtra(extra);
			return node;
		};
	}

}
