package com.liquidnet.service.platform.service.impl.kylin;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.core.type.TypeReference;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.feign.stone.api.FeignStoneIntegralClient;
import com.liquidnet.service.goblin.constant.GoblinRedisConst;
import com.liquidnet.service.goblin.constant.GoblinStatusConst;
import com.liquidnet.service.goblin.dto.vo.GoblinOrderAttrVo;
import com.liquidnet.service.goblin.dto.vo.GoblinOrderSkuVo;
import com.liquidnet.service.goblin.dto.vo.GoblinStoreOrderVo;
import com.liquidnet.service.goblin.entity.GoblinOrderAttr;
import com.liquidnet.service.goblin.entity.GoblinStoreOrder;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.entity.KylinPerformanceRelations;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.slime.constant.SlimeAuthorizationConst;
import com.liquidnet.service.slime.constant.SlimeRedisConst;
import com.liquidnet.service.slime.dto.param.SlimeAuthorizationPermissionParam;
import com.liquidnet.service.slime.dto.vo.*;
import com.liquidnet.service.slime.entity.*;
import com.liquidnet.service.slime.mapper.*;
import com.liquidnet.service.platform.utils.ObjectUtil;
import com.liquidnet.service.stone.constant.StoneConstant;
import com.liquidnet.service.stone.entity.StoneScoreLogs;
import com.liquidnet.service.stone.mapper.StoneScoreLogsMapper;
import com.mongodb.BasicDBObject;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class DataImpl {

    @Autowired
    RedisDataSourceUtil redisDataSourceUtil;

    //    private static final String SQL_URL = "jdbc:mysql://39.107.71.112:3308/test_ln_scene";
//    private static final String SQL_USER = "testmall";
//    private static final String SQL_PWD = "zhengzai!mYT";
//    private static final String PHP_DB = "testmall";
    private static final String SQL_URL = "jdbc:mysql://zhengzairead.rwlb.rds.aliyuncs.com:3306/mall";
    private static final String SQL_USER = "readonly";
    private static final String SQL_PWD = "ZWDsf8Fy";
    private static final String PHP_DB = "mall";

    //迁移场地和场地认领关系
    public void fieldData() {
        try {
            String sql = "select m.id                                     as 'order_id',\n" +
                    "       m.matter_num                             as 'master_order_code',\n" +
                    "       m.matter_num                             as 'order_code',\n" +
                    "       m.out_trade_no                           as 'pay_code',\n" +
                    "       m.user_id_new             as 'user_id',\n" +
                    "       m.matter_amount                          as 'price_total',\n" +
                    "       (m.matter_amount - m.coupon_type2_price) as 'price_actual',\n" +
                    "       m.price_send                             as 'price_express',\n" +
                    "       m.coupon_type2_price                     as 'price_coupon',\n" +
                    "       m.coupon_type2_price                     as 'price_voucher',\n" +
                    "       m.status                                 as 'status',\n" +
                    "       m.pay_type                               as 'pay_type',\n" +
                    "       m.source                                 as 'device_from',\n" +
                    "       m.payment_type                           as 'payment_type',\n" +
                    "       m.trade_no                               as 'payment_id',\n" +
                    "       m.source                                 as 'source',\n" +
                    "       m.version                                as 'version',\n" +
                    "       m.pay_time                               as 'pay_time',\n" +
                    "       m.coupon_type2_id                        as 'ucoupon_id',\n" +
                    "       m.post_name                              as 'express_contacts',\n" +
                    "       m.post_phone                             as 'express_phone',\n" +
                    "       m.post_address                           as 'express_address',\n" +
                    "       m.post_address                           as 'express_address_detail',\n" +
                    "       m.created_at                             as 'created_at'\n" +
                    "from matters as m\n" +
                    "where m.status = 1\n" +
                    "  and m.created_at >= '2022-01-01 00:00:00'";
            Connection connection = DriverManager.getConnection(SQL_URL, SQL_USER, SQL_PWD);
            //查询数据
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSetImpl row = (ResultSetImpl) preparedStatement.executeQuery();
            //数据迁移
            while (row.next()) {
                GoblinStoreOrderVo orderVo = GoblinStoreOrderVo.getNew();
                orderVo.setStoreId("dab4742921ba3555700896c4fafbee5b");
                orderVo.setStoreName("摩登天空自营店");
                orderVo.setPayCountdownMinute(5);
                orderVo.setStatus(GoblinStatusConst.Status.ORDER_STATUS_4.getValue());
                orderVo.setOrderId(row.getString("order_id"));
                orderVo.setMasterOrderCode(row.getString("master_order_code"));
                orderVo.setOrderCode(row.getString("order_code"));
                orderVo.setPayCode(row.getString("pay_code"));
                orderVo.setUserId(row.getString("user_id"));
//                orderVo.setUserId("938039519718440965850184");
                orderVo.setPriceTotal(row.getBigDecimal("price_total"));
                orderVo.setPriceActual(row.getBigDecimal("price_actual"));
                orderVo.setPriceExpress(row.getBigDecimal("price_express"));
                orderVo.setPriceCoupon(row.getBigDecimal("price_coupon"));
                orderVo.setPriceVoucher(row.getBigDecimal("price_voucher"));
                orderVo.setPayType(row.getString("pay_type"));
                orderVo.setDeviceFrom(row.getString("device_from"));
                orderVo.setPaymentType(row.getString("payment_type"));
                orderVo.setPaymentId(row.getString("payment_id"));
                orderVo.setSource(row.getString("source"));
                orderVo.setVersion(row.getString("version"));
                orderVo.setPayTime(row.getString("pay_time"));
                orderVo.setUcouponId(row.getString("ucoupon_id"));
                orderVo.setCreatedAt(row.getString("created_at"));
                GoblinOrderAttrVo orderAttrVo = GoblinOrderAttrVo.getNew();
                orderAttrVo.setOrderId(orderVo.getOrderId());
                orderAttrVo.setExpressContacts(row.getString("express_contacts"));
                orderAttrVo.setExpressPhone(row.getString("express_phone"));
                orderAttrVo.setExpressAddress(row.getString("express_address"));
                orderAttrVo.setExpressAddressDetail(row.getString("express_address_detail"));
                orderAttrVo.setCreatedAt(orderVo.getCreatedAt());
                orderVo.setOrderAttrVo(orderAttrVo);

                String sqlSku = "select mi.id                      as 'order_sku_id',\n" +
                        "       mi.good_id                 as 'spu_id',\n" +
                        "       mi.product_id              as 'sku_id',\n" +
                        "       mi.buy_number              as 'num',\n" +
                        "       mi.price                   as 'sku_price',\n" +
                        "       (mi.price * mi.buy_number) as 'sku_price_actual',\n" +
                        "       gic.name                   as 'sku_name',\n" +
                        "       p.cover                    as 'sku_image',\n" +
                        "       gic.value                  as 'sku_specs',\n" +
                        "       g.title                    as 'spu_name',\n" +
                        "       g.cover                    as 'spu_pic',\n" +
                        "       mi.created_at              as 'created_at'\n" +
                        "from matter_items as mi\n" +
                        "         inner join goods as g on g.id = mi.good_id\n" +
                        "         inner join products as p on p.id = mi.product_id\n" +
                        "         inner join good_item_contents as gic on gic.goods_item_id = mi.product_id\n" +
                        "where matter_id = " + orderVo.getOrderId() + "\n" +
                        "  and gic.goods_kinds = 1;";
                //查询数据
                PreparedStatement preparedStatementSku = connection.prepareStatement(sqlSku);
                ResultSetImpl rowSku = (ResultSetImpl) preparedStatementSku.executeQuery();
                //数据迁移
                List<String> orderSkuIds = CollectionUtil.linkedListString();
                while (rowSku.next()) {
                    GoblinOrderSkuVo skuVo = GoblinOrderSkuVo.getNew();
                    skuVo.setOrderId(orderVo.getOrderId());
                    skuVo.setStatus(GoblinStatusConst.Status.ORDER_STATUS_4.getValue());
                    skuVo.setOrderSkuId(rowSku.getString("order_sku_id"));
                    skuVo.setSpuId(rowSku.getString("spu_id"));
                    skuVo.setSkuId(rowSku.getString("sku_id"));
                    skuVo.setNum(rowSku.getInt("num"));
                    skuVo.setSkuPrice(rowSku.getBigDecimal("sku_price"));
                    skuVo.setSkuPriceActual(rowSku.getBigDecimal("sku_price_actual"));
                    skuVo.setSkuName(rowSku.getString("sku_specs"));
                    skuVo.setSkuImage(rowSku.getString("sku_image"));
                    skuVo.setSkuSpecs("[{\"specName\":\"" + rowSku.getString("sku_name") + "\",\"specVname\":\"" + rowSku.getString("sku_specs") + "\"}]");//
                    skuVo.setSpuName(rowSku.getString("spu_name"));
                    skuVo.setCreatedAt(orderVo.getCreatedAt());
                    setGoblinOrderSku(skuVo.getOrderSkuId(), skuVo);
                    orderSkuIds.add(skuVo.getOrderSkuId());
                }
                orderVo.setOrderSkuVoIds(orderSkuIds);
                setGoblinOrder(orderVo.getOrderId(), orderVo);
                addOrderList(orderVo.getUserId(), orderVo.getOrderId());

                rowSku.close();
                preparedStatementSku.close();
            }
            row.close();
            preparedStatement.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 赋值 订单相关vo
    public void setGoblinOrder(String orderId, GoblinStoreOrderVo vo) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_ORDER.concat(orderId);
        redisDataSourceUtil.getRedisKylinUtil().set(redisKey, vo);
    }

    // 赋值 订单相关Skuvo
    public void setGoblinOrderSku(String orderSkuId, GoblinOrderSkuVo vo) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_ORDER_SKU.concat(orderSkuId);
        redisDataSourceUtil.getRedisKylinUtil().set(redisKey, vo);
    }

    // 添加 订单id列表
    public void addOrderList(String uid, String orderId) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_ORDER_LIST.concat(uid);
        List<String> list = getOrderList(uid);
        if (list.size() >= 40) {
            list.remove(0);
            list.add(orderId);
        } else {
            list.add(orderId);
        }
        redisDataSourceUtil.getRedisKylinUtil().set(redisKey, list);
    }

    // 获取 订单id列表
    public List<String> getOrderList(String uid) {
        String redisKey = GoblinRedisConst.REDIS_GOBLIN_ORDER_LIST.concat(uid);
        Object obj = redisDataSourceUtil.getRedisKylinUtil().get(redisKey);
        if (obj == null) {
            return CollectionUtil.arrayListString();
        } else {
            return (List<String>) obj;
        }
    }
}
