/**
 * 文件：RoleAuthServiceImpl.java
 * 版本：1.0.0
 * 日期：
 * Copyright &reg;
 * All right reserved.
 */

package com.mortals.xhx.base.system.role.service.impl;

import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.util.DataUtil;
import com.mortals.xhx.base.system.menu.model.MenuEntity;
import com.mortals.xhx.base.system.menu.model.MenuQuery;
import com.mortals.xhx.base.system.menu.model.MenuTreeSelect;
import com.mortals.xhx.base.system.menu.service.MenuService;
import com.mortals.xhx.base.system.resource.service.ResourceService;
import com.mortals.xhx.base.system.role.dao.RoleAuthDao;
import com.mortals.xhx.base.system.role.model.RoleAuthEntity;
import com.mortals.xhx.base.system.role.model.RoleAuthQuery;
import com.mortals.xhx.base.system.role.service.RoleAuthService;
import com.mortals.xhx.common.key.RedisKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

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

import static com.mortals.xhx.common.utils.MenuEncodeUtil.generateMenuUrlCode;

/**
 * <p>Title: 角色资源权限</p>
 * <p>Description: RoleAuthServiceImpl service接口 </p>
 * <p>Copyright: Copyright &reg;  </p>
 * <p>Company: </p>
 *
 * @author
 * @version 1.0.0
 */
@Service("roleAuthService")
public class RoleAuthServiceImpl extends AbstractCRUDServiceImpl<RoleAuthDao, RoleAuthEntity, Long> implements RoleAuthService {

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private MenuService menuService;

    @Autowired
    @Lazy
    private ResourceService resourceService;

    @Override
    public void doDistributionSource(RoleAuthQuery query, Context context) {
        // 删除角色资源老数据
        Long roleId = query.getRoleId();
/*        Map<String, Object> condition = new HashMap<>();
        condition.put("roleId", roleId);
        this.dao.delete(condition);*/
        //todo
        RoleAuthQuery roleAuthQuery = new RoleAuthQuery();
        roleAuthQuery.setRoleId(roleId);
        Long[] delIds = this.find(roleAuthQuery).stream()
                .filter(f -> f.getMenuId() == null)
                .map(f -> f.getId()).toArray(Long[]::new);
        if (!ObjectUtils.isEmpty(delIds)) {
            this.remove(delIds, context);
        }

        List<RoleAuthEntity> list = new ArrayList<>();
        for (Long sourceId : query.getResourceIdList()) {
            RoleAuthEntity entity = new RoleAuthEntity();
            entity.setRoleId(roleId);
            entity.setResourceId(sourceId);
            list.add(entity);
        }
        this.dao.insertBatch(list);

        this.updateUserMenuUrlCache();
    }

    @Override
    public void doDistributionMenu(RoleAuthQuery query, Context context) {
        // 删除角色资源老数据
        Long roleId = query.getRoleId();
/*        Map<String, Object> condition = new HashMap<>();
        condition.put("roleId", roleId);
        this.dao.delete(condition);*/
        //todo
        RoleAuthQuery roleAuthQuery = new RoleAuthQuery();
        roleAuthQuery.setRoleId(roleId);
        Long[] delIds = this.find(roleAuthQuery).stream()
                .filter(f -> f.getMenuId() != null)
                .map(f -> f.getId()).toArray(Long[]::new);
        if (!ObjectUtils.isEmpty(delIds)) {
            this.remove(delIds, context);
        }

        List<RoleAuthEntity> list = new ArrayList<>();
        for (Long menuId : query.getMenuIdList()) {
            RoleAuthEntity entity = new RoleAuthEntity();
            entity.setRoleId(roleId);
            entity.setMenuId(menuId);
            list.add(entity);
        }
        this.dao.insertBatch(list);

        this.updateUserMenuUrlCache();
    }

    @Override
    public List<MenuTreeSelect> editMenu(RoleAuthQuery query, Context context) {
        if (ObjectUtils.isEmpty(query.getRoleId())) throw new AppException("角色不能为空");

        RoleAuthQuery roleAuthQuery = new RoleAuthQuery();
        roleAuthQuery.setRoleId(query.getRoleId());
        Set<Long> menuIdList = this.find(roleAuthQuery).stream()
                .map(f -> f.getMenuId())
                .filter(f -> f != null)
                .collect(Collectors.toSet());
        if (!ObjectUtils.isEmpty(menuIdList)) {
            List<MenuEntity> allMenuList = menuService.find(new MenuQuery());
            List<MenuTreeSelect> menuTreeSelects = menuService.buildMenuTreeChecked(allMenuList, menuIdList);
            return menuTreeSelects;
        }
        return Collections.emptyList();

    }

    private void updateUserMenuUrlCache() {
        //更新用户菜单
        Set<String> hkeys = cacheService.hkeys(RedisKey.KEY_USER_MENU_CACHE);
        for (String userId : hkeys) {
            Set<String> urls = resourceService.findUrlSetByUserId(DataUtil.converStr2Long(userId, 0L));
            String menuUrlCode = generateMenuUrlCode(urls);
            cacheService.hset(RedisKey.KEY_USER_MENU_CACHE, userId, menuUrlCode);
        }
    }

}