package com.fdkankan.scene.Interceptor;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.ServerCode;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.user.SSOLoginHelper;
import com.fdkankan.common.util.WebUtil;
import com.fdkankan.redis.constant.RedisKey;
import com.fdkankan.redis.util.RedisUtil;
import com.fdkankan.scene.entity.ScenePlus;
import com.fdkankan.scene.service.IScenePlusService;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Log4j2
@Aspect
@Component
@Order(101)
public class CheckCooperationPermitAspect {

	@Autowired
	private SSOLoginHelper ssoLoginHelper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IScenePlusService scenePlusService;


	@Pointcut("@annotation(com.fdkankan.scene.annotation.CheckCooperationPermit)")
	public void checkCooperationPermit() {
	}

	/**
	 * 前置通知 用于判断用户协作场景是否有协作权限
	 *
	 * @param joinPoint
	 *            切点
	 * @throws IOException
	 */
	@Before("checkCooperationPermit()")
	public void doBefore(JoinPoint joinPoint) throws Exception {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		// 读取session中的用户
		com.fdkankan.common.model.SSOUser user = ssoLoginHelper.loginCheckV3(request.getHeader("token"));
		if(Objects.isNull(user)){
			throw new BusinessException(ErrorCode.TOKEN_NOT_FOUND);
		}
		String num = WebUtil.getNum(joinPoint, request);
		if(StrUtil.isEmpty(num)){
			throw new BusinessException(ErrorCode.PARAM_REQUIRED);
		}


		//判断是不是场景原用户,如果是，跳出
        ScenePlus scenePlus= scenePlusService.getScenePlusByNum(num);
		if(Objects.isNull(scenePlus)){
			throw new BusinessException(ErrorCode.FAILURE_CODE_5005);
		}
        if(scenePlus.getUserId().equals(user.getId())){
            return;
        }

        //如果不是用户自己的场景，判断是否有协作权限
        String userId = redisUtil.hget(RedisKey.SCENE_COOPERATION_NUM_USERID, num);
        if(StrUtil.isEmpty(userId)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5014);
        }
        if(!userId.equals(String.valueOf(user.getId()))){
            throw new BusinessException(ErrorCode.FAILURE_CODE_5014);
        }
	}

}
