package cn.freemud;

import cn.freemud.amp.service.OrderCallBackMQService;
import cn.freemud.entities.dto.UserLoginInfoDto;
import cn.freemud.entities.dto.WechatReportOrderDto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freemud.application.sdk.api.ordercenter.entities.vo.OrderCallBackRequestVo;
import com.freemud.application.sdk.api.ordercenter.request.OrderExtInfoDto;
import com.freemud.application.sdk.api.ordercenter.response.orderInfo.OrderInfoReqs;
import org.junit.Test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;


public class AllTests {

    /**
     *  该方法 用于测试 推送微信支付上报获取参数
     * @param args
     */
    public static void main(String[] args) {
        String str = "{\"abnormalDesc\":\"\",\"abnormalState\":0,\"actualPayAmount\":1.0,\"afterSalesOrderList\":[],\"appId\":\"wxfa229ba41652df7f\",\"barCounter\":\"005\",\"bizType\":1,\"businessDay\":1652371200000,\"canRefund\":true,\"cancelReason\":\"\",\"companySelfCode\":\"\",\"createTime\":1652446892000,\"daySeq\":4,\"deliveryContactInfoList\":[{\"addressDetail\":\"上海市虹口区塘沽路456号\",\"city\":\"\",\"contactsName\":\"\",\"expressNo\":\"0\",\"extInfo\":\"\",\"infoType\":1,\"latitude\":0E-7,\"longitude\":0E-7,\"mobile\":\"13166430721\",\"province\":\"\",\"region\":\"\",\"relateObjectType\":1,\"street\":\"\",\"telephone\":\"\",\"thirdDeliveryId\":\"0\",\"tripDist\":0}],\"deliveryPromise\":0,\"deliveryState\":0,\"dinersNumber\":0,\"dispenseStatus\":1,\"downstreamPosCode\":\"0\",\"downstreamThirdOrderCode\":\"0\",\"evaluationState\":0,\"expressChannelCode\":\"\",\"expressChannelName\":\"\",\"expressNo\":\"\",\"expressType\":0,\"extInfo\":\"{\\\"appid\\\":\\\"wxfa229ba41652df7f\\\",\\\"deliveryHoursDayStart\\\":\\\"\\\",\\\"endTransId\\\":\\\"20220513100000210002111094704150\\\",\\\"fmId\\\":\\\"8802865243694612136531288\\\",\\\"openid\\\":\\\"oHZsJ5d-gbBvUNBoVrhZCV1rWcJE\\\",\\\"paidMember\\\":false,\\\"payDate\\\":\\\"2022-05-13 21:01:39\\\",\\\"payTransId\\\":\\\"8802865243694612136531288\\\",\\\"prepayId\\\":\\\"wx132101331091569eff3057deaf2fb50000\\\",\\\"serviceTime\\\":30,\\\"sessionKey\\\":\\\"rsGu1d6PwtARrxIYzkHxxg==\\\"}\",\"immediately\":true,\"isParent\":false,\"localTableKey\":\"\",\"marketingCode\":\"\",\"marketingType\":0,\"needInvoice\":false,\"note\":\"\",\"operator\":\"\",\"orderArea\":\"0\",\"orderClient\":2,\"orderCode\":\"24369461192889072600004\",\"orderCostDetailList\":[],\"orderExtended\":{\"createTime\":1652446892000,\"id\":243694611928890726,\"isDeleted\":false,\"orderClientGroup\":\"\",\"orderClientGroupCode\":\"\",\"orderCode\":\"24369461192889072600004\",\"orderId\":243694611928890726,\"partnerId\":\"2865\",\"sendWord\":\"\",\"spellGroupCode\":\"\",\"storeId\":\"8630021001941262-8630021001941262\",\"storeNameEn\":\"\",\"updateTime\":1652446892000,\"userPhone\":\"\",\"version\":0},\"orderInvoice\":{\"address\":\"\",\"bankCardNo\":\"\",\"content\":\"\",\"invoiceBank\":\"\",\"invoiceNo\":\"\",\"invoiceUrl\":\"\",\"itemId\":\"\",\"partnerId\":\"\",\"phoneNo\":\"\",\"pickUpNo\":\"\",\"taxNo\":\"\",\"title\":\"\",\"userId\":\"\"},\"orderItemList\":[{\"canRefund\":true,\"categoryId\":\"0\",\"categoryName\":\"0\",\"extInfo\":\"{\\\"score\\\": 0, \\\"linkedId\\\": \\\"\\\", \\\"showPrice\\\": 1, \\\"isSendGoods\\\": false, \\\"cartGoodsUid\\\": \\\"8c31801197f747e4ae9780c8d248e965\\\"}\",\"id\":243694611948813672,\"ignoreInOrderClose\":false,\"marketingCode\":\"0\",\"marketingType\":0,\"nickName\":\"\",\"note\":\"\",\"openId\":\"\",\"originalProductType\":0,\"parentProductId\":\"0\",\"photoUrl\":\"\",\"productCode\":\"20220424001\",\"productForeignName\":\"\",\"productForeignProperty\":\"\",\"productForeignSpecName\":\"\",\"productId\":\"239055192095472910\",\"productName\":\"可乐\",\"productPicUrl\":\"https://picture.sandload.cn/1650780459062.jpg\",\"productPrice\":1.0,\"productProperty\":\"\",\"productQuantity\":1,\"productSeq\":0,\"productSharePrice\":0.0,\"productSpec\":\"239055192095472910\",\"productSpecName\":\"可乐\",\"productType\":1,\"productUnit\":\"\",\"productUpc\":\"\",\"productWeightUnit\":0,\"salePrice\":1.0,\"settlementPrice\":1.0,\"thirdProductId\":\"20220424001\",\"userId\":\"\",\"weight\":0.00}],\"orderSendCouponRespList\":[],\"orderSettlementDetailList\":[{\"agentDiscountAmount\":0.0,\"carrierDiscountAmount\":0.0,\"extInfo\":\"\",\"externalObjectId\":\"\",\"externalObjectName\":\"优惠总金额\",\"externalObjectSubId\":\"\",\"ignoreInDiscountAmount\":false,\"isOnline\":true,\"note\":\"\",\"number\":0,\"platformDiscountAmount\":0.0,\"platformServiceAmount\":0.0,\"productId\":\"0\",\"productSeq\":0,\"prospectiveAmount\":0.0,\"settlementAmount\":1.0,\"settlementType\":205,\"shopAmount\":0.0,\"shopDiscountAmount\":0.0}],\"orderState\":1,\"orderSubState\":0,\"orderType\":1,\"originalAmount\":1.0,\"parentCode\":\"0\",\"partnerId\":\"2865\",\"partnerName\":\"\",\"payChannel\":\"10211\",\"payChannelName\":\"微信\",\"payChannelType\":1,\"payRequestNo\":\"8802865243694612136531288\",\"payState\":2,\"payTime\":1652446899684,\"payType\":1,\"pickUpGoodsNo\":\"5055\",\"posCode\":\"\",\"posTableKey\":\"\",\"printNum\":0,\"settlementAmount\":1.0,\"sourceType\":0,\"storeId\":\"8630021001941262-8630021001941262\",\"storeName\":\"沙县小吃\",\"storeUnifyId\":\"0\",\"suspendDesc\":\"\",\"suspendState\":0,\"thirdOrderCode\":\"24369461192889072600004\",\"thirdStoreId\":\"\",\"toStoreId\":\"0\",\"updateTime\":1652446892000,\"userId\":\"3647332017865482101\",\"userName\":\"\",\"weight\":0.00}";
        OrderCallBackRequestVo body = new OrderCallBackRequestVo();
        body.setContent(str);
        body.setOperateType(0);
        body.setMsgType("1");
        OrderInfoReqs orderInfoReqs = JSONObject.parseObject(body.getContent(), OrderInfoReqs.class);
        OrderCallBackMQService orderCallBackMQService = new OrderCallBackMQService();
        OrderExtInfoDto orderExtInfoDto = JSONObject.parseObject(orderInfoReqs.getExtInfo(), OrderExtInfoDto.class);
        orderExtInfoDto.setPlatformMchId("null");
        UserLoginInfoDto userLoginInfoDto = new UserLoginInfoDto();
        userLoginInfoDto.setWxAppid(orderInfoReqs.getAppId());
        userLoginInfoDto.setOpenId(orderExtInfoDto.getOpenid());
        userLoginInfoDto.setSessionKey(orderExtInfoDto.getSessionId());
//        WechatReportOrderDto wechatReportOrderDto = orderCallBackMQService.getWechatReportOrderDto(orderInfoReqs, orderExtInfoDto, userLoginInfoDto);
//        System.out.println(JSON.toJSONString(wechatReportOrderDto));
    }

