/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.ruoyi.common.wrapper;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.wrapper.BaseWrapper;
import com.ruoyi.common.wrapper.Wrapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * controller结果包装的aop
 *
 * @author xuyuxiang
 * @date 2020/7/24 17:42
 */
@Slf4j
@Aspect
@Component
public class WrapperAspect {


    /**
     * 切入点
     *
     * @author xuyuxiang
     * @date 2020/7/24 17:42
     */
    @Pointcut("@annotation(com.ruoyi.common.wrapper.Wrapper)")
    private void wrapperPointcut() {
    }

    /**
     * 执行具体的包装过程
     *
     * @author xuyuxiang
     * @date 2020/7/24 17:44
     */
    @AfterReturning(pointcut = "wrapperPointcut()", returning = "result")
    public Object doAfterReturning(JoinPoint joinPoint, Object result) throws InstantiationException, IllegalAccessException {

        return processWrapping(joinPoint, result);
    }

    /**
     * 具体包装过程
     *
     * @author xuyuxiang
     * @date 2020/7/24 17:53
     */
    @SuppressWarnings("all")
    private Object processWrapping(JoinPoint joinPoint, Object originResult) throws IllegalAccessException, InstantiationException {

        // 获取@Wrapper注解
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Wrapper wrapperAnnotation = method.getAnnotation(Wrapper.class);

        // 获取注解上的处理类
        Class<? extends BaseWrapper<?>>[] baseWrapperClasses = wrapperAnnotation.value();

        // 如果注解上的为空直接返回
        if (ObjectUtil.isEmpty(baseWrapperClasses)) {
            return originResult;
        }

        if (originResult instanceof TableDataInfo) {
            //分页
            // 获取TableDataInfo中的值
            TableDataInfo responseData = (TableDataInfo) originResult;
            List list = responseData.getRows();
            // 将page中所有records都包装一遍
            ArrayList<Object> maps = new ArrayList<>();
            for (Object wrappedItem : list) {
                maps.add(this.wrapPureObject(wrappedItem, baseWrapperClasses));
            }
            responseData.setRows(maps);
            return responseData;

        } else if (originResult instanceof R) {
            // 获取R中的值
            R r = (R) originResult;
            Object data = r.getData();
            // 如果是List类型
            if (data instanceof Collection) {
                // 获取原有的List
                Collection collection = (Collection) data;
                // 将page中所有records都包装一遍
                ArrayList<Object> maps = new ArrayList<>();
                for (Object wrappedItem : collection) {
                    maps.add(this.wrapPureObject(wrappedItem, baseWrapperClasses));
                }
                r.setData(maps);
            }// 如果是Array类型
            else if (ArrayUtil.isArray(data)) {
                // 获取原有的Array
                Object[] objects = this.objToArray(data);
                // 将array中所有records都包装一遍
                ArrayList<Object> maps = new ArrayList<>();
                for (Object wrappedItem : objects) {
                    maps.add(this.wrapPureObject(wrappedItem, baseWrapperClasses));
                }

                r.setData(maps);
            }

            // 如果是Object类型
            else {
                r.setData(this.wrapPureObject(data, baseWrapperClasses));
            }

            return r;

        } else {
            log.warn(">>> 当前请求的返回结果无需转换，直接返回原值！");
            return originResult;
        }

    }

    /**
     * 原始对象包装成一个map的过程
     * <p>
     * 期间多次根据BaseWrapper接口方法执行包装过程
     *
     * @author xuyuxiang
     * @date 2020/7/24 21:40
     */
    @SuppressWarnings("all")
    private Object wrapPureObject(Object originModel, Class<? extends BaseWrapper<?>>[] baseWrapperClasses) {

        // 经过多个包装类填充属性
        try {
            for (Class<? extends BaseWrapper<?>> baseWrapperClass : baseWrapperClasses) {
                BaseWrapper baseWrapper = baseWrapperClass.newInstance();
                Object incrementFieldsMap = baseWrapper.doWrap(originModel);
                return incrementFieldsMap;
            }
        } catch (Exception e) {
            log.error(">>> 原始对象包装过程，字段转化异常：{}", e.getMessage());
            throw new ServiceException("原始对象包装过程，字段转化异常");
        }

        return null;
    }

    /**
     * Object转为一个array，确保object为数组类型
     *
     * @author xuyuxiang
     * @date 2020/7/24 22:06
     */
    private Object[] objToArray(Object object) {
        int length = Array.getLength(object);
        Object[] result = new Object[length];
        for (int i = 0; i < result.length; i++) {
            result[i] = Array.get(object, i);
        }
        return result;
    }

}
