package com.zm.order.tool.server.stream.convert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zm.order.tool.server.model.Order;
import com.zm.order.tool.server.stream.SQLCategory;
import com.zm.order.tool.server.stream.SQLRouteDefinition;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单数据流转换器
 *
 * <p>
 *      streamIn：转换写入参数，持久化至数据库中
 *
 *      streamOut：转换查询参数，返回至接口result
 * </p>
 *
 * {@link SQLCategory}
 *
 * {@link SQLRouteDefinition}
 *
 * @author nianchang
 * @date 2023/03/07 3:20 下午
 */
@Component
@SuppressWarnings("all")
public class OrderStreamConverter extends AbstractStreamConverter {

    @Override
    public Integer route() {
        return SQLCategory.ORDERS.getCode();
    }

    public static void main(String[] args) {
        String s = "{\"orderNo\":\"D00085342660377747456\",\"userId\":0,\"sellerId\":218443,\"storeId\":244919,\"sellerRemarks\":null,\"sourceNo\":\"2504449662000423\",\"source\":16,\"orderType\":1,\"orderSubType\":null,\"performanceType\":2,\"status\":20,\"payStatus\":1,\"totalAmount\":1650,\"actualAmount\":850,\"payAmount\":850,\"itemAmount\":1200,\"discountAmount\":500,\"freightAmount\":350,\"isImmediatePerformance\":0,\"payType\":7,\"payModel\":1,\"mobile\":\"178****4628,1084\",\"orderAt\":1740110446000,\"packAmount\":100,\"buyerRemarks\":\"【JD310552606055】 缺货时电话与我沟通 \",\"buyerRemarksId\":null,\"itemList\":[{\"sellerId\":218443,\"storeId\":244919,\"goodsId\":\"0\",\"itemId\":\"2426443630\",\"itemImage\":\"\",\"itemName\":\"椰果\",\"marketPrice\":null,\"num\":1,\"itemPrice\":200,\"costPrice\":200,\"itemSpec\":\"[{\\\"specName\\\":\\\"规格\\\",\\\"specValue\\\":\\\"不分装（备注加入哪一杯）\\\"}]\",\"itemUnit\":null,\"packAmount\":0,\"paidAmount\":200,\"productNo\":null,\"itemSign\":null,\"itemBarcode\":null,\"discountAmount\":0,\"memberPrice\":null,\"discountList\":null,\"extraMap\":{\"distId\":\"2426443630\",\"goodsAttach\":\"[]\",\"produceDuration\":0,\"itemSkuId\":\"2426443630\",\"uniqueKey\":\"1\",\"costPrice\":2.0,\"weight\":null,\"goodsSkuId\":null,\"isLineup\":1,\"distSkuId\":null,\"foodCode\":null,\"isMatchCenter\":0},\"orderAt\":null,\"isTimeDiscount\":null,\"isGift\":0,\"activityId\":null,\"setMealItemList\":null,\"itemBatchingList\":[],\"itemType\":null,\"isRequired\":null,\"tradeMark\":null,\"orderItemId\":null,\"expressTemplateId\":null,\"posItemWeight\":null},{\"sellerId\":218443,\"storeId\":244919,\"goodsId\":\"0\",\"itemId\":\"2421737186\",\"itemImage\":\"\",\"itemName\":\"茉莉奶绿\",\"marketPrice\":null,\"num\":1,\"itemPrice\":1000,\"costPrice\":1000,\"itemSpec\":\"[{\\\"specName\\\":\\\"规格\\\",\\\"specValue\\\":\\\"大杯\\\"}]\",\"itemUnit\":null,\"packAmount\":0,\"paidAmount\":1000,\"productNo\":null,\"itemSign\":null,\"itemBarcode\":null,\"discountAmount\":0,\"memberPrice\":null,\"discountList\":null,\"extraMap\":{\"distId\":\"2421737186\",\"uniqueKey\":\"2\",\"costPrice\":10.0,\"weight\":null,\"goodsSkuId\":null,\"isLineup\":1,\"distSkuId\":null,\"isMatchCenter\":0,\"goodsAttach\":\"[]\",\"produceDuration\":0,\"itemSkuId\":\"2421737186\",\"goodsPractice\":\"[{\\\"name\\\":\\\"做法1\\\",\\\"value\\\":\\\"少冰\\\"},{\\\"name\\\":\\\"做法2\\\",\\\"value\\\":\\\"5分糖\\\"}]\",\"foodCode\":null},\"orderAt\":null,\"isTimeDiscount\":null,\"isGift\":0,\"activityId\":null,\"setMealItemList\":null,\"itemBatchingList\":[],\"itemType\":null,\"isRequired\":null,\"tradeMark\":null,\"orderItemId\":null,\"expressTemplateId\":null,\"posItemWeight\":null}],\"orderDiscountList\":[{\"discountAmount\":500,\"discountId\":\"0\",\"discountLevel\":null,\"discountName\":\"优惠劵\",\"discountText\":\"优惠劵\",\"discountSummary\":\"优惠\",\"discountType\":31,\"orderNo\":null,\"extraMap\":{\"shopPart\":0,\"uniqueKey\":null,\"platFromPart\":0},\"userId\":null,\"joinNum\":null},{\"discountAmount\":300,\"discountId\":\"0\",\"discountLevel\":null,\"discountName\":\"商家满免运费\",\"discountText\":\"商家满免运费\",\"discountSummary\":\"优惠\",\"discountType\":31,\"orderNo\":null,\"extraMap\":{\"shopPart\":3.0,\"uniqueKey\":null,\"platFromPart\":0.0},\"userId\":null,\"joinNum\":null}],\"extraMap\":{\"shopPart\":3.0,\"userInfo\":{\"userId\":0,\"userName\":\"严\",\"phone\":null,\"avatar\":null,\"openId\":null,\"appId\":null},\"extraCost\":null,\"freightPlatformSettle\":true,\"shopInfo\":{\"id\":244919,\"name\":\"淮安淮阴师范附属中学店\",\"lat\":\"33.606182\",\"lng\":\"119.009601\",\"address\":\"江苏省淮安市清江浦区北京北路北京新村10区4幢商铺\",\"fullAddress\":\"江苏省淮安市清江浦区\",\"cityId\":320800,\"cityName\":\"淮安市\",\"districtId\":320812,\"districtName\":\"清江浦区\",\"provinceId\":\"320000\",\"provinceName\":\"江苏省\",\"contactPhone\":\"152****1375\",\"code\":\"22000136\",\"managerPhone\":\"\",\"contactTel\":\"\"},\"platformPart\":0.0,\"greeting\":null,\"merchantDeliverySubsidy\":300,\"logisticsCode\":null,\"isMatchCenter\":0,\"commision_amount\":0,\"businessDate\":\"2025-02-21\",\"inCome\":10.0,\"privacyMobile\":\"178****4628,1084\",\"mealSetting\":\"noon\",\"deliveryMode\":1,\"discountFreightAmount\":0,\"deliveryCode\":null},\"addr\":{\"orderNo\":null,\"acceptName\":\"严\",\"area\":null,\"areaName\":\"\",\"city\":null,\"cityName\":\"\",\"doorNumber\":\"\",\"label\":null,\"lat\":\"33.608211\",\"lng\":\"118.996939\",\"mobile\":\"178****4628,1084\",\"province\":null,\"provinceName\":\"\",\"sex\":null,\"street\":\"江苏淮安市清江浦区柳树湾街道奥林晴园小区-10号楼五单元510\",\"zip\":null,\"distributionRange\":null,\"countryCode\":null,\"addressDescribe\":\" 江苏淮安市清江浦区柳树湾街道奥林晴园小区-10号楼五单元510 \"},\"invoiceType\":null,\"isReceipt\":null,\"thirdPayNo\":null,\"payNo\":null,\"storeOrderNo\":\"1\",\"receiptTerminal\":null,\"performanceStatus\":0,\"performancePlatform\":\"11\",\"performanceInfoMap\":{\"reserveTime\":null,\"pickUpTime\":null,\"reserveTimeStart\":null,\"reserveTimeEnd\":null,\"reserveTakeOutTime\":null,\"deliveryAt\":null,\"floorCode\":null,\"platformType\":null,\"deliveryStatus\":null,\"splitStatus\":null,\"deliveryOrderNo\":null,\"carrierName\":null,\"carrierPhone\":null,\"cancelDesc\":null,\"cancelReasonCode\":null,\"callNo\":null,\"receiverMobile\":null,\"statusName\":null,\"statusDesc\":null,\"mainCallNo\":null,\"bizCallType\":null,\"reserve_time\":null},\"payer\":null,\"payInfoMap\":{\"useWallet\":null,\"usePhysicalCard\":null,\"walletAmount\":0,\"physicalCardAmount\":0,\"amount\":null,\"payDetailsList\":null,\"walletPayDetail\":[],\"physicalCardPayDetail\":[],\"receiptAmount\":null,\"orderPayType\":null,\"entityCardIds\":null},\"payAt\":1740110446000,\"addrId\":null,\"isUseWallet\":null,\"useWallet\":null,\"completedAt\":null,\"payDetailsList\":[{\"amount\":850,\"incomeAmount\":null,\"commissionAmount\":null,\"payNo\":null,\"payType\":7,\"sellerId\":218443,\"storeId\":244919,\"thirdPayNo\":null,\"payAt\":1740110446000,\"extraMap\":null}],\"fromSystem\":1,\"isUseFlavorCard\":null,\"flavorCardMinus\":null,\"tableCardNum\":null,\"crowdorder\":null,\"pointCalCardId\":null,\"itemOperationRecordList\":null,\"pointPackAmount\":null,\"familyCardNo\":null,\"openId\":null,\"confirmPayNum\":null,\"confirmPayUserId\":null,\"balancePassword\":null,\"observerTag\":0,\"depositGiftCardBizId\":null,\"advanceGiftCardNoMap\":null,\"failureReason\":null,\"otherPointAmount\":null,\"scheduledTime\":null,\"preTimeConfig\":null,\"outTradeNo\":null,\"payNotifyUrl\":null,\"failMeituanCouponList\":null,\"kaoJiangSwitch\":null,\"itemCommentIdList\":null,\"currency\":\"CNY\"}";
        Order order = JSONObject.parseObject(s, Order.class);
        order.setBizType(5);
        OrderStreamConverter orderStreamConverter = new OrderStreamConverter();
        orderStreamConverter.streamOut(order);
    }

