package com.zcxk.service;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zcxk.dao.MenuMapper;
import com.zcxk.dao.TenantMenuMapper;
import com.zcxk.entity.MenuEntity;
import com.zcxk.entity.TenantMenuEntity;
import com.zcxk.model.LoginUser;
import com.zcxk.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.google.common.collect.Lists.newArrayList;

/**
 *
 * 菜单Service接口
 * @author: WYY
 * @date 2020-10-26 16:15
 */
@Service
public class MenuService extends ServiceImpl<MenuMapper,MenuEntity> {

	@Resource
	private MenuMapper menuMapper;
	@Resource
	private TenantMenuMapper tenantMenuMapper;

	/**
	 * 自定义分页查询，含关联实体对像
	 */
	public IPage<MenuEntity> findPage(IPage<MenuEntity> page, MenuEntity menuEntity) {
		Page<MenuEntity> ipage = menuMapper.findPage(page, menuEntity);
		return ipage;
	}
	/**
	 * 查询权限标志
	 */
	public List<String> getAuthCode() {
		List<String> list = new ArrayList<>();
		List<MenuEntity> menuEntities = findAllList(new MenuEntity());
		for (MenuEntity menuEntity : menuEntities) {
			if (menuEntity.getPermissionFlag() != null && menuEntity.getPermissionFlag() != ""&& menuEntity.getPermissionFlag().length()>0)
				list.add(menuEntity.getPermissionFlag());
		}
		return list;
	}
	/**
	 * 查列表
	 */
	public List<MenuEntity> findAllList(MenuEntity menuEntity) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		String tenantId = currentUser.getTenantId();
		String name = menuEntity.getName();
		menuEntity.setTenantId(tenantId);
		List<MenuEntity> menuEntities = new ArrayList<>();
		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				menuEntities = menuMapper.findList(menuEntity);
				break;
			case "-999"://租户管理员查询租户菜单
				menuEntities = menuMapper.findTenantList(menuEntity);
				break;
			default://普通用户按角色查询租户菜单
				menuEntities = menuMapper.findUserList(name,tenantId,userId);
				break;
		}

		return menuEntities;
	}
	/**
	 * 查列表
	 */
	public List<MenuEntity> findList(MenuEntity menuEntity) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		String tenantId = currentUser.getTenantId();
		String name = menuEntity.getName();
		menuEntity.setTenantId(tenantId);
		List<MenuEntity> menuEntities = new ArrayList<>();
		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				menuEntities = menuMapper.findList(menuEntity);
				break;
			case "-999"://租户管理员查询租户菜单
				menuEntities = menuMapper.findTenantList(menuEntity);
				break;
			default://普通用户按角色查询租户菜单
				menuEntities = menuMapper.findUserList(name,tenantId,userId);
				break;
		}

		List<MenuEntity> menuTree = getMenuTree(menuEntities, Long.valueOf(0), 1);
		return menuTree;
	}

	public static List<MenuEntity> getMenuTree(List<MenuEntity> list, Long id, Integer leve) {
		List<MenuEntity> temList = newArrayList();
		if (list != null) {
			for (MenuEntity menuEntity : list) {
				if (id.equals(menuEntity.getParentMenuId())) {
					List<MenuEntity> chidren = getMenuTree(list, menuEntity.getId(), ++leve);
					MenuEntity temMeanu = new MenuEntity();
					BeanUtils.copyProperties(menuEntity, temMeanu);
					temMeanu.setChildren(chidren);
					temList.add(temMeanu);
					leve--;
				}

			}
		}
		if (temList.size() > 0) {
			return temList;
		} else {
			return null;
		}
	}


	/**
	 * 按父级节点查列表
	 */
	public List<MenuEntity> findMenuByParentIds(List<Long> ids) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		List<MenuEntity> menuEntities = new ArrayList<>();
		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				menuEntities = menuMapper.findMenuByParentIds(ids);
				break;
			case "-999"://租户管理员查询租户菜单
				menuEntities = menuMapper.findTenantMenuByParentIds(currentUser.getTenantId(), ids);
				break;
			default://普通用户按角色查询租户菜单
				menuEntities = menuMapper.findTenantMenuByParentIds(currentUser.getTenantId(), ids);
				break;
		}
		return menuEntities;
	}
	/**
	 * 批量删除
	 */
	@Transactional(rollbackFor = Exception.class)
	public boolean delMenuByIds(Long[] ids) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		boolean isOk = false;
		for(Long id : ids) {
			switch (userType) {
				case "-9999"://超级管理员直接删除系统菜单
					isOk = this.removeById(id);
					break;
				case "-999"://租户管理员查询租户菜单
					isOk = menuMapper.updateState(id);
					break;
				default://普通用户按角色查询租户菜单
					isOk = menuMapper.updateState(id);
					break;
			}
		}
		return isOk;
	}

	/**
	 * 单个删除
	 */
	public boolean delMenuById(Long id) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		boolean isOk = false;
		switch (userType) {
			case "-9999"://超级管理员直接删除系统菜单
				isOk = this.removeById(id);
				break;
			case "-999"://租户管理员查询租户菜单
				isOk = menuMapper.updateState(id);
				break;
			default://普通用户按角色查询租户菜单
				isOk = menuMapper.updateState(id);
				break;
		}
		return isOk;
	}



	/**
	 * 保存
	 */
	public boolean addMenu(MenuEntity menu) {
		if (this.save(menu)) {
			return true;
		}
		return false;
	}

	/**
	 * 修改根居ID
	 */
	public boolean updateMenuById(MenuEntity menu) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
         //-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		TenantMenuEntity tenantMenuEntity = new TenantMenuEntity();
		if(!userType.equals("-9999")) {
			MenuEntity menuEntity = menuMapper.findTenantByMenuId(currentUser.getTenantId(), menu.getId());
			tenantMenuEntity.setId(menuEntity.getId());
			tenantMenuEntity.setDateUpdate(new Date());
			tenantMenuEntity.setUpdateBy(currentUser.getUsername());
			tenantMenuEntity.setLinkPath(menu.getLinkPath());
			tenantMenuEntity.setMenuImage(menu.getMenuImage());
			tenantMenuEntity.setEnglishName(menu.getEnglishName());
			tenantMenuEntity.setMenuDynamicImage(menu.getMenuDynamicImage());
			tenantMenuEntity.setMenuName(menu.getName());
			tenantMenuEntity.setMenuSeq(menu.getSeq());
			tenantMenuEntity.setRemark(menu.getRemark());
		}
		boolean isOk = false;
		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				isOk = this.updateById(menu);
				break;
			case "-999"://租户管理员查询租户菜单
				isOk = tenantMenuMapper.updateById(tenantMenuEntity) > 0 ? true : false;
				break;
			default://普通用户按角色查询租户菜单
				isOk = tenantMenuMapper.updateById(tenantMenuEntity) > 0 ? true : false;
				break;
		}
		return isOk;
	}
	/**
	 * 根居ID获取对象
	 */
	public MenuEntity findMenuById(Long id) {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		MenuEntity menuEntity = new MenuEntity();
		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				menuEntity = menuMapper.findMenuById(id);;
				break;
			case "-999"://租户管理员查询租户菜单
				menuEntity = menuMapper.findUserMenuById(currentUser.getTenantId(),id);
				break;
			default://普通用户按角色查询租户菜单
				menuEntity = menuMapper.findUserMenuById(currentUser.getTenantId(),id);
				break;
		}
		return menuEntity;
	}

	public List<MenuEntity> findUserFirstMenu() {
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		List<MenuEntity> menuEntities = new ArrayList<>();
		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				menuEntities = menuMapper.findAllFirstMenu();
				break;
			case "-999"://租户管理员查询租户菜单
				menuEntities = menuMapper.findTenantFirstMenu(currentUser.getTenantId());
				break;
			default:    //其他租户用户暂时不区分类型
				menuEntities = menuMapper.findUserFirstMenu(currentUser.getTenantId(), userId);
				break;
		}
		List<MenuEntity> menuAllEntities = menuMapper.findAllFirstMenu();
		Map<Long, MenuEntity> map = menuAllEntities.stream().collect(Collectors.toMap(MenuEntity::getId, item -> item));
		if(!userType.equals("-9999")) {
			for (MenuEntity item : menuEntities) {
				item.setIsOwner(1);
				map.remove(item.getId());
			}
			for (MenuEntity item : map.values()) {
				item.setIsOwner(0);
				menuEntities.add(item);
			}
		}
		return menuEntities;
	}
	public List<MenuEntity> findUserMenu(String appId) {
		List<MenuEntity> menuTree = getMenuTree(getMenus(appId), Long.valueOf(0), 1);
		return menuTree;
	}
	public List<MenuEntity> findTenantMenu() {
		List<MenuEntity> menuTree = getMenuTree(menuMapper.findSystemTenantMenu(), Long.valueOf(0), 1);
		return menuTree;
	}
    private List<MenuEntity>getMenus(String appId){
		LoginUser currentUser = UserUtil.getCurrentUser();
		Integer userId = currentUser.getId();
		//-999租户管理员  -9999超级管理员  2普通用户
		String userType = currentUser.getType();
		List<MenuEntity> menuEntities= new ArrayList<>();

		switch (userType) {
			case "-9999"://超级管理员查询所有系统菜单
				menuEntities = menuMapper.findSystemUserMenu(appId);
				break;
			case "-999"://租户管理员查询租户菜单
				menuEntities = menuMapper.findTenantUserMenu(currentUser.getTenantId(),appId);
				break;
			default://普通用户按角色查询租户菜单
				menuEntities = menuMapper.findUserMenu(currentUser.getTenantId(),userId, appId);
				break;
		}
		return menuEntities;
	}

	public Map<String, String> getUserMenuByUid(String appId) {
		List<MenuEntity> menuEntities=getMenus(appId);
		Map<String,String>urls=new HashMap<>();
		menuEntities.forEach(menuEntity -> {
			urls.put(menuEntity.getLinkPath(),1+"");
		});
		return urls;
	}
}
