package com.yeejoin.amos.boot.module.common.api.core.framework;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.UserDto;
import com.yeejoin.amos.boot.module.common.api.exception.PermissionException;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ResponseBody;
import org.typroject.tyboot.core.foundation.context.RequestContext;

/**
 * @author DELL
 */
@Aspect
@Component
@ResponseBody
@Order(value = 1)
public class PersonIdentifyAspect {

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    private IOrgUsrService orgUsrService;

    @Before(value = "@annotation(com.yeejoin.amos.boot.module.common.api.core.framework.PersonIdentify) && @annotation(permission)")
    public void personIdentity(JoinPoint joinPoint, PersonIdentify permission) throws PermissionException {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        if (permission.isNeedIdentity() && reginParam != null) {
            String userId = reginParam.getUserModel().getUserId();
            UserDto userDto = orgUsrService.getUserParentInfo(userId);
            ReginParams.PersonIdentity personIdentity = new ReginParams.PersonIdentity();
            personIdentity.setBizOrgCode(userDto.getBizOrgCode());
            personIdentity.setCompanyId(userDto.getCompanyId());
            personIdentity.setCompanyName(userDto.getCompanyName());
            personIdentity.setPersonSeq(userDto.getPersonSeq());
            personIdentity.setPersonName(userDto.getPersonName());
            personIdentity.setIdentityType(userDto.getIdentityType());
            reginParam.setPersonIdentity(personIdentity);
            redisUtils.set(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken()), JSONObject.toJSONString(reginParam));
        }
    }

}