    @Override
    public Object streamIn(Object data) {
        // 区分单个和批量写入数据结构有所区别
        // StrictMap --> [(collection, ArrayList), (list, ArrayList);]
        if (data instanceof DefaultSqlSession.StrictMap) {
            DefaultSqlSession.StrictMap dataSource = (DefaultSqlSession.StrictMap) data;
            Object collection = dataSource.get(BATCH_DATA);
            if (collection instanceof List) {
                dataSource.put(BATCH_DATA, parseAndSet(collection));
            }
            Object list = dataSource.get(BATCH_DATA0);
            if (list instanceof List) {
                dataSource.put(BATCH_DATA0, parseAndSet(list));
            }
            return dataSource;
        }
        else if (data instanceof Order) {
            Order order = (Order) data;
            if (!FILTER.contains(order.getBizType())) {
                return data;
            }
            return parse(data, SQLCategory.ORDERS);
        }
        return data;
    }

    private ArrayList parseAndSet(Object data) {
        ArrayList<Order> orderList = (ArrayList) data;
        ArrayList<Order> convertedList = new ArrayList<>(orderList.size());
        for (Order order : orderList) {
            convertedList.add((Order) parse(order, SQLCategory.ORDERS));
        }
        return convertedList;
    }

    private ArrayList tempParseAndSet(Object data) {
        List<JSONObject> orderList = (List) data;
        ArrayList<Order> convertedList = new ArrayList<>(orderList.size());
        for (JSONObject json : orderList) {
            Order order = JSON.parseObject(json.toString(), Order.class);
            convertedList.add((Order) parse(order, SQLCategory.ORDERS));
        }
        return convertedList;
    }

    @Override
    public Object streamOut(Object data) {
        if (data instanceof ArrayList) {
            return real(data);
        } else if (data instanceof Order) {
            return reverseParse(data, SQLCategory.ORDERS);
        }
        return data;
    }

    private ArrayList real(Object data) {
        ArrayList<Order> orderList = (ArrayList) data;
        ArrayList<Order> convertedList = new ArrayList<>(orderList.size());
        if (!CollectionUtils.isEmpty(orderList)) {
            for (Order order : orderList) {
                convertedList.add((Order) reverseParse(order, SQLCategory.ORDERS));
            }
        }
        return convertedList;
    }

    private ArrayList temp(Object data) {
        ArrayList<JSONObject> orderList = (ArrayList) data;
        ArrayList<Order> convertedList = new ArrayList<>(orderList.size());
        for (JSONObject json : orderList) {
            Order order = JSON.parseObject(json.toString(), Order.class);
            convertedList.add((Order) reverseParse(order, SQLCategory.ORDERS));
        }
        return convertedList;
    }
}
