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

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.UserPathDto;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.kylin.constant.KylinTableStatusConst;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderRefundEntitiesVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketEntitiesVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.returns.*;
import com.liquidnet.service.kylin.entity.KylinOrderRefunds;
import com.liquidnet.service.kylin.entity.KylinOrderTicketEntities;
import com.liquidnet.service.kylin.entity.KylinOrderTicketStatus;
import com.liquidnet.service.kylin.service.IKylinOrderTicketsService;
import com.liquidnet.service.kylin.utils.DataUtils;
import com.liquidnet.service.kylin.utils.ObjectUtil;
import com.liquidnet.service.kylin.utils.OrderUtils;
import com.liquidnet.service.kylin.utils.QueueUtils;
import com.mongodb.BasicDBObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.bson.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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 java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-20
 */
@Service
@Slf4j
public class KylinOrderTicketsServiceImpl implements IKylinOrderTicketsService {

    @Autowired
    private DataUtils dataUtils;
    @Autowired
    private OrderUtils orderUtils;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private QueueUtils queueUtils;
    @Autowired
    private KylinRefundsStatusServiceImpl refundsStatusService;

    @Override
    public PageInfo<List<KylinOrderListVo>> orderList() {
        //TODO 缺快递
        PageInfo<List<KylinOrderListVo>> mPageInfo = null;
        String uid = CurrentUtil.getCurrentUid();
//        checkOrderTime(uid);
        try {
            List<KylinOrderListVo> voList = dataUtils.getOrderList(uid);
            for (int i = 0; i < voList.size(); i++) {
                KylinOrderListVo item = voList.get(i);

                //TODO 顺丰快递
                Integer orderExpressStatus = dataUtils.getOrderExpressInfo(item.getOrderTicketsId());
                item.setExpressStatus(orderExpressStatus);

                if (item.getStatus().equals(KylinTableStatusConst.ORDER_STATUS0)) {
                    try {
                        item.setRestTime(DateUtil.intervalSeconds(
                                DateUtil.parse(item.getOverdueAt(), "yyyy-MM-dd HH:mm:ss"),
                                DateUtil.parse(DateUtil.getNowTime(), "yyyy-MM-dd HH:mm:ss")
                        ));
                        if (item.getRestTime() <= 0L) {
                            item.setRestTime(0L);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    log.debug("item.getOverdueAt() = " + item.getOverdueAt());
                    log.debug("DateUtil.getNowTime() = " + DateUtil.getNowTime());
                    log.debug("item.getRestTime() = " + item.getRestTime());
                } else {
                    item.setRestTime(0L);
                }
                if (i >= 40) {
                    break;
                }
            }

            mPageInfo = new PageInfo(voList);
            mPageInfo.setTotal(voList.size());

            log.info(UserPathDto.setData("订单列表", "", voList));
            return mPageInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return mPageInfo;
        }
    }

    @Override
    public OrderDetailsVo orderDetails(String orderId) {
        try {
            Long currentTime = System.currentTimeMillis();
            OrderDetailsVo vo = OrderDetailsVo.getNew();
            String uid = CurrentUtil.getCurrentUid();
//            checkOrderTime(uid);
            KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(orderId);
            currentTime = System.currentTimeMillis() - currentTime;
            log.debug("获取订单详情 -> time:" + (currentTime) + "毫秒");
            if (!orderTicketVo.getUserId().equals(uid)) {
                return null;
            }
            if (null != orderTicketVo) {
                KylinPerformanceVo performanceVo = dataUtils.getPerformanceVo(orderTicketVo.getPerformanceId());
                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("获取演出详情 -> time:" + (currentTime) + "毫秒");
                List<KylinOrderTicketEntitiesVo> kylinOrderTicketEntitiesVoList = orderTicketVo.getEntitiesVoList();
                KylinTicketVo ticketVo = null;

                //获取购票数据
                for (int x = 0; x < performanceVo.getTicketTimeList().size(); x++) {
                    KylinTicketTimesVo timeItem = performanceVo.getTicketTimeList().get(x);
                    for (int y = 0; y < timeItem.getTicketList().size(); y++) {
                        KylinTicketVo ticketItem = timeItem.getTicketList().get(y);
                        if (ticketItem.getTicketsId().equals(orderTicketVo.getTicketId())) {
                            ticketVo = ticketItem;
                            break;
                        }
                    }
                }
                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("巡演票数据 -> time:" + (currentTime) + "毫秒");

                orderTicketVo.setIsTrueName(ticketVo.getIsTrueName());
                orderTicketVo.setNoticeImage(performanceVo.getNoticeImage());
                orderTicketVo.setNotice(performanceVo.getNotice());
                orderTicketVo.setTicketType(ticketVo.getType());
                orderTicketVo.setFieldName(performanceVo.getFieldName());

                List<KylinOrderRefundsVo> orderRefundsVoList = dataUtils.getOrderRefundVoByOrderId(orderId);

                if (ticketVo.getIsShowCode() == 1 && orderTicketVo.getStatus() != 0 && orderTicketVo.getStatus() != 2 && orderTicketVo.getStatus() != 4) {
                    LocalDateTime date = DateUtil.Formatter.yyyyMMddHHmmss.parse(ticketVo.getQrCodeShowTime());
                    if (LocalDateTime.now().isAfter(date)) {
                        orderTicketVo.setQrCode(orderTicketVo.getQrCode());
                    } else {
                        orderTicketVo.setQrCode("");
                    }
                } else {
                    orderTicketVo.setQrCode("");
                }
                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("获取二维码 -> time:" + (currentTime) + "毫秒");

                // 数据脱敏
                for (KylinOrderTicketEntitiesVo item : kylinOrderTicketEntitiesVoList) {
                    if (item.getEnterIdCode().length() == 18) {
                        item.setEnterIdCode(item.getEnterIdCode().substring(0, 3) + "*************" + item.getEnterIdCode().substring(16));
                    }
                    if (item.getEnterMobile().length() == 11) {
                        item.setEnterMobile(item.getEnterMobile().substring(0, 3) + "****" + item.getEnterMobile().substring(7));
                    }
                }
                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("入场人加密 -> time:" + (currentTime) + "毫秒");
                //计算 倒计时
                Date nowDate = DateUtil.parse(DateUtil.getNowTime(), "yyyy-MM-dd HH:mm:ss");
                if (orderTicketVo.getStatus().equals(KylinTableStatusConst.ORDER_STATUS0)) {
                    vo.setRestTime(DateUtil.intervalSeconds(
                            DateUtil.parse(orderTicketVo.getOverdueAt(), "yyyy-MM-dd HH:mm:ss"),
                            nowDate
                    ));
                    if (vo.getRestTime() <= 0L) {
                        vo.setRestTime(0L);
                    }
                } else {
                    vo.setRestTime(0L);
                }
                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("获取倒计时 -> time:" + (currentTime) + "毫秒");

                Integer orderExpressStatus = dataUtils.getOrderExpressInfo(orderTicketVo.getOrderTicketsId());
                vo.setExpressStatus(orderExpressStatus);

                List<OrderRefundListVo> orderRefundListVos = new ArrayList<>();
                BigDecimal lockPrice = BigDecimal.valueOf(0.00);
                for (KylinOrderRefundsVo item : orderRefundsVoList) {
                    if (item.getType().equals(1)) {
                        break;
                    }
                    OrderRefundListVo data = OrderRefundListVo.getNew();
                    data.setOrderRefundCode(item.getOrderRefundCode().substring(item.getOrderRefundCode().length() - 10));
                    data.setOrderRefundsId(item.getOrderRefundsId());
                    data.setStatus(item.getStatus());
                    data.setPrice(item.getPrice());
                    data.setIsMine(uid.equals(item.getApplicantId()) ? 1 : 0);
                    if (item.getStatus().equals(0) || item.getStatus().equals(1) || item.getStatus().equals(7) || item.getStatus().equals(3) || item.getStatus().equals(4)) {
                        lockPrice = lockPrice.add(item.getPrice());
                    }
                    orderRefundListVos.add(data);
                }

                if (null != performanceVo.getIsCanRefund() && performanceVo.getIsCanRefund() == 1) {
                    LocalDateTime refundOpenDate = DateUtil.Formatter.yyyyMMddHHmmss.parse(performanceVo.getRefundOpenTime());
                    LocalDateTime refundCloseDate = DateUtil.Formatter.yyyyMMddHHmmss.parse(performanceVo.getRefundCloseTime());
                    if (LocalDateTime.now().isAfter(refundOpenDate) && LocalDateTime.now().isBefore(refundCloseDate) && orderTicketVo.getExpressAddress().trim().equals("")
                            && ticketVo.getCounts() == 1 && lockPrice.compareTo(orderTicketVo.getPriceActual()) != 0
                            && (orderTicketVo.getStatus().equals(1) || orderTicketVo.getStatus().equals(3) || orderTicketVo.getStatus().equals(6))) {
                        vo.setIsCanRefund(1);
                    } else {
                        vo.setIsCanRefund(0);
                    }
                } else {
                    vo.setIsCanRefund(0);
                }
                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("是否支持退款 -> time:" + (currentTime) + "毫秒");

                currentTime = System.currentTimeMillis() - currentTime;
                log.debug("循环退款详情 -> time:" + (currentTime) + "毫秒");
                orderTicketVo.setOrderRefundListVos(orderRefundListVos);
                orderTicketVo.setOrderCode(orderTicketVo.getOrderCode().substring(orderTicketVo.getOrderCode().length() - 10));
                vo.setOrderTicketVo(orderTicketVo);
                vo.setEnterDescribe(dataUtils.getEnterInfo(performanceVo.getType(), orderTicketVo.getGetTicketType(), orderTicketVo.getIsStudent(), ticketVo.getIsTrueName()));
            }
            log.info(UserPathDto.setData("订单详情", orderId, vo));
            return vo;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public ResponseDto<Integer> orderUnPayCount() {
        String uid = CurrentUtil.getCurrentUid();
        List<KylinOrderListVo> voList = dataUtils.getOrderList(uid);
        int unPayCount = 0;
        for (KylinOrderListVo item : voList) {

            if (item.getStatus().equals(KylinTableStatusConst.ORDER_STATUS0)) {
                item.setRestTime(DateUtil.intervalSeconds(
                        DateUtil.parse(item.getOverdueAt(), "yyyy-MM-dd HH:mm:ss"),
                        DateUtil.parse(DateUtil.getNowTime(), "yyyy-MM-dd HH:mm:ss")
                ));
                if (item.getRestTime() <= 0L) {
                    item.setRestTime(0L);
                } else {
                    unPayCount += 1;
                }
            } else {
                item.setRestTime(0L);
            }
        }
        return ResponseDto.success(unPayCount);
    }

    @Override
    public ResponseDto<KylinOrderTicketPreVo> toOrderRefundDetails(String orderId) {
        try {
            KylinOrderTicketPreVo vo = KylinOrderTicketPreVo.getNew();
            String uid = CurrentUtil.getCurrentUid();
            KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(orderId);
            KylinPerformanceVo performanceVo = dataUtils.getPerformanceVo(orderTicketVo.getPerformanceId());
            List<KylinOrderRefundsVo> kylinOrderRefundsVoBaseList = dataUtils.getOrderRefundVoByOrderId(orderTicketVo.getOrderTicketsId());
            if (!orderTicketVo.getUserId().equals(uid)) {
                return ResponseDto.failure(ErrorMapping.get("20003"));
            }
            List<KylinOrderTicketEntitiesVo> kylinOrderTicketEntitiesVoList = orderTicketVo.getEntitiesVoList();
            List<KylinOrderTicketEntitiesPreRefundVo> kylinOrderTicketEntitiesPreRefundVos = ObjectUtil.getKylinOrderTicketEntitiesPreRefundVoArrayList();
            // 数据脱敏
            for (KylinOrderTicketEntitiesVo item : kylinOrderTicketEntitiesVoList) {
                KylinOrderTicketEntitiesPreRefundVo refundVo = KylinOrderTicketEntitiesPreRefundVo.getNew();
                if (item.getEnterIdCode().length() == 18) {
                    item.setEnterIdCode(item.getEnterIdCode().substring(0, 3) + "*************" + item.getEnterIdCode().substring(16));
                }
                if (item.getEnterMobile().length() == 11) {
                    item.setEnterMobile(item.getEnterMobile().substring(0, 3) + "****" + item.getEnterMobile().substring(7));
                }
                item.setPriceActual(orderTicketVo.getPriceActual().subtract(orderTicketVo.getPriceExpress()).divide(BigDecimal.valueOf(orderTicketVo.getNumber())));
                item.setPriceCanRefund(dataUtils.getCanRefundOrderEntitiesPrice(orderTicketVo, kylinOrderRefundsVoBaseList, item.getOrderTicketEntitiesId()));
                BeanUtils.copyProperties(item, refundVo);
                kylinOrderTicketEntitiesPreRefundVos.add(refundVo);
            }
            orderTicketVo.setFieldName(performanceVo.getFieldName());
            orderTicketVo.setOrderCode(orderTicketVo.getOrderCode().substring(orderTicketVo.getOrderCode().length() - 10));

            BeanUtils.copyProperties(orderTicketVo, vo);
            vo.setIsTrueName(performanceVo.getIsTrueName());
            vo.setEntitiesPreRefundVos(kylinOrderTicketEntitiesPreRefundVos);
            return ResponseDto.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.failure(ErrorMapping.get("20030"));
        }
    }

    @Override
    public ResponseDto<OrderRefundVo> orderRefundDetails(String orderId, String orderRefundId) {
        try {
            OrderRefundVo vo = OrderRefundVo.getNew();
            String uid = CurrentUtil.getCurrentUid();
            KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(orderId);
            KylinPerformanceVo performanceVo = dataUtils.getPerformanceVo(orderTicketVo.getPerformanceId());

            if (!orderTicketVo.getUserId().equals(uid)) {
                return ResponseDto.failure(ErrorMapping.get("20003"));
            }
            orderTicketVo.setFieldName(performanceVo.getFieldName());
            orderTicketVo.setOrderCode(orderTicketVo.getOrderCode().substring(orderTicketVo.getOrderCode().length() - 10));
            KylinOrderRefundsVo kylinOrderRefundsVoBase = dataUtils.getOrderRefundVo(orderRefundId);
            kylinOrderRefundsVoBase.setOrderRefundCode(kylinOrderRefundsVoBase.getOrderRefundCode().substring(kylinOrderRefundsVoBase.getOrderRefundCode().length() - 10));
            vo.setKylinOrderRefundsVoBaseList(kylinOrderRefundsVoBase);
            vo.setOrderTicketVo(orderTicketVo);
            return ResponseDto.success(vo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.failure(ErrorMapping.get("20030"));
        }
    }

    @Override
    public String sendOrderRefund(String orderId, String orderTicketEntitiesId, String reason, String picList) {
        KylinOrderTicketEntitiesVo orderTicketEntitiesVo = null;
        try {
            String uid = CurrentUtil.getCurrentUid();
            KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(orderId);
            List<KylinOrderRefundsVo> kylinOrderRefundsVoBaseList = dataUtils.getOrderRefundVoByOrderId(orderTicketVo.getOrderTicketsId());
            if (!orderTicketVo.getUserId().equals(uid)) {
                return "无权查看";
            }

            if (!orderTicketVo.getPayStatus().equals(1)) {
                return "暂不支持退款";
            }

            KylinPerformanceVo performanceVo = dataUtils.getPerformanceVo(orderTicketVo.getPerformanceId());
            KylinTicketVo ticketVo = null;
            //获取购票数据
            for (int x = 0; x < performanceVo.getTicketTimeList().size(); x++) {
                KylinTicketTimesVo timeItem = performanceVo.getTicketTimeList().get(x);
                for (int y = 0; y < timeItem.getTicketList().size(); y++) {
                    KylinTicketVo ticketItem = timeItem.getTicketList().get(y);
                    if (ticketItem.getTicketsId().equals(orderTicketVo.getTicketId())) {
                        ticketVo = ticketItem;
                        break;
                    }
                }
            }

            if (null != performanceVo.getIsCanRefund() && performanceVo.getIsCanRefund() == 1) {
                LocalDateTime refundOpenDate = DateUtil.Formatter.yyyyMMddHHmmss.parse(performanceVo.getRefundOpenTime());
                LocalDateTime refundCloseDate = DateUtil.Formatter.yyyyMMddHHmmss.parse(performanceVo.getRefundCloseTime());
                if (LocalDateTime.now().isAfter(refundOpenDate) && LocalDateTime.now().isBefore(refundCloseDate) && orderTicketVo.getExpressAddress().trim().equals("") && ticketVo.getCounts() == 1) {

                } else {
                    return "暂不支持退款";
                }
            } else {
                return "暂不支持退款";
            }

            List<KylinOrderTicketEntitiesVo> entitiesVos = orderTicketVo.getEntitiesVoList();
            for (KylinOrderTicketEntitiesVo item : entitiesVos) {
                if (item.getOrderTicketEntitiesId().equals(orderTicketEntitiesId)) {
                    orderTicketEntitiesVo = item;
                }
            }
            if (null == orderTicketEntitiesVo) {
                return "订单不存在";
            }

            BigDecimal refundSinglePrice = dataUtils.getCanRefundOrderEntitiesPrice(orderTicketVo, kylinOrderRefundsVoBaseList, orderTicketEntitiesId);
            if (refundSinglePrice.compareTo(BigDecimal.ZERO) <= 0) {
                return "申请金额不得小于0";
            }
            Map token = CurrentUtil.getTokenClaims();
            String username = StringUtils.defaultString(((String) token.get("nickname")), "");
            String result = refundsStatusService.userOrderTicketRefunding(orderTicketVo, refundSinglePrice.doubleValue(), orderTicketEntitiesId, reason, picList, uid, username, kylinOrderRefundsVoBaseList.size());
            if (result != "") {
                return result;
            } else {
                return "申请失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "申请失败";
        }
    }

    @Override
    public ResponseDto<Boolean> orderRefundWithdraw(String orderRefundsId) {

        LinkedList<String> sqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
        LinkedList<Object[]> sqlsDataB = CollectionUtil.linkedListObjectArr();
        LinkedList<Object[]> sqlsDataC = CollectionUtil.linkedListObjectArr();

        LocalDateTime time = LocalDateTime.now();
        String strTime = DateUtil.Formatter.yyyyMMddHHmmss.format(time);
        try {
            KylinOrderRefundsVo orderRefundsVo = dataUtils.getOrderRefundVo(orderRefundsId);
            if (!orderRefundsVo.getStatus().equals(0)) {
                return ResponseDto.failure(ErrorMapping.get("20020"));
            }
            List<KylinOrderRefundEntitiesVo> refundEntities = orderRefundsVo.getOrderRefundEntitiesVoList();
            String orderTicketsId = orderRefundsVo.getOrderTicketsId();
            KylinOrderTicketVo orderTicketVo = dataUtils.getOrderTicketVo(orderTicketsId);

            // 更新数据
            // 订单状态表 判断是退到正在退款 已付款 部分退款？(取消，完成，失败)
            int newStatus;
            int refundingCount = 0;
            List<KylinOrderRefundsVo> orderRefundsVoList = dataUtils.getOrderRefundVoByOrderId(orderTicketsId);
            for (KylinOrderRefundsVo item : orderRefundsVoList) {
                int status = item.getStatus();
                log.info("status = " + status);
                if (status != 2 && status != 4 && status != 5 && !item.getOrderRefundsId().equals(orderRefundsId)) {
                    refundingCount += 1;
                }
            }

            if (refundingCount > 0) { // 存在其他正在退款的订单
                newStatus = KylinTableStatusConst.ORDER_STATUS3;
            } else {
                if (orderTicketVo.getPriceRefund().doubleValue() > 0) { // 已经有退完的 那就是部分退款了
                    newStatus = KylinTableStatusConst.ORDER_STATUS6;
                } else if (orderTicketVo.getStatus() != 2) {
                    newStatus = KylinTableStatusConst.ORDER_STATUS1;
                } else {
                    newStatus = KylinTableStatusConst.ORDER_STATUS2;
                }
            }

            KylinOrderTicketStatus orderStatusTable = KylinOrderTicketStatus.getNew();
            log.info("newStatus = " + newStatus);
            orderStatusTable.setStatus(newStatus);
            orderStatusTable.setUpdatedAt(time);
            LocalDateTime now = LocalDateTime.now();
            sqlsDataA.add(new Object[]{
                    orderStatusTable.getStatus(), orderStatusTable.getUpdatedAt(), orderTicketsId, now, now
            });

            KylinOrderTicketVo kylinOrderTicketVo = KylinOrderTicketVo.getNew();
            kylinOrderTicketVo.setStatus(newStatus);
            kylinOrderTicketVo.setUpdatedAt(strTime);
            kylinOrderTicketVo.setChangeDate(time);
            BasicDBObject orderObject = new BasicDBObject("$set", JSON.parse(JsonUtils.toJson(kylinOrderTicketVo)));
            mongoTemplate.getCollection(KylinOrderTicketVo.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("orderTicketsId").is(orderTicketsId)).getQueryObject(),
                    orderObject
            );
            orderUtils.resetOrderListVo(orderTicketVo.getUserId(), 2, orderTicketsId, null);

            // 入场人
            for (KylinOrderRefundEntitiesVo item : refundEntities) {
                // 订单状态表 判断是退到正在退款 已付款 部分退款？(取消，完成，失败)
                int newIsPayment = 0;
                int refundingEntitiesCount = 0;
                for (KylinOrderRefundsVo item2 : orderRefundsVoList) {
                    int status = item2.getStatus();
                    if (!item2.getOrderRefundsId().equals(orderRefundsId) && (status != 2 && status != 4 && status != 5)) {
                        for (KylinOrderRefundEntitiesVo item3 : item2.getOrderRefundEntitiesVoList()) {
                            if (item3.getOrderTicketEntitiesId().equals(item.getOrderTicketEntitiesId())) {
                                refundingEntitiesCount += 1;
                            }
                        }
                    }

                    /*for (KylinOrderRefundEntitiesVo item3 : item2.getOrderRefundEntitiesVoList()) {
                        if (item3.getOrderTicketEntitiesId().equals(item.getOrderTicketEntitiesId())) {
                            entitiesAllPrice.add(item3.getRefundPrice());
                        }
                    }*/

                }

                KylinOrderTicketEntitiesVo entitiesVo = null;
                for (KylinOrderTicketEntitiesVo entitiesVo1 : orderTicketVo.getEntitiesVoList()) {
                    if (entitiesVo1.getOrderTicketEntitiesId().equals(item.getOrderTicketEntitiesId())) {
                        entitiesVo = entitiesVo1;
                        break;
                    }
                }

                log.info("getRefundPrice =" + item.getRefundPrice());
                if (refundingEntitiesCount > 0) { // 存在其他正在退款的该入场人订单
                    newIsPayment = KylinTableStatusConst.ENTITIES_IS_PAYMENT2;
                } else {
                    if (orderTicketVo.getPriceRefund().compareTo(BigDecimal.ZERO) > 0) { // 已经有退完的 那就是部分退款了
                        newIsPayment = KylinTableStatusConst.ENTITIES_IS_PAYMENT4;
                    } else {
                        newIsPayment = KylinTableStatusConst.ENTITIES_IS_PAYMENT1;
                    }
                }
                KylinOrderTicketEntities entitiesTable = KylinOrderTicketEntities.getNew();
                entitiesTable.setIsPayment(newIsPayment);
                entitiesTable.setUpdatedAt(time);

                log.info("sqlsDataB data = "+entitiesTable.getIsPayment());

                sqlsDataB.add(new Object[]{
                        entitiesTable.getIsPayment(), entitiesTable.getUpdatedAt(), item.getOrderTicketEntitiesId(), now, now
                });

                KylinOrderTicketEntitiesVo kylinOrderTicketEntitiesVo = KylinOrderTicketEntitiesVo.getNew();
                kylinOrderTicketEntitiesVo.setIsPayment(newIsPayment);
                kylinOrderTicketEntitiesVo.setUpdatedAt(strTime);
                kylinOrderTicketEntitiesVo.setChangeDate(time);
//                for (KylinOrderRefundEntitiesVo item2:orderRefundsVo.getOrderRefundEntitiesVoList()){
//                    if(item2.getOrderTicketEntitiesId().equalsIgnoreCase(item.getOrderTicketEntitiesId())){
//                        log.info("entitiesVo.getRefundPrice() = "+entitiesVo.getRefundPrice());
//                        log.info("item2.getRefundPrice() = "+item2.getRefundPrice());
                kylinOrderTicketEntitiesVo.setRefundPrice(entitiesVo.getRefundPrice());
//                    }
//                }

                log.info("entitiesVo.getRefundPrice() = " + entitiesVo.getRefundPrice());
                BasicDBObject entitiesObject = new BasicDBObject("$set", JSON.parse(JsonUtils.toJson(kylinOrderTicketEntitiesVo)));
                mongoTemplate.getCollection(KylinOrderTicketEntitiesVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("orderTicketEntitiesId").is(item.getOrderTicketEntitiesId())).getQueryObject(),
                        entitiesObject
                );

                dataUtils.delOrderTicketEntitiesRedis(item.getOrderTicketEntitiesId());
            }

            // 退款细节取消
            KylinOrderRefunds kylinOrderRefunds = KylinOrderRefunds.getNew();
            kylinOrderRefunds.setStatus(KylinTableStatusConst.ORDER_REFUND_STATUS_CANCEL);
            kylinOrderRefunds.setUpdatedAt(LocalDateTime.now());

            mongoTemplate.getCollection(KylinOrderRefundsVo.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("orderRefundsId").is(orderRefundsId)).getQueryObject(),
                    new Document("$set", new Document("status", KylinTableStatusConst.ORDER_REFUND_STATUS_CANCEL).append("updatedAt", time))
            );

            sqlsDataC.add(new Object[]{
                    KylinTableStatusConst.ORDER_REFUND_STATUS_CANCEL, time, orderRefundsId
            });

            dataUtils.delOrderRefundVo(orderRefundsId);
            dataUtils.delOrderRefundVoByOrderId(orderTicketsId);
            dataUtils.delOrderTicketRedis(orderTicketsId);
            orderUtils.resetOrderListVo(CurrentUtil.getCurrentUid(), 2, orderTicketsId, null);


            sqls.add(SqlMapping.get("kylin_order_ticket_status.withDraw"));
            sqls.add(SqlMapping.get("kylin_order_ticket_entities.withDraw"));
            sqls.add(SqlMapping.get("kylin_order_refund.withDraw"));
            queueUtils.sendMsgByRedis(MQConst.KylinQueue.SQL_ORDER_WITHDRAW.getKey(),
                    SqlMapping.gets(sqls, sqlsDataA, sqlsDataB, sqlsDataC));
            return ResponseDto.success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.failure(ErrorMapping.get("20020"));
        }
    }

}
