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

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

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.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 java.util.*;

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
    @Lazy
    private ResourceService resourceService;

    @Override
    public void doDistributionSource(RoleAuthQuery query) {
        // 删除角色资源老数据
        Long roleId = query.getRoleId();
        Map<String, Object> condition = new HashMap<>();
        condition.put("roleId", roleId);
        this.dao.delete(condition);

        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();
    }

    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);
        }
    }

}