/**
 * 
 */
package org.springblade.modules.system.service.normal;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import org.springblade.core.constant.BladeConstant;
import org.springblade.core.tool.utils.CollectionUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.entity.Menu;
import org.springblade.modules.system.entity.SysPackage;
import org.springblade.modules.system.entity.SysPackageMenu;
import org.springblade.modules.system.mapper.MenuMapper;
import org.springblade.modules.system.mapper.SysPackageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * @author wookvn
 *
 */
@Service
public class SysPackageService extends ServiceImpl<SysPackageMapper, SysPackage> {

	@Autowired
	private SysPackageMenuService packageMenuService;
	
	@Autowired
	private MenuMapper menuMapper;
	
	/**
	 * 更新或插入
	 * @param sysPackage
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean doSaveOrUpdate(SysPackage sysPackage) {
		//添加或更新
		saveOrUpdate(sysPackage);
		Integer packageId = sysPackage.getId();
		if(packageId != null && packageId > 0 && CollectionUtil.isNotEmpty(sysPackage.getMenuIds())) {
			packageMenuService.remove(Wrappers.<SysPackageMenu>lambdaQuery().eq(SysPackageMenu::getPackageId, packageId));
			List<SysPackageMenu> entityList = new ArrayList<>(sysPackage.getMenuIds().size());
			sysPackage.getMenuIds().stream().forEach(menuId -> entityList.add(new SysPackageMenu(packageId, menuId)));
			//查询所有套餐菜单，递归获取到父节点
			List<Menu> allMenus = menuMapper.allSystemMenuButton(BladeConstant.ADMIN_TENANT_ID);
			for(Long menuId : sysPackage.getMenuIds()) {
				Optional<Menu> curMenu = allMenus.stream().filter(x -> Func.equals(x.getId(), menuId)).findFirst();
				if(curMenu.isPresent()) {
					sysPackage.getMenuIds().stream().forEach(item -> recursion(allMenus, entityList, curMenu.get(), packageId));
				}
			}
			packageMenuService.saveBatch(entityList);
		}
		return true;
	}
	
	/**
	 * 递归获取父节点ID保存
	 * @param allMenus
	 * @param packageMenus
	 * @param curMenu
	 * @param packageId
	 */
	private void recursion(List<Menu> allMenus, List<SysPackageMenu> packageMenus, Menu curMenu, Integer packageId) {
		Optional<Menu> menu = allMenus.stream().filter(x -> Func.equals(x.getId(), curMenu.getParentId())).findFirst();
		if (menu.isPresent() && !packageMenus.stream().anyMatch(item -> item.getMenuId().longValue() == menu.get().getId().longValue())) {
			packageMenus.add(new SysPackageMenu(packageId, menu.get().getId()));
			recursion(allMenus, packageMenus, menu.get(), packageId);
		}
	}
}
