package com.cdkj.framework.aspectj;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cdkj.common.constant.Constants;
import com.cdkj.common.enums.EnumDeviceStatus;
import com.cdkj.common.enums.EnumDr;
import com.cdkj.common.exception.CustomException;
import com.cdkj.common.utils.StringUtils;
import com.cdkj.common.utils.ThreadLocalUtil;
import com.cdkj.common.utils.spring.SpringUtils;
import com.cdkj.framework.aspectj.lang.annotation.AnnoEquipment;
import com.cdkj.project.backstage.domain.SysDeviceCenter;
import com.cdkj.project.backstage.service.ISysDeviceCenterService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Optional;

/**
 * 自助机单独设置租户标识
 */
@Aspect
@Component
public class AnnoEquipmentAspect {
    private static final Logger log = LoggerFactory.getLogger(AnnoEquipmentAspect.class);



    // 配置织入点
    @Pointcut("@annotation(com.cdkj.framework.aspectj.lang.annotation.AnnoEquipment)")
    public void logPointCut() {
    }

    @Before("execution(public * com.cdkj.project.equipment..*(..))")
    public void before(JoinPoint joinPoint) {
        if (getAnnotationLog(joinPoint) != null) {
            ThreadLocalUtil.set(getTenant(joinPoint));
        } else {

        }

    }

    /**
     * *处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        if (getAnnotationLog(joinPoint) != null) {

            ThreadLocalUtil.remove();

        }
    }

    /**
     * *拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        if (getAnnotationLog(joinPoint) != null) {
            ThreadLocalUtil.remove();
        }
    }

    private String getTenant(JoinPoint joinPoint) {
        //获取自助机编号,获取自助机所在租户
        String paramsJson=argsArrayToString(joinPoint.getArgs());
        JSONObject jsonObject = JSONObject.parseObject(paramsJson);
        //设备编号
        String equipmentSn=jsonObject.getString(Constants.EQUIPMENT_SN);
        //设备类型
        String equipmentType=jsonObject.getString(Constants.EQUIPMENT_TYPE);
        Optional.ofNullable(equipmentSn).orElseThrow(()->new CustomException("设备号不能为空"));
        Optional.ofNullable(equipmentType).orElseThrow(()->new CustomException("设备类型不能为空"));
        ISysDeviceCenterService sysDeviceCenterService=SpringUtils.getBean(ISysDeviceCenterService.class);
        SysDeviceCenter sysDeviceCenter= new  SysDeviceCenter();
        sysDeviceCenter.setDeviceSn(equipmentSn);
        sysDeviceCenter.setDeviceType(Integer.parseInt(equipmentType));
        SysDeviceCenter sdc= sysDeviceCenterService.selectSysDeviceCenterBySn(sysDeviceCenter);
        Optional.ofNullable(sdc).orElseThrow(()->new CustomException("没有找到该设备"));
        if(EnumDr.DELETED.getCode().equals(sdc.getDr())){
          throw  new CustomException("设备已被删除");
        }else if(EnumDeviceStatus.DISABLE.getCode().equals(sdc.getVstatus())){
            throw  new CustomException("设备已被停用");
        }else if(StringUtils.isBlank(sdc.getTenantPk())){
            throw  new CustomException("设备没有对应的租户");
        }
        return sdc.getTenantPk();
    }




    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray)
    {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0)
        {
            for (int i = 0; i < paramsArray.length; i++)
            {
                if (!isFilterObject(paramsArray[i]))
                {
                    Object jsonObj = JSON.toJSON(paramsArray[i]);
                    if (jsonObj != null) {
                        params += jsonObj.toString() + " ";
                    }
                }
            }
        }
        return params.trim();
    }
    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象,则返回true;否则返回false。
     */
    public boolean isFilterObject(final Object o)
    {
        return o instanceof MultipartFile || o instanceof MultipartFile[] || o instanceof HttpServletRequest || o instanceof HttpServletResponse;
    }
    /**
     * * 是否存在自助机注解
     */
    private AnnoEquipment getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(AnnoEquipment.class);
        }
        return null;
    }

}