package com.liquidnet.service.adam.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.adam.dto.AdamMemberOrderCallbackParam;
import com.liquidnet.service.adam.dto.AdamMemberOrderCodeParam;
import com.liquidnet.service.adam.dto.AdamMemberOrderParam;
import com.liquidnet.service.adam.dto.AdamMemberOrderResult;
import com.liquidnet.service.adam.dto.vo.*;
import com.liquidnet.service.adam.service.AdamRdmService;
import com.liquidnet.service.adam.service.IAdamMemberOrderService;
import com.liquidnet.service.adam.service.IAdamUserMemberService;
import com.liquidnet.service.adam.util.MemberUtil;
import com.liquidnet.service.adam.util.QueueUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AdamMemberOrderServiceImpl implements IAdamMemberOrderService {
    @Autowired
    Environment env;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    QueueUtils queueUtils;
    @Autowired
    AdamRdmService adamRdmService;
    @Autowired
    IAdamUserMemberService adamUserMemberService;

    @Override
//    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ResponseDto<AdamMemberOrderResult> buyMemberOrMemberCode(AdamMemberOrderParam param) {
        AdamMemberVo memberVo = adamRdmService.getMemberVoByMemberId(param.getMemberId());
        if (null == memberVo) {
            return ResponseDto.failure(ErrorMapping.get("10201"));
        }
        AdamMemberPriceVo memberPriceVo = adamRdmService.getMemberPriceVoByPriceId(param.getMemberId(), param.getMemberPriceId());
        if (null == memberPriceVo) {
            return ResponseDto.failure(ErrorMapping.get("10202"));
        }

        LocalDateTime now = LocalDateTime.now();
        String nowStr = DateUtil.Formatter.yyyyMMddHHmmss.format(now);
        String orderNo = IDGenerator.nextSnowId().toString().concat("V");
        String clientIp = CurrentUtil.getCliIpAddr();

        // 调取对应支付接口
        LinkedMultiValueMap<String, String> payParam = CollectionUtil.linkedMultiValueMapStringString();
        payParam.add("type", "VIP");// TICKET,PRODUCT,COST,MBEANS,LIVE,VIDEO,VIP,CLUB
        payParam.add("price", String.valueOf(memberPriceVo.getPrice()));
        payParam.add("name", memberVo.getName());
        payParam.add("detail", "正在现场:购买会员".concat(param.getMode() == 0 ? "" : "码"));
        payParam.add("orderCode", orderNo);
        payParam.add("clientIp", clientIp);
        payParam.add("notifyUrl", env.getProperty("liquidnet.url-pay.callback"));
        payParam.add("deviceFrom", param.getDeviceFrom());
        payParam.add("payType", param.getPayType());

        String payUri = "/" + param.getDeviceFrom() + "/" + param.getPayType();
        switch (payUri) {// applet/wepay | js/wepay | wap/alipay | wap/wepay | app/iappay | app/wepay
            /**
             * auth_code open_id为空时必传 微信网页静默获取，可用于后台请求获取openid
             * open_id auth_code为空时必传 微信网页静默获取auth_code，然后请求后台获取openid
             * 建议传open_id
             */
            case "/applet/wepay":
            case "/js/wepay":
                if (StringUtils.isEmpty(param.getOpenId())) {
                    return ResponseDto.failure(ErrorMapping.get("10204"));
                }
                payParam.add("openId", param.getOpenId());
                break;
            case "/wap/alipay":
                if (StringUtils.isEmpty(param.getShowUrl()) || StringUtils.isEmpty(param.getReturnUrl())) {
                    return ResponseDto.failure(ErrorMapping.get("10205"));
                }
                // 取消支付，点击取消支付宝回调地址
                payParam.add("showUrl", param.getShowUrl());
                // 支付成功，点击完成支付宝回调地址
                payParam.add("returnUrl", param.getReturnUrl() + orderNo);
                break;
            case "/app/iappay":
                if (StringUtils.isEmpty(param.getOpenId())) {
                    return ResponseDto.failure(ErrorMapping.get("10206"));
                }
                // iOS App唯一标识，目前为：com.zhengzai.zhengzai-tv
                payParam.add("bundleId", "com.zhengzai.zhengzai-tv");
                // iTunes上架的商品唯一标识
                payParam.add("productId", param.getProductId());
                break;
        }
        payParam.add("createDate", nowStr);
        payParam.add("expireTime", "5");// 过期时间，单位分钟，默认5

        // 生成订单信息
        AdamMemberOrderVo memberOrderVo = new AdamMemberOrderVo();
        memberOrderVo.setOrderNo(orderNo);
        memberOrderVo.setMemberId(param.getMemberId());
        memberOrderVo.setDays(memberPriceVo.getDays());
        memberOrderVo.setMemberPriceId(param.getMemberPriceId());
        memberOrderVo.setCreatedAt(now);
        memberOrderVo.setMemberName(memberVo.getName());
        memberOrderVo.setMode(param.getMode());
        memberOrderVo.setBirthday(param.getBirthday());
        memberOrderVo.setDeviceFrom(param.getDeviceFrom());
        memberOrderVo.setPayType(param.getPayType());
        memberOrderVo.setState(0);// 0-待支付
        memberOrderVo.setUid(CurrentUtil.getCurrentUid());
        memberOrderVo.setPrice(param.getPrice());
        memberOrderVo.setClientIp(clientIp);
        memberOrderVo.setVersion(CurrentUtil.getCliVersion());
        memberOrderVo.setSource(CurrentUtil.getCliSource());

        if (!adamRdmService.setShotMemberOrderVoByOrderNo(orderNo, memberOrderVo)) {
            log.warn("###购买会员创建订单失败[memberOrderVo:{}]", JsonUtils.toJson(memberOrderVo));
            return ResponseDto.failure(ErrorMapping.get("10210"));
        }
        AdamMemberOrderResult result = AdamMemberOrderResult.getNew();
        try {
//            String url = env.getProperty("liquidnet.url-pay.pay") + payUri;
            String url = env.getProperty("liquidnet.url-pay.pay");
            log.debug("HttpUtil.resquest.url:{},param:{}", url, JsonUtils.toJson(payParam));
            long s = System.currentTimeMillis();
            String respStr = HttpUtil.post(url, payParam);
            log.debug("#PHP.API耗时:{}ms", System.currentTimeMillis() - s);
            log.debug("HttpUtil.response.body:{}", respStr);
            JsonNode respJNode = JsonUtils.fromJson(respStr, JsonNode.class);
            if (null == respJNode || !"0".equals(respJNode.get("code").asText())) {
                log.warn("###购买会员调用支付失败[respStr:{}]", respStr);
                return ResponseDto.failure(ErrorMapping.get("10210"));
            }
            JsonNode respDataJNode = respJNode.get("data");
            result.setCode(respDataJNode.get("code").asText());
            result.setPayData(respDataJNode.get("payData"));

            memberOrderVo.setPayNo(result.getCode());
        } catch (Exception e) {
            log.warn("###购买会员下单调用支付中心异常[payParam:{}]", JsonUtils.toJson(payParam), e);

            return ResponseDto.failure(ErrorMapping.get("10203"));
        }
        adamRdmService.setShotMemberOrderVoByOrderNo(orderNo, memberOrderVo);

        result.setOrderNo(memberOrderVo.getOrderNo());
        result.setShowUrl(param.getShowUrl());
        result.setReturnUrl(param.getReturnUrl());
        return ResponseDto.success(result);
    }

    @Override
    public ResponseDto<Object> paymentNotifyCallBack(AdamMemberOrderCallbackParam parameter) {
        AdamMemberOrderVo handleMemberOrderVo = adamRdmService.getShotMemberOrderVoByOrderNo(parameter.getOrderCode());
        if (null == handleMemberOrderVo) {
            return ResponseDto.failure(ErrorMapping.get("10501"), parameter);
        }
        // AdamMemberConst.STATUS_*:0-待支付,1-已支付,2-已过期,3-超时付,4-退款中,5-退款完成
        if (1 == handleMemberOrderVo.getState() || 3 == handleMemberOrderVo.getState()) {
            return ResponseDto.failure(ErrorMapping.get("10502"), parameter);
        }
        if (parameter.getPrice().compareTo(handleMemberOrderVo.getPrice()) != 0) {
            // 订单金额比对
            return ResponseDto.failure(ErrorMapping.get("10503"), parameter);
        }
        AdamMemberPriceVo memberPriceVo = adamRdmService.getMemberPriceVoByPriceId(
                handleMemberOrderVo.getMemberId(), handleMemberOrderVo.getMemberPriceId());
        if (null == memberPriceVo) {
            return ResponseDto.failure(ErrorMapping.get("10504"));
        }
        /**
         * 购买方式[order.mode]:
         * 0-购买会员
         * 1-购买会员码(不需要填写地址)
         * 2-使用会员码(购买的) 仅限从未购买过会员的用户使用，需要填写地址
         * 3-使用礼包码(赠送的) 仅限从未购买过会员的用户使用，不需要填写地址
         */
        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> operationObjs = CollectionUtil.linkedListObjectArr(),
                updateMemberOrderObjs = CollectionUtil.linkedListObjectArr();
        LocalDateTime now = LocalDateTime.now();
        if (0 == handleMemberOrderVo.getMode()) {// 购买会员回调
            AdamUserMemberVo existUserMemberVo = adamRdmService.getUserMemberVoByUid(handleMemberOrderVo.getUid());
            if (null == existUserMemberVo) {// 创建会员
                String memberNo = adamUserMemberService.getNextMemberNo(handleMemberOrderVo.getMemberId());

                AdamUserMemberVo initUserMemberVo = AdamUserMemberVo.getNew();
                initUserMemberVo.setUid(handleMemberOrderVo.getUid());
                initUserMemberVo.setMemberId(handleMemberOrderVo.getMemberId());
                initUserMemberVo.setMemberNo(memberNo);
                initUserMemberVo.setState(1);// 1-正常,2-失效
                initUserMemberVo.setExpiryAt(now.plusDays(memberPriceVo.getDays()).with(LocalTime.MAX));
                initUserMemberVo.setCreatedAt(now);

                long s = System.currentTimeMillis();
                mongoTemplate.insert(initUserMemberVo, AdamUserMemberVo.class.getSimpleName());
                log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
                s = System.currentTimeMillis();
                adamRdmService.setUserMemberVoByUid(handleMemberOrderVo.getUid(), initUserMemberVo);
                log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

                handleMemberOrderVo.setMemberNo(memberNo);

                toMqSqls.add(SqlMapping.get("adam_user_member.add"));
                operationObjs.add(new Object[]{
                        initUserMemberVo.getUid(), initUserMemberVo.getMemberId(), initUserMemberVo.getMemberNo(),
                        initUserMemberVo.getState(), initUserMemberVo.getExpiryAt(), initUserMemberVo.getCreatedAt()
                });
            } else {// 续费
                LocalDateTime currentExpiryAt = existUserMemberVo.getExpiryAt();
                LocalDateTime expiryAt = (currentExpiryAt.isBefore(now) ? now : currentExpiryAt).plusDays(memberPriceVo.getDays()).with(LocalTime.MAX);

                long s = System.currentTimeMillis();
                mongoTemplate.getCollection(AdamUserMemberVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("uid").is(existUserMemberVo.getUid())).getQueryObject(),
                        new Document("$set", new Document("expiryAt", expiryAt).append("state", 1))
                );
                log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
                existUserMemberVo.setState(1);
                existUserMemberVo.setExpiryAt(expiryAt);
                s = System.currentTimeMillis();
                adamRdmService.setUserMemberVoByUid(handleMemberOrderVo.getUid(), existUserMemberVo);
                log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

                handleMemberOrderVo.setMemberNo(existUserMemberVo.getMemberNo());

                toMqSqls.add(SqlMapping.get("adam_user_member.update"));
                operationObjs.add(new Object[]{
                        existUserMemberVo.getState(), existUserMemberVo.getExpiryAt(), now, existUserMemberVo.getUid()
                });
            }
        }
        if (1 == handleMemberOrderVo.getMode()) {// 购买会员码回调
            String memberNo = adamUserMemberService.getNextMemberNo(handleMemberOrderVo.getMemberId());

            AdamMemberCodeVo initMemberCodeVo = new AdamMemberCodeVo();
            initMemberCodeVo.setCode(MemberUtil.buyCode());
            initMemberCodeVo.setMemberId(handleMemberOrderVo.getMemberId());
            initMemberCodeVo.setMemberPriceId(handleMemberOrderVo.getMemberPriceId());
            initMemberCodeVo.setType(1);// 1-购买,2-赠送
            initMemberCodeVo.setMemberNo(memberNo);
            initMemberCodeVo.setState(0);
            initMemberCodeVo.setBuyOrderNo(handleMemberOrderVo.getOrderNo());
            initMemberCodeVo.setBuyUid(handleMemberOrderVo.getUid());
            initMemberCodeVo.setBuyAt(handleMemberOrderVo.getCreatedAt());
            initMemberCodeVo.setCreatedAt(now);

            long s = System.currentTimeMillis();
            mongoTemplate.insert(initMemberCodeVo, AdamMemberCodeVo.class.getSimpleName());
            log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
            s = System.currentTimeMillis();
            adamRdmService.setMemberCodeVoByCode(initMemberCodeVo.getCode(), initMemberCodeVo);
            log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

            toMqSqls.add(SqlMapping.get("adam_member_code.add"));
            operationObjs.add(new Object[]{
                    initMemberCodeVo.getCode(), initMemberCodeVo.getType(), initMemberCodeVo.getMemberId(), initMemberCodeVo.getMemberPriceId(),
                    initMemberCodeVo.getMemberNo(), initMemberCodeVo.getState(), initMemberCodeVo.getCreatedAt(),
                    initMemberCodeVo.getBuyOrderNo(), initMemberCodeVo.getBuyUid(), initMemberCodeVo.getBuyAt()
            });
        }
        handleMemberOrderVo.setPaymentAt(DateUtil.Formatter.yyyyMMddHHmmss.parse(parameter.getPaymentAt()));
        handleMemberOrderVo.setUpdatedAt(now);
        handleMemberOrderVo.setState(1);// 1-已支付

        long s = System.currentTimeMillis();
        mongoTemplate.insert(handleMemberOrderVo, AdamMemberOrderVo.class.getSimpleName());
        log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);

        toMqSqls.add(SqlMapping.get("adam_member_order.add"));
        updateMemberOrderObjs.add(new Object[]{
                handleMemberOrderVo.getOrderNo(), handleMemberOrderVo.getUid(), handleMemberOrderVo.getMode(), handleMemberOrderVo.getPrice(),
                handleMemberOrderVo.getPricePaid(), handleMemberOrderVo.getMemberName(), handleMemberOrderVo.getMemberId(), handleMemberOrderVo.getMemberPriceId(),
                handleMemberOrderVo.getDays(), handleMemberOrderVo.getState(), handleMemberOrderVo.getMemberNo(), handleMemberOrderVo.getBirthday(),
                handleMemberOrderVo.getDeviceFrom(), handleMemberOrderVo.getPayType(), handleMemberOrderVo.getPayNo(), handleMemberOrderVo.getPaymentAt(),
                handleMemberOrderVo.getCreatedAt(), handleMemberOrderVo.getClientIp(), handleMemberOrderVo.getSource(), handleMemberOrderVo.getVersion()
        });

        s = System.currentTimeMillis();
        adamRdmService.setShotMemberOrderVoByOrderNo(handleMemberOrderVo.getOrderNo(), handleMemberOrderVo);
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

        s = System.currentTimeMillis();
        queueUtils.sendMsgByRedis(
                com.liquidnet.service.base.constant.MQConst.AdamQueue.SQL_UMEMBER.getKey(),
                SqlMapping.gets(toMqSqls, operationObjs, updateMemberOrderObjs)
        );
        log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);
        return ResponseDto.success();
    }

    @Override
    public ResponseDto<AdamMemberOrderResult> exchangeMemberCode(AdamMemberOrderCodeParam param) {
        AdamMemberCodeVo memberCodeVo = adamRdmService.getMemberCodeVoByCode(param.getMemberCode());
        if (null == memberCodeVo) {
            return ResponseDto.failure(ErrorMapping.get("10207"));
        }
        if (memberCodeVo.getState() != 0) {
            return ResponseDto.failure(ErrorMapping.get(memberCodeVo.getState() == 1 ? "10208" : "10209"));
        }
        AdamMemberPriceVo memberPriceVo = adamRdmService.getMemberPriceVoByPriceId(memberCodeVo.getMemberId(), memberCodeVo.getMemberPriceId());
        if (null == memberPriceVo) {
            return ResponseDto.failure(ErrorMapping.get("10202"));
        }
        AdamMemberVo memberVo = adamRdmService.getMemberVoByMemberId(memberCodeVo.getMemberId());

        LocalDateTime now = LocalDateTime.now();
        // 创建会员订单
        AdamMemberOrderVo initMemberOrderVo = AdamMemberOrderVo.getNew();
        initMemberOrderVo.setOrderNo(IDGenerator.nextSnowId().concat("V"));
        initMemberOrderVo.setUid(CurrentUtil.getCurrentUid());
        initMemberOrderVo.setMode(param.getMode());
        initMemberOrderVo.setPrice(memberPriceVo.getPrice());
        initMemberOrderVo.setPricePaid(BigDecimal.ZERO);
        initMemberOrderVo.setMemberName(memberVo.getName());
        initMemberOrderVo.setMemberId(memberCodeVo.getMemberId());
        initMemberOrderVo.setMemberPriceId(memberCodeVo.getMemberPriceId());
        initMemberOrderVo.setDays(memberPriceVo.getDays());
        initMemberOrderVo.setState(1);// 0-待支付,1-已支付
        initMemberOrderVo.setMemberNo(memberCodeVo.getMemberNo());
        initMemberOrderVo.setBirthday(param.getBirthday());
        initMemberOrderVo.setDeviceFrom(param.getDeviceFrom());
        initMemberOrderVo.setPayType(param.getMode() == 2 ? "vipcode" : "giftcode");
        initMemberOrderVo.setPayNo(memberCodeVo.getCode());
        initMemberOrderVo.setPaymentAt(now);
        initMemberOrderVo.setCreatedAt(now);
        initMemberOrderVo.setClientIp(CurrentUtil.getCliIpAddr());
        initMemberOrderVo.setSource(CurrentUtil.getCliSource());
        initMemberOrderVo.setVersion(CurrentUtil.getCliVersion());

        LinkedList<String> toMqSqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> updateMemberCodeObjs = CollectionUtil.linkedListObjectArr(),
                initMemberOrderObjs = CollectionUtil.linkedListObjectArr(),
                upsertUserMemberObjs = CollectionUtil.linkedListObjectArr();
        AdamUserMemberVo upsertUserMemberVo = adamRdmService.getUserMemberVoByUid(initMemberOrderVo.getUid());
        if (null != upsertUserMemberVo) {
            upsertUserMemberVo.setState(1);
            LocalDateTime expiryAt = upsertUserMemberVo.getExpiryAt();
            upsertUserMemberVo.setExpiryAt(
                    (expiryAt.isBefore(now) ? now : expiryAt).plusDays(initMemberOrderVo.getDays()).with(LocalTime.MAX)
            );
            long s = System.currentTimeMillis();
            mongoTemplate.getCollection(AdamUserMemberVo.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("uid").is(upsertUserMemberVo.getUid())).getQueryObject(),
                    new Document("$set", new Document("expiryAt", upsertUserMemberVo.getExpiryAt()).append("state", 1))
            );
            log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
            toMqSqls.add(SqlMapping.get("adam_user_member.update"));
            upsertUserMemberObjs.add(new Object[]{
                    upsertUserMemberVo.getState(), upsertUserMemberVo.getExpiryAt(), now, upsertUserMemberVo.getUid()
            });
        } else {
            upsertUserMemberVo = AdamUserMemberVo.getNew();
            upsertUserMemberVo.setUid(initMemberOrderVo.getUid());
            upsertUserMemberVo.setMemberId(memberCodeVo.getMemberId());
            upsertUserMemberVo.setMemberNo(memberCodeVo.getMemberNo());
            upsertUserMemberVo.setState(1);
            upsertUserMemberVo.setExpiryAt(now.plusDays(initMemberOrderVo.getDays()).with(LocalTime.MAX));
            upsertUserMemberVo.setCreatedAt(now);

            long s = System.currentTimeMillis();
            mongoTemplate.insert(upsertUserMemberVo, AdamUserMemberVo.class.getSimpleName());
            log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
            toMqSqls.add(SqlMapping.get("adam_user_member.add"));
            upsertUserMemberObjs.add(new Object[]{
                    upsertUserMemberVo.getUid(), upsertUserMemberVo.getMemberId(), upsertUserMemberVo.getMemberNo(),
                    upsertUserMemberVo.getState(), upsertUserMemberVo.getExpiryAt(), upsertUserMemberVo.getCreatedAt()
            });
        }
        long s = System.currentTimeMillis();
        adamRdmService.setUserMemberVoByUid(initMemberOrderVo.getUid(), upsertUserMemberVo);
        adamRdmService.delMemberCodeVoByCode(memberCodeVo.getCode());
        log.debug("#RDS耗时:{}ms", System.currentTimeMillis() - s);

        Document updateMemberCodeVo = new Document("state", 1)
                .append("updatedAt", now)
                .append("useOrderNo", initMemberOrderVo.getOrderNo())
                .append("useUid", upsertUserMemberVo.getUid())
                .append("useAt", now);
        s = System.currentTimeMillis();
        mongoTemplate.getCollection(AdamMemberCodeVo.class.getSimpleName()).updateOne(
                Query.query(Criteria.where("code").is(memberCodeVo.getCode())).getQueryObject(),
                new Document("$set", updateMemberCodeVo)
        );
        log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
        toMqSqls.add(SqlMapping.get("adam_member_code.exchange"));
        updateMemberCodeObjs.add(new Object[]{
                1, now, initMemberOrderVo.getOrderNo(), upsertUserMemberVo.getUid(), now, memberCodeVo.getCode()
        });

        s = System.currentTimeMillis();
        mongoTemplate.insert(initMemberOrderVo, AdamMemberOrderVo.class.getSimpleName());
        log.debug("#MDB耗时:{}ms", System.currentTimeMillis() - s);
        toMqSqls.add(SqlMapping.get("adam_member_order.add"));
        initMemberOrderObjs.add(new Object[]{
                initMemberOrderVo.getOrderNo(), initMemberOrderVo.getUid(), initMemberOrderVo.getMode(), initMemberOrderVo.getPrice(),
                initMemberOrderVo.getPricePaid(), initMemberOrderVo.getMemberName(), initMemberOrderVo.getMemberId(), initMemberOrderVo.getMemberPriceId(),
                initMemberOrderVo.getDays(), initMemberOrderVo.getState(), initMemberOrderVo.getMemberNo(), initMemberOrderVo.getBirthday(),
                initMemberOrderVo.getDeviceFrom(), initMemberOrderVo.getPayType(), initMemberOrderVo.getPayNo(), initMemberOrderVo.getPaymentAt(),
                initMemberOrderVo.getCreatedAt(), initMemberOrderVo.getClientIp(), initMemberOrderVo.getSource(), initMemberOrderVo.getVersion()
        });

        s = System.currentTimeMillis();
        queueUtils.sendMsgByRedis(
                MQConst.AdamQueue.SQL_UMEMBER.getKey(),
                SqlMapping.gets(toMqSqls, upsertUserMemberObjs, updateMemberCodeObjs, initMemberOrderObjs)
        );
        log.debug("#MQ耗时:{}ms", System.currentTimeMillis() - s);

        AdamMemberOrderResult result = AdamMemberOrderResult.getNew();
        result.setOrderNo(initMemberOrderVo.getOrderNo());
        return ResponseDto.success(result);
    }

    @Override
    public PageInfo<AdamMemberOrderSimpleVo> queryPage(String uid, int pageNo, int pageSize) {
        Query query = Query.query(Criteria.where("uid").is(uid).and("state").in(1,5));

        long count = mongoTemplate.count(query, AdamMemberOrderVo.class.getSimpleName());

        PageInfo<AdamMemberOrderSimpleVo> pageInfo = null;
        if (count > 0) {
            query.with(PageRequest.of(pageNo - 1, pageSize, Sort.by(Sort.Direction.DESC, "createdAt")));

            List<AdamMemberOrderSimpleVo> voList = mongoTemplate.find(
                    query, AdamMemberOrderSimpleVo.class, AdamMemberOrderVo.class.getSimpleName()
            );

            pageInfo = PageInfo.of(voList);
            pageInfo.setTotal(count);
        } else {
            pageInfo = new PageInfo<>();
        }
        return pageInfo;
    }
}
