package com.kmall.schedule.service;

import com.google.common.collect.Maps;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import com.kmall.manager.dao.TemplateConfDao;
import com.kmall.manager.entity.pay.TemplateConfVo;
import com.kmall.manager.manager.pay.data.open.cus.CusPropertiesBuilder;
import com.kmall.manager.manager.pingan.PinganUtil;
import com.kmall.manager.manager.pingan.dto.PinganPayOrderDto;
import com.kmall.manager.manager.pingan.dto.PinganResponseDto;
import com.kmall.manager.manager.wechat.WechatUtil;
import com.kmall.manager.manager.wechat.wxglobal.WechatGlobalUtil;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalQueryApiResult;
import com.kmall.manager.manager.wechat.wxglobal.dto.WechatGlobalRefundQueryResult;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplate;
import com.kmall.schedule.dao.*;
import com.kmall.common.utils.wechat.ReaderXmlForDOM4J;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.WechatRefundQueryResult;
import com.kmall.manager.manager.wechat.wxtemplate.TemplateData;
import com.kmall.manager.manager.wechat.wxtemplate.WxTemplateUtil;
import com.kmall.schedule.entity.MkDistSellStatisEntity;
import com.kmall.schedule.entity.ScheduleJobLogEntity;
import com.kmall.schedule.quartz.OrderTask;
import com.kmall.schedule.entity.MngChangeJobEntity;
import com.kmall.schedule.entity.StoreMngChangeJobEntity;
import com.kmall.schedule.utils.ScheduleJob;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信提醒任务
 *
 * @author zhouzhengde(CN)
 * @date 2017/12/4.
 */
@Service
public class QzOrderService {
    private static Log logger = LogFactory.getLog(QzOrderService.class);
    @Autowired
    private TemplateConfDao templateConfDao;
    @Autowired
    private QzGroupMapper qzGroupMapper;
    @Autowired
    private QzOrderMapper qzOrderMapper;
    @Autowired
    private OrderWXPayRecordMapper orderWXPayRecordMapper;
    @Autowired
    private MkDistSellStatisMapper mkDistSellStatisMapper;
    @Autowired
    private ScheduleJobLogDao scheduleJobLogDao;