    @Test
    public void entityTest() throws Exception {
        int i = 0;
        Set<Class<?>> classes = getClasses("cn.freemud.entities");
        for (Class clazz : classes) {
            try {
                Object object = clazz.newInstance();
                Method[] methods = clazz.getDeclaredMethods();

                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        method.invoke(object);
                    } else {
                        Type[] paramType = method.getGenericParameterTypes();
                        Object paramObj = null;
                        try {
                            paramObj = Class.forName(paramType[0].getTypeName()).newInstance();
                        } catch (Exception ignore) {
                            paramObj = Class.forName(paramType[0].getTypeName()).getDeclaredConstructor(String.class).newInstance("0");
                        }
                        try {
                            method.invoke(object, paramObj);
                        } catch (Exception ignore) {
                            method.invoke(object, null);
                        }

                    }
                }
            } catch (Exception ignore) {
            }
        }
    }

    @Test
    public void classTest() throws Exception {
        int i = 0;
        Set<Class<?>> classes = getClasses("cn.freemud");
        for (Class clazz : classes) {
            try {
                Object object = clazz.newInstance();
                Method[] methods = clazz.getDeclaredMethods();

                for (Method method : methods) {

                    Type[] paramTypes = method.getGenericParameterTypes();
                    Object[] paramObjs = new Object[paramTypes.length];
                    try {
                        for (int index = 0, len = paramTypes.length; i < len; i++) {
                            Object paramObj = Class.forName(paramTypes[index].getTypeName()).newInstance();
                            paramObjs[index] = paramObj;
                        }
                    } catch (Exception ex) {

                    }

                    try {
                        method.invoke(object, paramObjs);
                    } catch (Exception ignore) {
                        method.invoke(object, null);
                    }


                }
            } catch (Exception ignore) {
            }
        }
    }

    /**
     * 从包package中获取所有的Class
     *
     * @param pack
     * @return
     */
    public static Set<Class<?>> getClasses(String pack) {
        Set<Class<?>> classes = new LinkedHashSet<Class<?>>();

        boolean recursive = true;

        String packageName = pack;
        String packageDirName = packageName.replace('.', '/');

        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(
                    packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements()) {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath,
                            recursive, classes);
                }
            }
        } catch (IOException e) {

        }

        return classes;
    }


    /**
     * 以文件的形式来获取包下的所有Class
     *
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName,
                                                        String packagePath, final boolean recursive, Set<Class<?>> classes) {

        File dir = new File(packagePath);

        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }

        File[] dirfiles = dir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return (recursive && file.isDirectory())
                        || (file.getName().endsWith(".class"));
            }
        });

        for (File file : dirfiles) {
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "."
                                + file.getName(), file.getAbsolutePath(), recursive,
                        classes);
            } else {
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                }
            }
        }
    }
}
