package com.dayou.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dayou.annotation.DataPermission;
import com.dayou.annotation.Transfer;
import com.dayou.entity.ResourceTransfer;
import com.dayou.enums.BusinessResourceEnum;
import com.dayou.service.IResourceTransferService;
import com.dayou.utils.LoginContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 类说明：
 *
 * @author: wucl
 * @since: 2023/6/1
 * created with IntelliJ IDEA.
 */
@Slf4j
@Component
@Aspect
public class ResourceTransferAop {

    @Autowired
    private IResourceTransferService resourceTransferService;


    @AfterReturning("@annotation(transfer)")
    public void afterResourceTransfer(JoinPoint joinPoint, Transfer transfer) throws Throwable {
        BusinessResourceEnum businessResourceEnum = transfer.resourceEnum();
        Object[] args = joinPoint.getArgs();
        List<?> param = new ArrayList<>(Arrays.asList(args)).stream().filter(p -> !(p instanceof ServletResponse))
                .filter(e -> !(e instanceof MultipartFile))
                .collect(Collectors.toList());
        String params = JSON.toJSONString(param, true);
        JSONObject jsonObject = JSON.parseArray(params).getJSONObject(0);
        ResourceTransfer rt = new ResourceTransfer();
        rt.setCurrentUserId(Long.valueOf(jsonObject.get("userId")+""));
        rt.setOriginalUserId(Long.valueOf(jsonObject.get("originalUserId")+""));
        rt.setResourceType(businessResourceEnum);
        rt.setResourceId(Long.valueOf(jsonObject.get("id")+""));
        rt.setOperatorId(LoginContext.getCurrentUserId());
        resourceTransferService.save(rt);
    }
}