    /**
     * todo 一期暂时不实现团购
     * 团购进度提醒，提前一天提醒(发送微信模版消息提醒用户)
    @Transactional
    public void groupProgressRemind() {
        logger.info(">>>>>>>>>>>>>>>>>>>>groupProgressRemind is start ");
        TemplateConfVo templateConfVo =
                templateConfDao.queryByTypeId(4); //  模板类型 1订单付款成功 2团购成功 3拼团失败通知 4拼团进度 5 6 7订单配送 8订单评价提醒
        if (null == templateConfVo) {
            return;
        }
        List<Map> groupList = qzGroupMapper.queryRemindGroupList();

        if (null != groupList && groupList.size() > 0) {
            for (Map map : groupList) {
                Long id = MapUtils.getLong("id", map);
                String open_id = MapUtils.getString("open_id", map);
                Long group_id = MapUtils.getLong("group_id", map);
                Integer attend_num = MapUtils.getInteger("attend_num", map);
                String name = MapUtils.getString("name", map);
                Date open_time = MapUtils.getDate("open_time", map);
                Date end_time = MapUtils.getDate("end_time", map);
                String form_id = MapUtils.getString("form_id", map);
                BigDecimal retail_min_price = MapUtils.getBigDecimal("retail_min_price", map);
                if (StringUtils.isNullOrEmpty(form_id)) {
                    continue;
                }
                WxTemplate tem = new WxTemplate();
                tem.setTemplate_id(templateConfVo.getTemplateId());
                //                tem.setTopcolor("#00DD00");
                tem.setTouser(open_id);
                tem.setPage("/pages/groupDetail/groupDetail?id=" + group_id);
                tem.setForm_id(form_id);

                List<TemplateData> paras = new ArrayList<TemplateData>();
                paras.add(new TemplateData("keyword1", name));
                paras.add(new TemplateData("keyword2", DateUtils.format(open_time, DateUtils.DATE_PATTERN)));
                paras.add(new TemplateData("keyword3", "已有" + attend_num + "人参与"));
                //剩余时长
                long time = (end_time.getTime() - System.currentTimeMillis()) / 1000;
                long hour = time / 3600;
                long minite = time / 60 % 60;
                long second = (time - hour * 3600 - minite * 60);
                String body = hour + "时" + minite + "分" + second + "秒";
                paras.add(new TemplateData("keyword3", body));
                paras.add(new TemplateData("keyword4", retail_min_price.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString() + "元"));
                paras.add(new TemplateData("keyword5", templateConfVo.getDesc()));
                tem.setData(paras);
                WxTemplateUtil.sendMessage(tem);
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>groupProgressRemind is end ");
    }

    *//**
     * todo 一期暂时不实现团购
     * 更新过期的团购订单(发送微信模版消息提醒用户)
     *//*
    @Transactional
    public void pastGroupRemind() {
        logger.info(">>>>>>>>>>>>>>>>>>>>pastGroupRemind is start ");
        TemplateConfVo templateConfVo =
                templateConfDao.queryByTypeId(3); //  模板类型 1订单付款成功 2团购成功 3拼团失败通知 4拼团进度 5 6 7订单配送 8订单评价提醒
        if (null == templateConfVo) {
            return;
        }
        List<Map> groupList = qzGroupMapper.queryPastGroupList();

        if (null != groupList && groupList.size() > 0) {
            for (Map map : groupList) {
                Long id = MapUtils.getLong("id", map);
                String open_id = MapUtils.getString("open_id", map);
                Long group_id = MapUtils.getLong("group_id", map);
                Integer attend_num = MapUtils.getInteger("attend_num", map);
                String name = MapUtils.getString("name", map);
                String form_id = MapUtils.getString("form_id", map);
                Integer min_open_group = MapUtils.getInteger("min_open_group", map);
                BigDecimal retail_min_price = MapUtils.getBigDecimal("retail_min_price", map);
                if (StringUtils.isNullOrEmpty(form_id)) {
                    continue;
                }
                WxTemplate tem = new WxTemplate();
                tem.setTemplate_id(templateConfVo.getTemplateId());
//                tem.setTopcolor("#00DD00");
                tem.setTouser(open_id);
                tem.setPage("/pages/groupDetail/groupDetail?id=" + group_id);
                tem.setForm_id(form_id);

                List<TemplateData> paras = new ArrayList<TemplateData>();
                paras.add(new TemplateData("keyword1", name));
                paras.add(new TemplateData("keyword2", attend_num + "/" + min_open_group));
                paras.add(new TemplateData("keyword3", retail_min_price + "元"));
                paras.add(new TemplateData("keyword4", templateConfVo.getDesc()));
                tem.setData(paras);
                WxTemplateUtil.sendMessage(tem);
                // 更新团购失败订单
                Map updateFailParams = Maps.newHashMap();
                updateFailParams.put("id", id);
                qzGroupMapper.updatePastGroup(updateFailParams);
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>pastGroupRemind is end ");
    }

    *//**
     * 未评价订单(发送微信模版消息提醒用户)
     *//*
    @Transactional
    public void orderUnEvaluateRemind() {
        logger.info(">>>>>>>>>>>>>>>>>>>>orderUnEvaluateRemind is start ");
        TemplateConfVo templateConfVo =
                templateConfDao.queryByTypeId(8); //  模板类型 1订单付款成功 2团购成功 3拼团失败通知 4拼团进度 5 6 7订单配送 8订单评价提醒
        if (null == templateConfVo) {
            return;
        }
        List<Map> unEvaluateList = qzOrderMapper.queryrderUnEvaluateList();

        if (null != unEvaluateList && unEvaluateList.size() > 0) {
            for (Map map : unEvaluateList) {
                Long id = MapUtils.getLong("id", map);
                String form_id = MapUtils.getString("form_id", map);
                String order_sn = MapUtils.getString("order_sn", map);
                String open_id = MapUtils.getString("open_id", map);
                String goods_name = MapUtils.getString("goods_name", map);
                if (StringUtils.isNullOrEmpty(form_id)) {
                    continue;
                }
                WxTemplate tem = new WxTemplate();
                tem.setTemplate_id(templateConfVo.getTemplateId());
//                tem.setTopcolor("#00DD00");
                tem.setTouser(open_id);
                tem.setPage("/pages/ucenter/orderDetail/orderDetail?id=" + id);
                tem.setForm_id(form_id);

                List<TemplateData> paras = new ArrayList<TemplateData>();
                paras.add(new TemplateData("keyword1", goods_name));
                paras.add(new TemplateData("keyword2", order_sn));
                paras.add(new TemplateData("keyword3", templateConfVo.getDesc()));
                tem.setData(paras);
                WxTemplateUtil.sendMessage(tem);
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>orderUnEvaluateRemind is end ");
    }*/
    /**
     * 未支付的现场商品且已人脸识别通过的订单(发送微信模版消息提醒用户)
     */
    @Transactional
    public void unPayAndFaceSuccessOrder() {
        logger.info(">>>>>>>>>>>>>>>>>>>>unPayAndFaceSuccessOrder is start ");
        TemplateConfVo templateConfVo =
                qzOrderMapper.queryByTypeId(10); //  模板类型 10待支付提醒
        if (null == templateConfVo) {
            return;
        }
        List<Map> unPayAndFaceSuccessOrderList = qzOrderMapper.unPayAndFaceSuccessOrderList();

        if (null != unPayAndFaceSuccessOrderList && unPayAndFaceSuccessOrderList.size() > 0) {
            for (Map map : unPayAndFaceSuccessOrderList) {
                Long id = MapUtils.getLong("order_id", map);
                /*String form_id = MapUtils.getString("form_id", map);
                if (StringUtils.isNullOrEmpty(form_id)) {
                    continue;
                }*/
                Date add_time = MapUtils.getDate("add_time", map);
                String open_id = MapUtils.getString("open_id", map);
//                String goods_name = MapUtils.getString("goods_name", map);
                String order_sn = MapUtils.getString("order_sn", map);
                String addTime = "";
                if(add_time!= null){
                    addTime = DateUtils.format(add_time, DateUtils.DATE_TIME_PATTERN);
                }
                WxTemplate tem = new WxTemplate();
                tem.setTemplate_id(templateConfVo.getTemplateId());
                tem.setTouser(open_id);
                tem.setPage("/pages/ucenter/orderDetail/orderDetail?id=" + id);

                List<TemplateData> paras = new ArrayList<TemplateData>();
                String addTimeAfter = DateUtils.addMin(add_time,15);
                String desc = templateConfVo.getDesc().replace("addTimeAfter", addTimeAfter);
                List<Map> orderGoodsEntityList = qzOrderMapper.queryOrderGoodsByOrderId(id);
                StringBuffer goodsNames = new StringBuffer();
                if(orderGoodsEntityList.size()>0){
                    for(Map goodsEntity: orderGoodsEntityList){
                        goodsNames.append(MapUtils.getString("goodsName", goodsEntity) + ",");
                    }
                }
                String goods_name = goodsNames.toString().substring(0, goodsNames.length() - 1);
                paras.add(new TemplateData("thing1", goods_name));
                paras.add(new TemplateData("date2", addTime));
                paras.add(new TemplateData("thing3", desc));
                tem.setData(paras);
                JSONObject jsonObject = WxTemplateUtil.sendMessage(tem);
                int result = jsonObject.getInt("errcode");
                String resultmsg = jsonObject.getString("errmsg");
                if(result != 0){
                    String error = "";
                    if(result == 43101){
                        error = "用户openId【"+open_id+"】待支付提醒模板推送失败，原因：用户拒绝接受消息，如果用户之前曾经订阅过，则表示用户取消了订阅关系";
                        logger.info(error);
                    }else if(result == 40037){
                        error = "用户openId【"+open_id+"】待支付提醒模板推送失败，原因：订阅模板id为空不正确";
                        logger.info(error);
                    }else if(result == 41030){
                        error = "用户openId【"+open_id+"】待支付提醒模板推送失败，原因：page路径不正确，需要保证在现网版本小程序中存在，与app.json保持一致";
                        logger.info(error);
                    }else{
                        error = resultmsg;
                        logger.info(error);
                    }
                    Map param = new HashMap();
                    param.put("orderSn", order_sn);
                    param.put("isTempNoti", 0);
                    param.put("tempNotiMsg", error);
                    qzOrderMapper.updateOrderByTempNoti(param);
                }else{
                    Map param = new HashMap();
                    param.put("orderSn", order_sn);
                    param.put("isTempNoti", 1);
                    param.put("tempNotiMsg", "通知成功");
                    qzOrderMapper.updateOrderByTempNoti(param);
                }
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>unPayAndFaceSuccessOrder is end ");
    }
    /**
     * 更新过期未支付订单
     */
    @Transactional
    public void unpayPastUpdate() {
        logger.info(">>>>>>>>>>>>>>>>>>>>unpayPastUpdate is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>更新过期未支付订单 ");
        // 获取快过期订单
        List<Map> pastOrderList = qzOrderMapper.queryPastOrderList();
        if (null != pastOrderList && pastOrderList.size() > 0) {
            for (Map map : pastOrderList) {
                restStockNum(map,"更新过期未支付订单");
                restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
            }
            qzOrderMapper.unpayPastUpdate();

        }
        logger.info(">>>>>>>>>>>>>>>>>>>>unpayPastUpdate is end ");
    }

    /**
     * 更新退款中的，或小程序更新退款信息异常订单
     */
    @Transactional
    public void refundUpdate() {
        logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询已申请退款订单以及退款中订单，查询微信退款信息更新订单状态 ");
        // 获取退款中或更新退款信息异常订单
        List<Map> refundOrderList = qzOrderMapper.queryRefundOrderList();
        if (null != refundOrderList && refundOrderList.size() > 0) {
            for (Map map : refundOrderList) {
                String pay_flag = MapUtils.getString("pay_flag", map);
                String orderId = MapUtils.getString("orderId", map);
                if(org.apache.commons.lang.StringUtils.isNotEmpty(pay_flag)) {
                    if (pay_flag.equalsIgnoreCase("wxglobalpay")) {//微信国际支付
                        wxGlobalRefundQuery(map);
                    } else if (pay_flag.equalsIgnoreCase("weixin")) {//微信支付、平安支付、线下扫码支付
                        wxRefundquery(map);
                    } else if (pay_flag.equalsIgnoreCase("pingan")) {
                        pinganRefundquery(map);
                    }
                }else{
                    logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate 订单编号【"+orderId+"】的支付方式不能为空！ ");
                }
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate 未查到退款数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate is end ");
    }

    /**
     * 微信支付、线下扫码支付共用微信查询订单api
     * @param map
     */
    private void  wxRefundquery(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用");
        String out_trade_no = MapUtils.getString("merch_order_sn", map);
        String order_id = MapUtils.getString("orderId", map);
        String order_sn_wx = MapUtils.getString("order_sn_wx", map);
        String out_refund_no = MapUtils.getString("out_refund_no", map);
        Integer is_onffline_order = MapUtils.getInteger("is_onffline_order", map);
        if (is_onffline_order == 1) {
            out_trade_no = order_sn_wx;
        }
        WechatRefundQueryResult result = WechatUtil.wxRefundquery(out_trade_no);
        if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                Map refundRaram = Maps.newHashMap();
                Map orderRaram = Maps.newHashMap();
                int msgCount = Integer.parseInt(result.getRefund_count());
                for (int i = 0; i < msgCount; i++) {
                    WechatRefundQueryResult querySuccessResponseDto =
                            ReaderXmlForDOM4J.parse(result.getXmlStr(), i);
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用,返回退款单号"+querySuccessResponseDto.getOut_refund_no());
                    if(out_refund_no.equalsIgnoreCase(querySuccessResponseDto.getOut_refund_no())) {
                        result.setRefund_success_time(querySuccessResponseDto.getRefund_success_time());
                        result.setOut_refund_no(querySuccessResponseDto.getOut_refund_no());
                        result.setRefund_account(querySuccessResponseDto.getRefund_account());
                        result.setRefund_channel(querySuccessResponseDto.getRefund_channel());
                        result.setRefund_fee(querySuccessResponseDto.getRefund_fee());
                        result.setRefund_id(querySuccessResponseDto.getRefund_id());
                        result.setRefund_recv_accout(querySuccessResponseDto.getRefund_recv_accout());
                        result.setRefund_status(querySuccessResponseDto.getRefund_status());

                        Date successTime = DateUtils.strToDate(result.getRefund_success_time());
                        refundRaram.put("refundTime", successTime);
                        refundRaram.put("outRefundNo", result.getOut_refund_no());
                        refundRaram.put("refundId", result.getRefund_id());
                        refundRaram.put("refundMoney",
                                BigDecimal.valueOf(Long.valueOf(result.getRefund_fee()))
                                        .divide(Constant.ONE_HUNDRED));
                        if (result.getRefund_status().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用,返回退款成功");
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_2.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款成功");
                            orderRaram.put("payStatus", Dict.payStatus.item_4.getItem());
                            //退款成功释放库存、释放优惠券、释放促销满减
                            restStockNum(map,"定时任务更新退款成功订单");//库存还原
                            restUserCoupon(map);// 判断是否使用优惠券,修改为可使用
                            restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                        } else if (result.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用,返回退款关闭");
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款关闭");
                            orderRaram.put("payStatus", Dict.payStatus.item_5.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("CHANGE")) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用,返回退款异常");
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款异常");
                            orderRaram.put("payStatus", Dict.payStatus.item_6.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用,返回退款处理中");
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_5.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款处理中");
                            orderRaram.put("payStatus", Dict.payStatus.item_3.getItem());
                        }
                        refundRaram.put("refundRecvAccout", result.getRefund_recv_accout());
                        refundRaram.put("orderRefundId", result.getOut_refund_no());
                        qzOrderMapper.updateOrderRefund(refundRaram);//更新订单退款信息
                    }
                }
                orderRaram.put("orderStatus", Dict.orderStatus.item_401.getItem());
                orderRaram.put("orderId", order_id);
                orderRaram.put("payTransactionId", result.getTransaction_id());
                qzOrderMapper.updateOrderInfo(orderRaram);
            } else {
                logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口返回失败信息：code 【" + result.getErr_code() +
                        "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信退款查询接口调用失败： " + result.getReturn_msg());
        }
    }

    /**
     * 平安支付查询订单api
     * @param map
     */
    private void  pinganRefundquery(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>pinganRefundquery 平安退款查询接口调用");
        String outNo = MapUtils.getString("merch_order_sn", map);
        String outRefundNo = MapUtils.getString("out_refund_no", map);
        String orderId = MapUtils.getString("orderId", map);

        PinganResponseDto response = PinganUtil.pinganQueryRefund(null, outRefundNo);
        if (!Objects.isNull(response)) {
            response.setOutNo(outNo);
            response.setCreateTime(new Date());
            qzOrderMapper.insertPinganResponseDto(MapBeanUtil.fromObject(response));

            if ("0".equals(response.getErrcode()) && StringUtils.isNotEmpty(response.getDatajson())) {
                JSONObject refundResult = JSONObject.fromObject(response.getDatajson());
                String tradeResult = refundResult.getString("trade_result");

                JSONObject result = JSONObject.fromObject(tradeResult);
                Map refundParam = Maps.newHashMap();
                Map orderParam = Maps.newHashMap();

                String refundCount= MapUtils.getString("refund_count", result);
                if (!StringUtils.isNullOrEmpty(refundCount) && !"null".equals(refundCount)) {
                    int msgCount = Integer.parseInt(refundCount);
                    for (int i = 0; i < msgCount; i++) {
                        WechatRefundQueryResult refundQueryResult = PinganUtil.buildWechatRefundQueryResult(result, i);
                        logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 平安退款查询接口调用,返回退款单号"+refundQueryResult.getOut_refund_no());
                        updateOrderRefund(outRefundNo,refundQueryResult,refundParam,orderParam,map);
                    }
                } else {
                    WechatRefundQueryResult refundQueryResult = PinganUtil.buildWechatRefundQueryResult(result);
                    updateOrderRefund(outRefundNo,refundQueryResult,refundParam,orderParam,map);
                }
                orderParam.put("orderStatus", Dict.orderStatus.item_401.getItem());
                orderParam.put("orderId", orderId);
                qzOrderMapper.updateOrderInfo(orderParam);
            } else {
                logger.info(">>>>>>>>>>>>>>>>>>>>pinganRefundquery 平安退款查询接口返回失败信息：code 【" + response.getErrcode() + "】，des【" + response.getMsg() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>pinganRefundquery 平安退款查询接口调用失败");
        }

        /*WechatRefundQueryResult result = WechatUtil.wxRefundquery(out_trade_no);
        if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                Map refundRaram = Maps.newHashMap();
                Map orderRaram = Maps.newHashMap();
                int msgCount = Integer.parseInt(result.getRefund_count());
                for (int i = 0; i < msgCount; i++) {
                    WechatRefundQueryResult querySuccessResponseDto =
                            ReaderXmlForDOM4J.parse(result.getXmlStr(), i);
                    if(out_refund_no.equalsIgnoreCase(querySuccessResponseDto.getOut_refund_no())) {
                        result.setRefund_success_time(querySuccessResponseDto.getRefund_success_time());
                        result.setOut_refund_no(querySuccessResponseDto.getOut_refund_no());
                        result.setRefund_account(querySuccessResponseDto.getRefund_account());
                        result.setRefund_channel(querySuccessResponseDto.getRefund_channel());
                        result.setRefund_fee(querySuccessResponseDto.getRefund_fee());
                        result.setRefund_id(querySuccessResponseDto.getRefund_id());
                        result.setRefund_recv_accout(querySuccessResponseDto.getRefund_recv_accout());
                        result.setRefund_status(querySuccessResponseDto.getRefund_status());

                        Date successTime = DateUtils.strToDate(result.getRefund_success_time());
                        refundRaram.put("refundTime", successTime);
                        refundRaram.put("outRefundNo", result.getOut_refund_no());
                        refundRaram.put("refundId", result.getRefund_id());
                        refundRaram.put("refundMoney",
                                BigDecimal.valueOf(Long.valueOf(result.getRefund_fee()))
                                        .divide(Constant.ONE_HUNDRED));
                        if (result.getRefund_status().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_2.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款成功");
                            orderRaram.put("payStatus", Dict.payStatus.item_4.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款关闭");
                            orderRaram.put("payStatus", Dict.payStatus.item_5.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("CHANGE")) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款异常");
                            orderRaram.put("payStatus", Dict.payStatus.item_6.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_5.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款处理中");
                            orderRaram.put("payStatus", Dict.payStatus.item_3.getItem());
                        }
                        refundRaram.put("refundRecvAccout", result.getRefund_recv_accout());
                        refundRaram.put("orderRefundId", result.getOut_refund_no());
                        qzOrderMapper.updateOrderRefund(refundRaram);//更新订单退款信息
                    }
                }
                orderRaram.put("orderStatus", Dict.orderStatus.item_401.getItem());
                orderRaram.put("orderId", order_id);
                orderRaram.put("payTransactionId", result.getTransaction_id());
                qzOrderMapper.updateOrderInfo(orderRaram);
            } else {
                logger.info(">>>>>>>>>>>>>>>>>>>>pinganRefundquery 平安退款查询接口返回失败信息：code 【" + result.getErr_code() + "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>pinganRefundquery 平安退款查询接口调用失败： " + result.getReturn_msg());
        }*/
    }

    private void updateOrderRefund(String outRefundNo,WechatRefundQueryResult refundQueryResult,Map refundParam,Map orderParam,Map map){
        if (outRefundNo.equalsIgnoreCase(refundQueryResult.getOut_refund_no())) {
            Date successTime = DateUtils.strToDate(refundQueryResult.getRefund_success_time());
            refundParam.put("refundTime", successTime);
            refundParam.put("outRefundNo", refundQueryResult.getOut_refund_no());
            refundParam.put("refundId", refundQueryResult.getRefund_id());
            refundParam.put("refundMoney",
                    BigDecimal.valueOf(Long.valueOf(refundQueryResult.getRefund_fee()))
                            .divide(Constant.ONE_HUNDRED));
            if (refundQueryResult.getRefund_status().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                refundParam.put("refundStatus", Dict.RefundStatus.item_2.getItem());
                refundParam.put("wechat_refund_status_des", "退款成功");
                orderParam.put("payStatus", Dict.payStatus.item_4.getItem());
                //退款成功释放库存、释放优惠券、释放促销满减
                restStockNum(map,"定时任务更新退款成功订单");//库存还原
                restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
            } else if (refundQueryResult.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                refundParam.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                refundParam.put("wechat_refund_status_des", "退款关闭");
                orderParam.put("payStatus", Dict.payStatus.item_5.getItem());
            } else if (refundQueryResult.getRefund_status().equalsIgnoreCase("CHANGE")) {
                refundParam.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                refundParam.put("wechat_refund_status_des", "退款异常");
                orderParam.put("payStatus", Dict.payStatus.item_6.getItem());
            } else if (refundQueryResult.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                refundParam.put("refundStatus", Dict.RefundStatus.item_5.getItem());
                refundParam.put("wechat_refund_status_des", "退款处理中");
                orderParam.put("payStatus", Dict.payStatus.item_3.getItem());
            }
            refundParam.put("refundRecvAccout", refundQueryResult.getRefund_recv_accout());
            refundParam.put("orderRefundId", refundQueryResult.getOut_refund_no());
            qzOrderMapper.updateOrderRefund(refundParam);//更新订单退款信息
        }
    }

    /**
     * 微信国际支付微信查询订单api
     * @param map
     */
    private void  wxGlobalRefundQuery(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalRefundQuery 微信国际退款查询接口调用");
        String out_trade_no = MapUtils.getString("merch_order_sn", map);
        String order_id = MapUtils.getString("orderId", map);
        String out_refund_no = MapUtils.getString("out_refund_no", map);
        WechatGlobalRefundQueryResult result = WechatGlobalUtil.wxRefundquery(out_trade_no);
        if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                Map orderRaram = Maps.newHashMap();
                Map refundRaram = Maps.newHashMap();
                int msgCount = Integer.parseInt(result.getRefund_count());
                for (int i = 0; i < msgCount; i++) {
                    //微信部分退款时返回的多条退款信息数据解析
                    WechatRefundQueryResult querySuccessResponseDto = ReaderXmlForDOM4J.parse(result.getXmlStr(), i);
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxRefundquery 微信国际退款查询接口调用,返回退款单号"+querySuccessResponseDto.getOut_refund_no());
                    if(out_refund_no.equalsIgnoreCase(querySuccessResponseDto.getOut_refund_no())) {
                        //微信部分退款时返回的多条退款信息数据
                        result.setRefund_fee(querySuccessResponseDto.getRefund_fee());
                        result.setOut_refund_no(querySuccessResponseDto.getOut_refund_no());
                        result.setRefund_id(querySuccessResponseDto.getRefund_id());
                        result.setRefund_channel(querySuccessResponseDto.getRefund_channel());
                        result.setRefund_status(querySuccessResponseDto.getRefund_status());
                        result.setRefund_account(querySuccessResponseDto.getRefund_account());
                        result.setRefund_recv_accout(querySuccessResponseDto.getRefund_recv_accout());
                        result.setRefund_success_time(querySuccessResponseDto.getRefund_success_time());

                        refundRaram.put("refundTime", DateUtils.strToDate(result.getRefund_success_time()));
                        refundRaram.put("outRefundNo", result.getOut_refund_no());
                        refundRaram.put("refundId", result.getRefund_id());
                        refundRaram.put("refundMoney",
                                BigDecimal.valueOf(Long.valueOf(result.getRefund_fee()))
                                        .divide(Constant.ONE_HUNDRED));//退款金额
                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getTotal_fee())) {
                            refundRaram.put("totalFee", BigDecimal.valueOf(Long.valueOf(result.getTotal_fee()))
                                    .divide(Constant.ONE_HUNDRED));//标价金额
                        }
                        refundRaram.put("feeType", result.getFee_type());//标价币种
                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(result.getCash_fee())) {
                            refundRaram.put("cashFee", BigDecimal.valueOf(Long.valueOf(result.getCash_fee()))
                                    .divide(Constant.ONE_HUNDRED));//用户支付金额
                        }
                        refundRaram.put("cashFeeType", result.getCash_fee_type());//用户支付金额币种
                        refundRaram.put("rate", result.getRate());//汇率
                        if (result.getRefund_status().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_2.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款成功");
                            orderRaram.put("payStatus", Dict.payStatus.item_4.getItem());
                            //退款成功释放库存、释放优惠券、释放促销满减
                            restStockNum(map,"定时任务更新退款成功订单");//库存还原
                            restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                            restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                        } else if (result.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_5.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款处理中");
                            orderRaram.put("payStatus", Dict.payStatus.item_3.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款关闭");
                            orderRaram.put("payStatus", Dict.payStatus.item_5.getItem());
                        } else if (result.getRefund_status().equalsIgnoreCase("CHANGE")) {
                            refundRaram.put("refundStatus", Dict.RefundStatus.item_4.getItem());
                            refundRaram.put("wechat_refund_status_des", "退款异常");
                            orderRaram.put("payStatus", Dict.payStatus.item_6.getItem());
                        }
                        refundRaram.put("refundRecvAccout", result.getRefund_recv_accout());
                        refundRaram.put("orderRefundId", result.getOut_refund_no());
                        qzOrderMapper.updateOrderRefund(refundRaram);//更新订单退款信息
                    }
                }
                orderRaram.put("orderStatus", Dict.orderStatus.item_401.getItem());
                orderRaram.put("orderId", order_id);
                orderRaram.put("payTransactionId", result.getTransaction_id());
                qzOrderMapper.updateOrderInfo(orderRaram);
            } else {
                logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalRefundQuery 微信国际退款查询接口返回失败信息：code 【" + result.getErr_code() +
                        "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalRefundQuery 微信国际退款查询接口调用失败： " + result.getReturn_msg());
        }
    }


    /**
     * 查询小程序支付状态“支付中或成功”的订单信息，以及小程序更新支付信息缺失的订单，获取商户订单号查询微信支付信息更新小程序订单支付数据
     */
    @Transactional
    public void orderQueryUpdate() {
        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询小程序支付状态“支付中或成功”的订单信息，以及小程序更新支付信息缺失的订单，获取商户订单号查询微信支付信息更新小程序订单支付数据");
        // 获取支付中的订单以及小程序更新支付信息异常订单
        List<Map> orderList = qzOrderMapper.queryPayingOrderList();
        if (null != orderList && orderList.size() > 0) {
            for (Map map : orderList) {
                String pay_flag = MapUtils.getString("pay_flag", map);
                String orderId = MapUtils.getString("order_id", map);
                if(org.apache.commons.lang.StringUtils.isNotEmpty(pay_flag)) {
                    if (pay_flag.equalsIgnoreCase("wxglobalpay")) {//微信国际支付
                        wxGlobalOrderQuery(map);
                    } else {//微信支付、平安支付、线下扫码支付
                        wxOrderQuery(map);
                    }
                }else{
                    logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate 订单编号【"+orderId+"】的支付方式不能为空！ ");
                }
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate 未查到订单数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate is end ");
    }

    /**
     * 微信查询接口
     * @param map
     */
    private void wxOrderQuery(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口调用");
        String out_trade_no = MapUtils.getString("merch_order_sn", map);
        String orderId = MapUtils.getString("orderId", map);
        String orderSn = MapUtils.getString("order_sn", map);
        String add_time = MapUtils.getString("add_time", map);

        Date addTime = DateUtils.strToDate(add_time);
        Date nowDate = new Date();

        WechatRefundApiResult result = WechatUtil.wxOrderQuery(out_trade_no);
        if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode()) ){
                if(result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_SUCCESS.getItem())) {
                    Date successTime = DateUtils.convertStringToDate(result.getTime_end(),
                            DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_2.getItem());//已支付
                    orderRaram.put("orderStatus", Dict.orderStatus.item_201.getItem());//已支付
                    orderRaram.put("payTransactionId", result.getTransaction_id());
                    orderRaram.put("payTime", successTime);
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    Map processParam = Maps.newHashMap();
                    processParam.put("payTime", successTime);
                    processParam.put("orderSn", orderSn);
                    qzOrderMapper.updateOrderProcessRecord(processParam);
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {//订单未支付
                    Map orderRaram = Maps.newHashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        restStockNum(map,"定时任务更新过期未支付订单");//库存还原
                        restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                        restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                        orderRaram.put("orderStatus", Dict.orderStatus.item_101.getItem());//订单状态已取消
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                    } else {
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                        orderRaram.put("orderStatus", Dict.orderStatus.item_0.getItem());//订单状态未支付
                    }
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_CLOSED.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_7.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_500.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    restStockNum(map,"定时任务更新已关闭订单");//库存还原
                    restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                    restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + result.getTrade_state_desc() + "】");
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_PAYERROR.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_8.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_501.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + result.getTrade_state_desc() + "】");
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_USERPAYING.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_1.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_100.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + result.getTrade_state_desc() + "】");
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_REVOKED.getItem())) {
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + result.getTrade_state_desc() + "】");
                }
            }else {
                logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口返回失败信息：code 【" + result.getErr_code() +
                        "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderQuery 微信查询接口调用失败： " + result.getReturn_msg());
        }
    }

    /**
     * 微信国际查询接口
     * @param map
     */
    private void wxGlobalOrderQuery(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderQuery 微信查询接口调用");
        String out_trade_no = MapUtils.getString("merch_order_sn", map);
        String orderId = MapUtils.getString("orderId", map);
        String orderSn = MapUtils.getString("order_sn", map);
        String add_time = MapUtils.getString("add_time", map);
        Integer number = MapUtils.getInteger("number", map);
        Integer stock_num = MapUtils.getInteger("stock_num", map);
        Long storeRelaId = MapUtils.getLong("storeRelaId", map);
        Date addTime = DateUtils.strToDate(add_time);
        Date nowDate = new Date();
        WechatGlobalQueryApiResult result = WechatGlobalUtil.wxOrderQuery(out_trade_no);
        if (result.getReturn_code().equalsIgnoreCase(WechatGlobalUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatGlobalUtil.WXTradeState.SUCCESS.getCode())) {
                if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_SUCCESS.getItem())) {
                    Date successTime = DateUtils.convertStringToDate(result.getTime_end(),
                            DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_2.getItem());//已支付
                    orderRaram.put("orderStatus", Dict.orderStatus.item_201.getItem());//已支付
                    orderRaram.put("payTransactionId", result.getTransaction_id());
                    orderRaram.put("payTime", successTime);
                    orderRaram.put("orderId", orderId);

                    orderRaram.put("totalFee", result.getTotal_fee());//标价金额
                    orderRaram.put("feeType", result.getFee_type());//标价币种
                    orderRaram.put("cashFee", result.getCash_fee());//用户支付金额
                    orderRaram.put("cashFeeType", result.getCash_fee_type());//用户支付金额币种
                    orderRaram.put("rate", result.getRate());//汇率
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    Map processParam = Maps.newHashMap();
                    processParam.put("payTime", successTime);
                    processParam.put("orderSn", orderSn);
                    qzOrderMapper.updateOrderProcessRecord(processParam);
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {//订单未支付
                    Map orderRaram = Maps.newHashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        restStockNum(map,"定时任务更新过期未支付订单");//库存还原
                        restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                        restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                        orderRaram.put("orderStatus", Dict.orderStatus.item_101.getItem());//订单状态已取消
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                    } else {
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                        orderRaram.put("orderStatus", Dict.orderStatus.item_0.getItem());//订单状态未支付
                    }
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_CLOSED.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_7.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_500.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    restStockNum(map,"定时任务更新已关闭订单");//库存还原
                    restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                    restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + Dict.tradeState.item_CLOSED.getItemName() + "】");
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_PAYERROR.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_8.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_501.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + Dict.tradeState.item_PAYERROR.getItemName() + "】");
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_USERPAYING.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_1.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_100.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + Dict.tradeState.item_USERPAYING.getItemName() + "】");
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_REVOKED.getItem())) {
                    logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口返回信息：state 【" + result.getTrade_state() +
                            "】，des【" + Dict.tradeState.item_REVOKED.getItemName() + "】");
                }
            }else {
                logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderQuery 微信查询接口返回失败信息：code 【" + result.getErr_code() +
                        "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderQuery 微信查询接口调用失败： " + result.getReturn_msg());
        }
    }

    /**
     * 查询支付中的订单以及小程序更新支付信息异常订单，查询平安订单更新订单状态
     */
    @Transactional
    public void pinganOrderQueryUpdate() {
        logger.info(">>>>>>>>>>>>>>>>>>>>pinganOrderQueryUpdate is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询支付中的订单以及小程序更新支付信息异常订单，查询平安订单信息更新订单状态 ");
        // 获取支付中的订单以及小程序更新支付信息异常订单
        List<Map> orderList = qzOrderMapper.queryPinganPayingOrderList();
        if (null != orderList && orderList.size() > 0) {
            for (Map map : orderList) {
                String outNo = MapUtils.getString("merch_order_sn", map);
                String orderId = MapUtils.getString("orderId", map);
                String orderSn = MapUtils.getString("order_sn", map);
                String add_time = MapUtils.getString("add_time", map);

                PinganResponseDto response = PinganUtil.pinganPaystatus(outNo);

                if (!Objects.isNull(response)) {
                    response.setOutNo(outNo);
                    response.setCreateTime(new Date());
                    qzOrderMapper.insertPinganResponseDto(MapBeanUtil.fromObject(response));

                    if ("0".equals(response.getErrcode()) && StringUtils.isNotEmpty(response.getDatajson())) {
                        PinganPayOrderDto payOrderDto = PinganUtil.buildPayOrderDto(JSONObject.fromObject(response.getDatajson()));
                        qzOrderMapper.updatePayOrderByOutNo(MapBeanUtil.fromObject(payOrderDto));

                        Date addTime = DateUtils.strToDate(add_time);
                        Date nowDate = new Date();
                        // 订单状态（1交易成功，2待支付，4已取消，9等待用户输入密码确认）
                        if (payOrderDto.getStatus() == 1) {
                            Map orderParam = Maps.newHashMap();
                            orderParam.put("payStatus", 2);//已支付
                            orderParam.put("orderStatus", 201);//已支付
                            orderParam.put("payTransactionId", payOrderDto.getTradeNo());
                            orderParam.put("payTime", payOrderDto.getTradeTime());
                            orderParam.put("orderId", orderId);
                            qzOrderMapper.updateOrderInfo(orderParam);
                            Map processParam = Maps.newHashMap();
                            processParam.put("payTime", payOrderDto.getTradeTime());
                            processParam.put("orderSn", orderSn);
                            qzOrderMapper.updateOrderProcessRecord(processParam);
                        } else {
                            Map orderRaram = Maps.newHashMap();
                            if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                                orderRaram.put("payStatus", 0);//支付状态未支付
                                orderRaram.put("orderStatus", 101);//订单状态已取消
                                restStockNum(map, "定时任务更新平安超时未支付订单");//库存还原
                                restUserCoupon(map);// 判断是否有优惠券,修改为可使用
                                restUserCamp(map);// 判断是否使用促销满减活动,修改为可使用
                            } else {
                                orderRaram.put("payStatus", 0);//支付状态未支付
                                orderRaram.put("orderStatus", 0);//订单状态未支付
                            }
                            orderRaram.put("orderId", orderId);
                            qzOrderMapper.updateOrderInfo(orderRaram);
                        }
                    } else {
                        logger.info(">>>>>>>>>>>>>>>>>>>>pinganOrderQueryUpdate 平安查询接口返回失败信息：code 【" + response.getErrcode() + "】，des【" + response.getMsg() + "】");
                    }
                } else {
                    logger.info(">>>>>>>>>>>>>>>>>>>>pinganOrderQueryUpdate 平安查询接口调用失败");
                }
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>pinganOrderQueryUpdate 未查到订单数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>pinganOrderQueryUpdate is end ");
    }

    /**
     *  查询微信支付中且已生成支付单的订单，更新订单状态
     *//*
    @Transactional
    public void orderQueryUpdateByWxTransactionId() {
        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdateByWxTransactionId is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询微信支付中且已生成支付单的订单，更新订单状态");
        // 查询订单状态为支付中，且已生成支付单号的订单数据
        List<Map> orderList = qzOrderMapper.queryPayingOrderList();
        if (null != orderList && orderList.size() > 0) {
            for (Map map : orderList) {
                String pay_flag = MapUtils.getString("pay_flag", map);
                String orderId = MapUtils.getString("order_id", map);
                if(org.apache.commons.lang.StringUtils.isNotEmpty(pay_flag)) {
                    if (pay_flag.equalsIgnoreCase("wxglobalpay")) {//微信国际支付
                        wxGlobalOrderByTransactionIdQueryUpdFail(map);
                    } else {//微信支付、平安支付、线下扫码支付
                        wxOrderByTransactionIdQueryUpdFail(map);
                    }
                }else{
                    logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdateByWxTransactionId 订单编号【"+orderId+"】的支付方式不能为空！ ");
                }
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdateByWxTransactionId 未查到订单数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdateByWxTransactionId is end ");
    }

    *//**
     * 微信查询接口，根据支付单号查询微信失败数据，更新中网订单数据
     * @param map
     *//*
    private void wxOrderByTransactionIdQueryUpdFail(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口调用");
        String orderId = MapUtils.getString("order_id", map);
        String payTransactionId =  MapUtils.getString("payTransactionId", map);
        String add_time = MapUtils.getString("add_time", map);
        Integer number = MapUtils.getInteger("number", map);
        Integer stock_num = MapUtils.getInteger("stock_num", map);
        Long storeRelaId = MapUtils.getLong("storeRelaId", map);
        Date addTime = DateUtils.strToDate(add_time);
        Date nowDate = new Date();
        WechatRefundApiResult result = WechatUtil.wxOrderQueryByTransactionId(payTransactionId);
        if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode()) ){
                //订单未支付
                if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        Map param = Maps.newHashMap();
                        param.put("id", storeRelaId);
                        param.put("stock_num", stock_num + number);
                        qzOrderMapper.updateStockNum(param);//库存还原
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                        orderRaram.put("orderStatus", Dict.orderStatus.item_101.getItem());//订单状态已取消
                    } else {
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                        orderRaram.put("orderStatus", Dict.orderStatus.item_0.getItem());//订单状态未支付
                    }
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                }
            }else {
                logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口返回失败信息：code 【" + result.getErr_code() +
                        "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>wxOrderByTransactionIdQueryUpdFail 根据支付单查询微信接口调用失败： " + result.getReturn_msg());
        }
    }
    *//**
     * 微信国际查询接口，根据支付单号查询微信失败数据，更新中网订单数据
     * @param map
     *//*
    private void wxGlobalOrderByTransactionIdQueryUpdFail(Map map){
        logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口调用");
        String orderId = MapUtils.getString("order_id", map);
        String payTransactionId =  MapUtils.getString("payTransactionId", map);
        String add_time = MapUtils.getString("add_time", map);
        Integer number = MapUtils.getInteger("number", map);
        Integer stock_num = MapUtils.getInteger("stock_num", map);
        Long storeRelaId = MapUtils.getLong("storeRelaId", map);
        Date addTime = DateUtils.strToDate(add_time);
        Date nowDate = new Date();
        WechatGlobalQueryApiResult result = WechatGlobalUtil.wxOrderQueryByTransactionId(payTransactionId);
        if (result.getReturn_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode())) {
            if (result.getResult_code().equalsIgnoreCase(WechatUtil.WXTradeState.SUCCESS.getCode()) ){
                //订单未支付
                if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {
                    Map orderRaram = Maps.newHashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        Map param = Maps.newHashMap();
                        param.put("id", storeRelaId);
                        param.put("stock_num", stock_num + number);
                        qzOrderMapper.updateStockNum(param);//库存还原
                        orderRaram.put("orderStatus", Dict.orderStatus.item_101.getItem());//订单状态已取消
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                    } else {
                        orderRaram.put("payStatus", Dict.payStatus.item_0.getItem());//支付状态未支付
                        orderRaram.put("orderStatus", Dict.orderStatus.item_0.getItem());//订单状态未支付
                    }
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                }
            }else {
                logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口返回失败信息：code 【" + result.getErr_code() +
                        "】，des【" + result.getErr_code_des() + "】");
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>wxGlobalOrderByTransactionIdQueryUpdFail 根据支付单查询微信国际接口调用失败： " + result.getReturn_msg());
        }
    }*/


    /**
     * 查询付款码支付记录的支付状态
     */
    @Transactional
    public void orderMicropayQueryUpdate() {
        logger.info(">>>>>>>>>>>>>>>>>>>>查询付款码支付记录的支付状态开始<<<<<<<<<<<<<<<<<<<<<<<");
        // 获取交易状态是未支付,支付中和支付失败3种状态的付款码支付记录
        List<String> tradeStates = new ArrayList<>();
        tradeStates.add(WechatUtil.WXTradeState.NOTPAY.getCode());
        tradeStates.add(WechatUtil.WXTradeState.USERPAYING.getCode());
        tradeStates.add(WechatUtil.WXTradeState.PAYERROR.getCode());
        List<Map> records = orderWXPayRecordMapper.queryRecordList(tradeStates);
        if (null != records && records.size() > 0) {
            for (Map map : records) {
                String out_trade_no_wx = MapUtils.getString("out_trade_no_wx", map);
                String out_trade_no = MapUtils.getString("out_trade_no", map);
                Integer id = MapUtils.getInteger("id", map);

                WechatRefundApiResult result = WechatUtil.wxOrderQuery(out_trade_no_wx);
                if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(result.getReturn_code()) && WechatUtil.WXTradeState.SUCCESS.getCode().equals(result.getResult_code())) {
                    Map recordRaram = Maps.newHashMap();
                    recordRaram.put("id", id);
                    recordRaram.put("trade_state", result.getTrade_state());
                    //查询到支付成功
                    if (WechatUtil.WXTradeState.SUCCESS.getCode().equals(result.getTrade_state())) {
                        recordRaram.put("result_code", result.getTrade_state());
                        recordRaram.put("err_code", "");
                        recordRaram.put("err_code_des", "");
                        recordRaram.put("openid", result.getOpenid());
                        recordRaram.put("is_subscribe", result.getIs_subscribe());
                        recordRaram.put("trade_type", result.getTrade_type());
                        recordRaram.put("fee_type", result.getFee_type());
                        recordRaram.put("total_fee", result.getTotal_fee());
                        recordRaram.put("transaction_id", result.getTransaction_id());
                        recordRaram.put("attach", result.getAttach());
                        recordRaram.put("time_end", result.getTime_end());

                        //修改订单状态
                        Map order = qzOrderMapper.queryOrder(out_trade_no);
                        if (MapUtils.getInteger("order_status", order) == 201) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 此订单已付款： " + out_trade_no);
                        } else if (MapUtils.getInteger("order_status", order) == 301) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 此订单已完成： " + out_trade_no);
                        } else if (MapUtils.getInteger("order_status", order) == 101) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 此订单已取消： " + out_trade_no);
                        } else if (MapUtils.getInteger("order_status", order) == 102) {
                            logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 此订单已删除： " + out_trade_no);
                        } else {
                            Map orderRaram = Maps.newHashMap();
                            orderRaram.put("payStatus", 2);//已支付
                            orderRaram.put("orderStatus", 201);//已支付
                            orderRaram.put("payFlag", "weixin");
                            orderRaram.put("orderSnWx",out_trade_no_wx);
                            orderRaram.put("payTime", new Date());
                            orderRaram.put("orderId", MapUtils.getInteger("id", order));
                            qzOrderMapper.updateOrderInfo(orderRaram);
                            logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 订单:" + out_trade_no +
                                        "支付成功,修改支付状态");

                            //查询当前订单所有的支付记录
                            List<Map> orderWXPayRecordEntitys =
                                    orderWXPayRecordMapper.getRecordsByOutTradeNo(out_trade_no);
                            for (Map orderWXPayRecordTemp : orderWXPayRecordEntitys) {
                                //查询出来的记录不等于当前记录,并且未撤销,未关闭时,撤销订单
                                Integer orderWXPayRecordTemp_id = MapUtils.getInteger("id", orderWXPayRecordTemp);
                                String orderWXPayRecordTemp_tradeState =
                                        MapUtils.getString("trade_state", orderWXPayRecordTemp);
                                String orderWXPayRecordTemp_outTradeNoWX =
                                        MapUtils.getString("out_trade_no_wx", orderWXPayRecordTemp);
                                if (orderWXPayRecordTemp_id != id && (!WechatUtil.WXTradeState.REVOKED.getCode()
                                                                                                      .equals(orderWXPayRecordTemp_tradeState) ||
                                                                      !WechatUtil.WXTradeState.CLOSED.getCode()
                                                                                                     .equals(orderWXPayRecordTemp_tradeState))) {

                                    logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 订单:" +
                                                orderWXPayRecordTemp_outTradeNoWX + "支付失败,调用撤销订单接口开始");
                                    WechatUtil.wxReverse(orderWXPayRecordTemp_outTradeNoWX);
                                    logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 订单:" +
                                                orderWXPayRecordTemp_outTradeNoWX + "支付失败,调用撤销订单接口结束");
                                }
                            }

                        }
                        //查询到支付失败,撤销订单
                    } else if (WechatUtil.WXTradeState.PAYERROR.getCode().equals(result.getTrade_state())) {
                        logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 订单:" + out_trade_no_wx +
                                    "支付失败,调用撤销订单接口开始");
                        WechatUtil.wxReverse(out_trade_no_wx);
                        logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 订单:" + out_trade_no_wx +
                                    "支付失败,调用撤销订单接口结束");
                    }
                    recordRaram.put("mod_time", new Date());
                    orderWXPayRecordMapper.update(recordRaram);

                } else {
                    logger.info(
                            ">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 微信查询接口调用失败： " + result.getReturn_msg());
                }
            }
        } else {
            logger.info(">>>>>>>>>>>>>>>>>>>>orderWXPayRecordQueryUpdate 未查到需要调用接口的支付记录数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>查询付款码支付记录的支付状态 结束<<<<<<<<<<<<<<<<<<<<<<<");
    }

    /**
     * 商品发货后7天自动确认收货
     */
    @Transactional
    public void shipmentOrderAutoTakeGoods() {
        logger.info(">>>>>>>>>>>>>>>>>>>>shipmentOrderAutoTakeGoods is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>商品发货后7天自动确认收货 ");
        // 查询门店业务发货后7天的订单，门店业务根据清关完成时间后7天
        List<Map> shipmentOrderList = qzOrderMapper.queryShipmentOrderList();
        updateShipmentOrder(shipmentOrderList);
        //查询保税备货发货后7天的订单，保税备货根据发货完成时间后7天
        List<Map> shipmentBondedOrderList = qzOrderMapper.queryShipmentBondedOrderList();
        updateShipmentOrder(shipmentBondedOrderList);
        logger.info(">>>>>>>>>>>>>>>>>>>>shipmentOrderAutoTakeGoods is end ");
    }

    private void updateShipmentOrder(List<Map> shipmentBondedOrderList){
        if (null != shipmentBondedOrderList && shipmentBondedOrderList.size() > 0) {
            for (Map map : shipmentBondedOrderList) {
                Map orderMap = Maps.newHashMap();
                orderMap.put("orderId", MapUtils.getLong("orderId", map));
                qzOrderMapper.updateShipmentOrder(orderMap);
            }
        }

    }
    /**
     * 确认收货后30天自动确认好评
     */
    @Transactional
    public void receiptOrderAutoComment() {
        logger.info(">>>>>>>>>>>>>>>>>>>>receiptOrderAutoComment is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>确认收货后30天自动确认好评 ");
        // 获取收货后30天的订单
        List<Map> receiptOrderList = qzOrderMapper.queryReceiptOrderList();
        if (null != receiptOrderList && receiptOrderList.size() > 0) {
            for (Map map : receiptOrderList) {
                Long userId = MapUtils.getLong("userId", map);
                Long orderId = MapUtils.getLong("orderId", map);
                Long goodsId = MapUtils.getLong("goodsId", map);
                Long productId = MapUtils.getLong("productId", map);
                String goodsSpecificationNameValue = MapUtils.getString("goodsSpecificationNameValue", map);
                String goodsName = MapUtils.getString("goodsName", map);

                Map param = Maps.newHashMap();
                param.put("userId", userId);
                param.put("orderId", orderId);
                param.put("valueId", goodsId);
                param.put("typeId", 0);
                param.put("productId", productId);
                param.put("goodsSpecificationNameValue", goodsSpecificationNameValue);
                param.put("status", "1");
                param.put("content", "默认好评");
                param.put("evalLevel", 5);
                param.put("goodsLevel", 5);
                param.put("valueName", goodsName);
                param.put("createTime", new Date());
                param.put("modTime", new Date());
                param.put("addTime", System.currentTimeMillis() / 1000);
                qzOrderMapper.insertComment(param);//新增评论
            }
            qzOrderMapper.updateReceiptOrderByCommentCount();//修改评论数量
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>receiptOrderAutoComment is end ");

    }

    /**
     * 返回海关所需获取的支付相关实时数据
     */
    @Transactional
    public void realTimeDataUp() {
        logger.info(">>>>>>>>>>>>>>>>>>>>realTimeDataUp is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>返回海关所需获取的支付相关实时数据 ");
        try {
            logger.info(CusPropertiesBuilder.instance().getSendUrl());
            String string = OkHttpUtils.post(new HashMap<>(), CusPropertiesBuilder.instance().getSendUrl(), null);
            logger.info(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>realTimeDataUp is end ");
    }

    /**
     * 方法描述：用户确认收货后，记录商品分销购买记录
     * 1分钟更新
     */
    @Transactional
    public void receiptOrderSaveDistSellStatis(){
        logger.info(">>>>>>>>>>>>>>>>>>>>receiptOrderSaveDistSellStatis is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>用户确认收货后，记录商品分销购买记录 ");

        // 获取收货后的订单
        List<Map> receiptOrderList = qzOrderMapper.queryReceiptOrderByDistList();
        if (null != receiptOrderList && receiptOrderList.size() > 0) {
            for (Map map : receiptOrderList) {
                Integer thirdMerchSn = MapUtils.getInteger("thirdMerchSn", map);
                Map distMap = qzOrderMapper.queryThirdMerchantBySn(thirdMerchSn);
                String is_dist_sell_start = MapUtils.getString("is_dist_sell_start", distMap);
                if(StringUtils.isNotEmpty(is_dist_sell_start) && Dict.status.item_1.getItem().equalsIgnoreCase(is_dist_sell_start)){
                    String orderSn = MapUtils.getString("orderSn", map);
                    Integer orderGoodsId = MapUtils.getInteger("orderGoodsId", map);
                    Integer storeId = MapUtils.getInteger("storeId", map);
                    Integer userId = MapUtils.getInteger("userId", map);
                    Long goodsId = MapUtils.getLong("goodsId", map);
                    BigDecimal goodsPrice = MapUtils.getBigDecimal("goodsPrice", map);
                    Integer supplierId = MapUtils.getInteger("supplierId", map);
                    Integer distId = MapUtils.getInteger("distId", map);
                    String distFlag = MapUtils.getString("distFlag", map);
                    String distChnlId = MapUtils.getString("distChnlId", map);

                    String allocType = MapUtils.getString("allocType", map);
                    Integer sell_alloc_history_id = MapUtils.getInteger("sell_alloc_history_id", map);

                    String expendDistIds = MapUtils.getString("expendDistIds", map);
                    String expendDistLines = MapUtils.getString("expendDistLines", map);

                    MkDistSellStatisEntity mkDistSellStatisEntity = new MkDistSellStatisEntity();
                    mkDistSellStatisEntity.setUserId(userId);
                    mkDistSellStatisEntity.setOrderGoodsId(orderGoodsId);
                    mkDistSellStatisEntity.setOrderSn(orderSn);
                    mkDistSellStatisEntity.setGoodsId(String.valueOf(goodsId));
                    mkDistSellStatisEntity.setGoodsPrice(goodsPrice);
                    mkDistSellStatisEntity.setThirdMerchSn(thirdMerchSn);
                    mkDistSellStatisEntity.setSupplierId(supplierId);
                    mkDistSellStatisEntity.setDistId(distId);
                    mkDistSellStatisEntity.setDistChnlId(distChnlId);
                    mkDistSellStatisEntity.setDistFlag(distFlag);
//                    mkDistSellStatisEntity.setAllocType(allocType);
                    mkDistSellStatisEntity.setSellAllocHistoryId(sell_alloc_history_id);
                    mkDistSellStatisEntity.setIsValid("0");
                    mkDistSellStatisEntity.setCreateTime(new Date());
                    mkDistSellStatisEntity.setModTime(new Date());
                    mkDistSellStatisEntity.setStoreId(storeId);

                    List<Integer> expendDistIdList = getExpendDistId(expendDistIds);//支出对应分销商
                    List<Double> expendDistLinesList = getExpendDistLines(expendDistLines);//商品支出对应佣金额度

                    for (int i = 0; i < expendDistIdList.size(); i++) {
                        Map hierMap = new HashMap();
                        hierMap.put("distId", expendDistIdList.get(i));
//                        hierMap.put("pdistId", distId);
                        hierMap.put("distChnlId", distChnlId);
                        Map distHierMap = qzOrderMapper.queryMkDistHierById(hierMap);
                        if (!StringUtils.isNullOrEmpty(distHierMap)) {
                            String level = MapUtils.getString("hierLvl", distHierMap);
                            BigDecimal price = new BigDecimal(0);
                            Double expendDistPrice = expendDistLinesList.get(i);
                            if (allocType.equalsIgnoreCase(Dict.allocType.item_00.getItem())) {//比例，公式：商品购买价格*设置比例
                                price = goodsPrice.multiply(BigDecimal.valueOf(expendDistPrice));
                            } else if (allocType.equalsIgnoreCase(Dict.allocType.item_10.getItem())) {//金额
                                price = BigDecimal.valueOf(expendDistPrice);
                            }
                            mkDistSellStatisEntity.setExpendDistId(expendDistIdList.get(i));
                            mkDistSellStatisEntity.setExpendDistLevel(level);
                            mkDistSellStatisEntity.setExpendDistPrice(price);
                            mkDistSellStatisEntity.setExpendSource("");
                            mkDistSellStatisMapper.save(mkDistSellStatisEntity);
                        }
                    }

                    Map isScanMap = new HashMap();
                    isScanMap.put("orderGoodsId", orderGoodsId);
                    isScanMap.put("isDistSellScan", Dict.isDistSellScan.item_1.getItem());
                    qzOrderMapper.updateOrderGoodsIsScan(isScanMap);
                }else{
                    logger.info(">>>>>>>>>>>>>>>>>>>>第三方商户没有分销渠道权限 ");
                }
            }
        }else{
            logger.info(">>>>>>>>>>>>>>>>>>>>确认收货订单没有数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>receiptOrderSaveDistSellStatis is end ");
    }

    /**
     * 查询商品库存数量变化后未共享的商品数据，批量修改该商品的门店商品库存信息
     */
    public void updateProductStoreByGoodsShareStock(){
        logger.info(">>>>>>>>>>>>>>>>>>>>updateProductStoreByGoodsShareStock is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询商品库存数量变化后未共享的商品数据，批量修改该商品的门店商品库存信息 ");

        // 查询商品库存数量变化后未共享的商品数据
        List<Map> goodsList = qzOrderMapper.queryGoodsListByIsShareStock();
        if (null != goodsList && goodsList.size() > 0) {
            for (Map map : goodsList) {
                Integer goodsId = MapUtils.getInteger("goodsId", map);
                Integer goodsNumber = MapUtils.getInteger("goodsNumber", map);
                String merchSn = MapUtils.getString("merchSn", map);

                List<Map> storeRelaList = qzOrderMapper.queryStoreRelaListByGoodsId(goodsId);
                for (Map storeRelaMap : storeRelaList) {
                    Integer storeRelaId = MapUtils.getInteger("storeRelaId", storeRelaMap);
                    Integer storeId = MapUtils.getInteger("storeId", storeRelaMap);
                    Integer stockNum = MapUtils.getInteger("stockNum", storeRelaMap);//原有库存
                    Map param = Maps.newHashMap();
                    param.put("id", storeRelaId);
                    param.put("stock_num", goodsNumber);
                    qzOrderMapper.updateStockNum(param);//修改该商品的门店商品库存信息

                    StoreMngChangeJobEntity storeMngChangeJobEntity = new StoreMngChangeJobEntity();
                    storeMngChangeJobEntity.setChangeReason("共享库存变更，门店商品库存同步更新");
                    storeMngChangeJobEntity.setGoodsId(goodsId);
                    storeMngChangeJobEntity.setStoreId(storeId);
                    storeMngChangeJobEntity.setMerchSn(merchSn);
                    storeMngChangeJobEntity.setCreateTime(new Date());
                    storeMngChangeJobEntity.setModTime(new Date());
                    storeMngChangeJobEntity.setCreaterSn("定时任务");
                    storeMngChangeJobEntity.setModerSn("定时任务");
                    storeMngChangeJobEntity.setIsValid(0);
                    if(goodsNumber != stockNum) {
                        if (stockNum > goodsNumber) {
                            storeMngChangeJobEntity.setStoreChangeNum(stockNum - goodsNumber);//变化数
                            storeMngChangeJobEntity.setChangeType(Dict.changeType.item_4.getItem());
                        } else {
                            storeMngChangeJobEntity.setChangeType(Dict.changeType.item_3.getItem());
                            storeMngChangeJobEntity.setStoreChangeNum(goodsNumber - stockNum);//变化数
                        }
                        storeMngChangeJobEntity.setStoreOriginalNum(stockNum);//原库存数
                        storeMngChangeJobEntity.setStoreValidNum(goodsNumber);//可用数
                        qzOrderMapper.saveStoreMngChange(storeMngChangeJobEntity);
                    }
                }
                Map goodsMap = new HashMap();
                goodsMap.put("goodsId", goodsId);
                //商品库存数量变化后是否已共享,0：否，1：是(下单、退款、取消订单触发)
                goodsMap.put("isGoodsShareStock", Dict.isGoodsShareStock.item_1.getItem());
                qzOrderMapper.updateByGoodsShareStock(goodsMap);
            }
        }else{
            logger.info(">>>>>>>>>>>>>>>>>>>>未查到商品库存数量变化后未共享的商品数据");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>updateProductStoreByGoodsShareStock is end ");

    }

    /**
     * 查询订单中支付成功的订单详情，更新详情中商品的销量信息
     */
    public void updateSellVolume(){
        logger.info(">>>>>>>>>>>>>>>>>>>>updateSellVolume is start ");
        logger.info(">>>>>>>>>>>>>>>>>>>>查询订单中支付成功的订单详情，更新详情中商品的销量信息 ");

        // 获取收货后的订单
        List<Map> orderGoodsList = qzOrderMapper.queryOrderIdByOrderGoodsList();
        if (null != orderGoodsList && orderGoodsList.size() > 0) {
            for (Map map : orderGoodsList) {
                Integer orderId = MapUtils.getInteger("orderId", map);
                Integer storeRelaId = MapUtils.getInteger("storeRelaId", map);
                Map sellMap = qzOrderMapper.queryOrderCountByIdAndPayStatus(storeRelaId);
                BigDecimal sellVolume = MapUtils.getBigDecimal("sellVolume", sellMap);

                Map param = Maps.newHashMap();
                param.put("id", storeRelaId);
                param.put("sell_volume", sellVolume);
                qzOrderMapper.updateStockNum(param);//更新门店商品销量

            }
        }else{
            logger.info(">>>>>>>>>>>>>>>>>>>>订单中支付成功的订单详情没有数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>updateSellVolume is end ");
    }

    /**
     * 释放优惠券
     * @param map
     */
    private void restUserCoupon(Map map){
        Long orderId = MapUtils.getLong("orderId", map);
        Map couponMap = qzOrderMapper.queryUserCouponByOrderId(orderId);
        if (null != couponMap) {
            Long couponId = MapUtils.getLong("couponId", couponMap);
            Map updateCouponMap = new HashMap();
            updateCouponMap.put("id", couponId);
            qzOrderMapper.cancelUserCouponOrder(updateCouponMap);
        }
    }
    /**
     * 释放促销满减券
     * @param map
     */
    private void restUserCamp(Map map){
        Long orderId = MapUtils.getLong("orderId", map);
        Map campMap = qzOrderMapper.queryUserCampByOrderId(orderId);
        if (null != campMap) {
            Long userCampId = MapUtils.getLong("userCampId", campMap);
            Map updateCampMap = new HashMap();
            updateCampMap.put("userCampId", userCampId);
            qzOrderMapper.cancelUserCampOrder(updateCampMap);
        }
    }
    /**
     * 还原库存
     * @param map
     */
    private void restStockNum(Map map, String changeReason){
        String isStockShare = getIsStockShareByGoodsVo(map);
        resetGoodsStockNum(map, changeReason);
        String goodsBizType = MapUtils.getString("goods_biz_type", map);
        Integer goodsId = MapUtils.getInteger("goods_id", map);
        //该商品所属第三方商户不是共享库存
        if(isStockShare.equalsIgnoreCase(Dict.isStockShare.item_0.getItem())) {
            resetStoreStockNumAndSellVolume(map, changeReason);//还原门店商品库存
        }else{
            //该商品所属第三方商户是共享库存，但商品业务类型不是00保税备货
            if(!goodsBizType.equalsIgnoreCase(Dict.orderBizType.item_00.getItem())){
                resetStoreStockNumAndSellVolume(map, changeReason);//还原门店商品库存
            }
        }
        //该商品所属第三方商户为共享库存，且是保税备货商品，取消订单时改变
        updateGoodsByIsShareStock(isStockShare, goodsBizType, goodsId);
    }

    /**
     * 还原商品总库存
     * @param map
     * @param changeReason
     */
    private void resetGoodsStockNum(Map map, String changeReason){
        Integer goods_number = MapUtils.getInteger("goods_number", map);//商品总库存数
        Integer number = MapUtils.getInteger("number", map);//订单商品购买数
        Long goods_id = MapUtils.getLong("goods_id", map);
        String merch_sn = MapUtils.getString("merch_sn", map);
        String third_party_merch_code = MapUtils.getString("third_party_merch_code", map);

        Map param = Maps.newHashMap();
        param.put("id", goods_id);
        param.put("goods_number", goods_number + number);
        qzOrderMapper.updateGoodsStockNum(param);//商户商品库存还原

        MngChangeJobEntity mngChangeJobEntity = new MngChangeJobEntity();
        mngChangeJobEntity.setGoodsId(Integer.parseInt(String.valueOf(goods_id)));
        mngChangeJobEntity.setThirdPartyMerchCode(third_party_merch_code);
        mngChangeJobEntity.setChangeReason(changeReason);
        mngChangeJobEntity.setChangeType(Dict.changeType.item_0.getItem());
        mngChangeJobEntity.setChangeNum(number);//变化数
        mngChangeJobEntity.setOriginalNum(goods_number);//原库存数
        mngChangeJobEntity.setValidNum(goods_number + number);//可用数
        mngChangeJobEntity.setCreateTime(new Date());
        mngChangeJobEntity.setModTime(new Date());
        mngChangeJobEntity.setCreaterSn("定时任务");
        mngChangeJobEntity.setModerSn("定时任务");
        mngChangeJobEntity.setIsValid(0);
        mngChangeJobEntity.setMerchSn(merch_sn);
        qzOrderMapper.saveMngChange(mngChangeJobEntity);
    }

    /**
     * 还原门店商品库存
     * @param map
     * @param changeReason
     */
    private void resetStoreStockNumAndSellVolume(Map map, String changeReason){
        Integer number = MapUtils.getInteger("number", map);//订单商品购买数
        Integer stock_num = MapUtils.getInteger("stock_num", map);//门店商品总库存数
        Long storeRelaId = MapUtils.getLong("storeRelaId", map);
        Long goods_id = MapUtils.getLong("goods_id", map);
        Long store_id = MapUtils.getLong("store_id", map);
        String merch_sn = MapUtils.getString("merch_sn", map);

        Map param = Maps.newHashMap();
        param.put("id", storeRelaId);
        param.put("stock_num", stock_num + number);
        Integer sell_volume = MapUtils.getInteger("store_sell_volume", map);//销量
        if(sell_volume >= number){
            param.put("sell_volume", sell_volume - number);
        }
        qzOrderMapper.updateStockNum(param);//门店库存还原
        StoreMngChangeJobEntity storeMngChangeJobEntity = new StoreMngChangeJobEntity();
        storeMngChangeJobEntity.setChangeType(Dict.changeType.item_0.getItem());
        storeMngChangeJobEntity.setChangeReason(changeReason);
        storeMngChangeJobEntity.setGoodsId(Integer.parseInt(String.valueOf(goods_id)));
        storeMngChangeJobEntity.setStoreId(Integer.parseInt(String.valueOf(store_id)));
        storeMngChangeJobEntity.setMerchSn(merch_sn);
        storeMngChangeJobEntity.setCreateTime(new Date());
        storeMngChangeJobEntity.setModTime(new Date());
        storeMngChangeJobEntity.setStoreChangeNum(number);
        storeMngChangeJobEntity.setStoreOriginalNum(stock_num);
        storeMngChangeJobEntity.setStoreValidNum(stock_num + number);
        storeMngChangeJobEntity.setCreaterSn("定时任务");
        storeMngChangeJobEntity.setModerSn("定时任务");
        storeMngChangeJobEntity.setIsValid(0);
        qzOrderMapper.saveStoreMngChange(storeMngChangeJobEntity);
    }
    /**
     * 更新商品库存数量变化后是否已共享为0“未共享”
     * @param isStockShare
     */
    private void updateGoodsByIsShareStock(String isStockShare, String goodsBizType, Integer goodsId){
        //该商品所属第三方商户为共享库存，且是保税备货商品
        if(isStockShare.equalsIgnoreCase(Dict.isStockShare.item_1.getItem())
                && goodsBizType.equalsIgnoreCase(Dict.orderBizType.item_00.getItem())) {
            Map goodsMap = new HashMap();
            goodsMap.put("goodsId", goodsId);
            //商品库存数量变化后是否已共享,0：否，1：是(下单、退款、取消订单触发)
            goodsMap.put("isGoodsShareStock", Dict.isGoodsShareStock.item_0.getItem());
            qzOrderMapper.updateByGoodsShareStock(goodsMap);
        }
    }

    private String getIsStockShareByGoodsVo(Map map){
        String isStockShare = "";
        String isSupplierGoods = MapUtils.getString("isSupplierGoods", map);
        if(isSupplierGoods.equalsIgnoreCase(Dict.isSupplierGoods.item_0.getItem())) {
            isStockShare = MapUtils.getString("isStockShare", map);
        }else{
            isStockShare = MapUtils.getString("isStockShareBySuppler", map);
        }
        return isStockShare;
    }

    private List<Integer> getExpendDistId(String expendDistIds){
        List<Integer> expendDistIdList = new ArrayList<>();
        String[] expendIds = expendDistIds.split(",");
        for (int i=0;i<expendIds.length;i++){
            expendDistIdList.add(Integer.parseInt(expendIds[i]));
        }
        return expendDistIdList;
    }

    private List<Double> getExpendDistLines(String expendDistLines){
        List<Double> expendDistLinesList = new ArrayList<>();
        String[] expendLines = expendDistLines.split(",");
        for (int i=0;i<expendLines.length;i++){
            expendDistLinesList.add(Double.parseDouble(expendLines[i]));
        }
        return expendDistLinesList;
    }

    public long getDateBetween(Date begin, Date end) {
        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long between = (end.getTime() - begin.getTime()) / 1000;

        long min = between / 60;

        return min;
    }

    public static void main(String[] args) {

        SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        long between = (new Date().getTime() - DateUtils.strToDate("2018-11-16 09:30:12").getTime()) / 1000;

        long min = between / 60;
        System.out.println(min);
        //        Calendar calendar = Calendar.getInstance();
        //        calendar.add(Calendar.DAY_OF_MONTH, 3);
        //
        //        long time = (calendar.getTime().getTime() - System.currentTimeMillis()) / 1000;
        //        System.out.println(calendar.getTime().getTime());
        //        System.out.println(System.currentTimeMillis());
        //        long hour = time / 3600;
        //        long minite = time / 60 % 60;
        //        long second = (time - hour * 3600 - minite * 60);
        //
        //        String body = hour + "时" + minite + "分" + second + "秒";
        //        System.out.println(body);

        long currentTime = System.currentTimeMillis() + 2 * 60 * 60 * 1000;
        Date date = new Date(currentTime);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = "";
        nowTime = df.format(date);
        System.out.println(nowTime);

        Date successTime = DateUtils.strToDate("2018-11-02 14:57:12.0");
        System.out.println(successTime);
    }
}
