package cn.wise.sc.cement.business.service.impl;

import cn.wise.sc.cement.business.entity.SysPermission;
import cn.wise.sc.cement.business.mapper.SysPermissionMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.service.ISysPermissionService;
import cn.wise.sc.cement.business.service.ISysUserService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-20
 */
@Service
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements ISysPermissionService {

	@Resource
	private SysPermissionMapper permissionMapper;
	@Autowired
	private ISysUserService userService;

	/**
	 * 当前登录用户拥有的权限
	 *
	 * @return
	 */
	@Override
	public BaseResponse<List<SysPermission>> current() {
		LoginUser loginUser = userService.getLoginUser();

		List<SysPermission> list = loginUser.getPermissions();
		final List<SysPermission> permissions = list.stream().filter(l -> l.getType().equals(1))
				.collect(Collectors.toList());
		//		setChild(permissions);
		//
		//		return permissions.stream().filter(p -> p.getParentId().equals(0L)).collect(Collectors.toList());
		// 2018.06.09 支持多级菜单
		List<SysPermission> firstLevel = permissions.stream().filter(p -> p.getParentId().equals(0)).collect(Collectors.toList());
		firstLevel.parallelStream().forEach(p -> {
			setChild(p, permissions);
		});

		return BaseResponse.okData(firstLevel);
	}

	private void setChild(SysPermission p, List<SysPermission> permissions) {
		List<SysPermission> child = permissions.parallelStream().filter(a -> a.getParentId().equals(p.getId())).collect(Collectors.toList());
		p.setChild(child);
		if (!CollectionUtils.isEmpty(child)) {
			child.parallelStream().forEach(c -> {
				//递归设置子元素，多级菜单支持
				setChild(c, permissions);
			});
		}
	}

	/**
	 * 菜单列表
	 */
	@Override
	public BaseResponse<List<SysPermission>> permissionsList() {
		List<SysPermission> permissionsAll = this.list();
		List<SysPermission> list = Lists.newArrayList();
		setPermissionsList(0, permissionsAll, list);
		return BaseResponse.okData(list);
	}

	private void setPermissionsList(Integer pId, List<SysPermission> permissionsAll, List<SysPermission> list) {
		for (SysPermission per : permissionsAll) {
			if (per.getParentId().equals(pId)) {
				list.add(per);
				if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
					setPermissionsList(per.getId(), permissionsAll, list);
				}
			}
		}
	}

	/**
	 * 一级菜单
	 *
	 * @return
	 */
	@Override
	public BaseResponse<List<SysPermission>> parents() {
		QueryWrapper<SysPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", 1);
		queryWrapper.eq("parent_id", 0);
		queryWrapper.orderByAsc("parent_id", "sort");
		List<SysPermission> list = this.list(queryWrapper);
		return BaseResponse.okData(list);
	}

	/**
	 * 菜单树
	 *
	 * @return
	 */
	@Override
	public BaseResponse<JSONArray> tree() {
		List<SysPermission> permissionsAll = this.list();
		JSONArray array = new JSONArray();
		setPermissionsTree(0, permissionsAll, array);
		return BaseResponse.okData(array);
	}

	private void setPermissionsTree(Integer pId, List<SysPermission> permissionsAll, JSONArray array) {
		for (SysPermission per : permissionsAll) {
			if (per.getParentId().equals(pId)) {
				String string = JSONObject.toJSONString(per);
				JSONObject parent = (JSONObject) JSONObject.parse(string);
				array.add(parent);

				if (permissionsAll.stream().filter(p -> p.getParentId().equals(per.getId())).findAny() != null) {
					JSONArray child = new JSONArray();
					parent.put("child", child);
					setPermissionsTree(per.getId(), permissionsAll, child);
				}
			}
		}
	}

	/**
	 * 根据角色id获取权限
	 *
	 * @param roleId
	 * @return
	 */
	@Override
	public BaseResponse<List<SysPermission>> listByRoleId(Integer roleId) {
		List<SysPermission> list = permissionMapper.listByRoleId(roleId);
		return BaseResponse.okData(list);
	}

	/**
	 * 新增
	 *
	 * @param permission
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<SysPermission> create(SysPermission permission) {
		if (StringUtils.isEmpty(permission.getName())) {
			return BaseResponse.errorMsg("权限名称不可为空");
		}
		this.save(permission);
		return BaseResponse.okData(permission);
	}

	/**
	 * 修改
	 *
	 * @param permission
	 * @return
	 */
	@Override
	@Transactional
	public BaseResponse<SysPermission> update(SysPermission permission) {
		if (StringUtils.isEmpty(permission.getName())) {
			return BaseResponse.errorMsg("权限名称不可为空");
		}
		this.updateById(permission);
		return BaseResponse.okData(permission);
	}

}
