package com.yeejoin.amos.maintenance.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.RedisUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.maintenance.business.feign.JCSFeignClient;
import com.yeejoin.amos.maintenance.exception.PermissionException;
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;
import org.typroject.tyboot.core.foundation.utils.Bean;

import java.util.Map;

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

    @Autowired
    RedisUtils redisUtils;
    @Autowired
    JCSFeignClient jcsFeignClient;

    final int HTTP_OK_STATUS = 200;

    @Before(value = "@annotation(com.yeejoin.amos.maintenance.core.framework.PersonIdentify) && @annotation(permission)")
    public void personIdentity(JoinPoint joinPoint, PersonIdentify permission) throws PermissionException {
        ReginParams reginParam = JSON.parseObject(redisUtils.get(buildKey(RequestContext.getToken())).toString(), ReginParams.class);
        if (permission.isNeedIdentity() && reginParam != null) {
            //调用jcs，进行人员身份判断，是维保公司人员还是业主单位人员
            String userId = reginParam.getUserModel().getUserId();
            FeignClientResult responseModel = jcsFeignClient.getUserUnit(userId);
            if (ObjectUtils.isEmpty(responseModel.getResult()) || responseModel.getStatus() != HTTP_OK_STATUS) {
                throw new RuntimeException(responseModel.getDevMessage());
            }
            ReginParams.PersonIdentity personIdentity = (ReginParams.PersonIdentity) Bean.mapToBean((Map<String, Object>) responseModel.getResult(), ReginParams.PersonIdentity.class);
            reginParam.setPersonIdentity(personIdentity);
            redisUtils.set(buildKey(RequestContext.getToken()), JSONObject.toJSONString(reginParam));
        }
    }

    public String buildKey(String token) {
        return "region_" + token;
    }

}
