package com.kmall.schedule.service;

import com.kmall.common.constant.Dict;
import com.kmall.common.utils.*;
import com.kmall.common.utils.pay.data.open.cus.CusPropertiesBuilder;
import com.kmall.common.utils.wechat.*;
import com.kmall.common.utils.wechat.wxglobal.WechatGlobalUtil;
import com.kmall.common.utils.wechat.wxglobal.dto.WechatGlobalQueryApiResult;
import com.kmall.common.utils.wechat.wxglobal.dto.WechatGlobalRefundQueryResult;
import com.kmall.schedule.dao.OrderWXPayRecordMapper;
import com.kmall.schedule.dao.QzGroupMapper;
import com.kmall.schedule.dao.QzOrderMapper;
import com.kmall.common.dao.TemplateConfDao;
import com.kmall.common.entity.TemplateConfVo;
import com.kmall.common.utils.*;
import com.kmall.common.utils.pingan.PinganUtil;
import com.kmall.common.utils.pingan.dto.PinganPayOrderDto;
import com.kmall.common.utils.pingan.dto.PinganResponseDto;
import com.kmall.common.utils.wechat.ReaderXmlForDOM4J;
import com.kmall.common.utils.wechat.WechatRefundApiResult;
import com.kmall.common.utils.wechat.WechatRefundQueryResult;
import com.kmall.common.utils.wechat.WechatUtil;
import com.kmall.common.utils.wxtemplate.TemplateData;
import com.kmall.common.utils.wxtemplate.WxTemplate;
import com.kmall.common.utils.wxtemplate.WxTemplateUtil;
import com.kmall.schedule.dao.OrderWXPayRecordMapper;
import com.kmall.schedule.dao.QzGroupMapper;
import com.kmall.schedule.dao.QzOrderMapper;
import com.kmall.schedule.quartz.OrderTask;
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(OrderTask.class);
    @Autowired
    private TemplateConfDao templateConfDao;
    @Autowired
    private QzGroupMapper qzGroupMapper;
    @Autowired
    private QzOrderMapper qzOrderMapper;
    @Autowired
    private OrderWXPayRecordMapper orderWXPayRecordMapper;

    /**
     * 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, "#000000"));
                paras.add(new TemplateData("keyword2", DateUtils.format(open_time, DateUtils.DATE_PATTERN), "#000000"));
                paras.add(new TemplateData("keyword3", "已有" + attend_num + "人参与", "#000000"));
                //剩余时长
                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, "#000000"));
                paras.add(new TemplateData("keyword4", retail_min_price.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString() + "元", "#000000"));
                paras.add(new TemplateData("keyword5", templateConfVo.getDesc(), "#000000"));
                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, "#000000"));
                paras.add(new TemplateData("keyword2", attend_num + "/" + min_open_group, "#000000"));
                paras.add(new TemplateData("keyword3", retail_min_price + "元", "#000000"));
                paras.add(new TemplateData("keyword4", templateConfVo.getDesc(), "#000000"));
                tem.setData(paras);
                WxTemplateUtil.sendMessage(tem);
                // 更新团购失败订单
                Map updateFailParams = new HashMap();
                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, "#000000"));
                paras.add(new TemplateData("keyword2", order_sn, "#000000"));
                paras.add(new TemplateData("keyword3", templateConfVo.getDesc(), "#000000"));
                tem.setData(paras);
                WxTemplateUtil.sendMessage(tem);
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>orderUnEvaluateRemind 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) {
                Integer number = MapUtils.getInteger("number", map);
                Integer stock_num = MapUtils.getInteger("stock_num", map);
                Long storeRelaId = MapUtils.getLong("storeRelaId", map);
                Map param = new HashMap();
                param.put("id", storeRelaId);
                param.put("stock_num", stock_num + number);
                qzOrderMapper.updateStockNum(param);
            }
            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("order_id", 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("order_id", 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 = new HashMap();
                Map orderRaram = new HashMap();
                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(">>>>>>>>>>>>>>>>>>>>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("order_id", 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 = new HashMap();
                Map orderParam = new HashMap();

                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);
                        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());
                            } 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);//更新订单退款信息
                        }
                    }
                } else {
                    WechatRefundQueryResult refundQueryResult = PinganUtil.buildWechatRefundQueryResult(result);
                    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());
                        } 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);//更新订单退款信息
                    }
                }
                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 = new HashMap();
                Map orderRaram = new HashMap();
                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());
        }*/
    }

    /**
     * 微信国际支付微信查询订单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("order_id", 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 = new HashMap();
                Map refundRaram = new HashMap();
                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_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());
                        } 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(">>>>>>>>>>>>>>>>>>>>refundUpdate 订单编号【"+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("order_id", 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();

        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 = new HashMap();
                    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 = new HashMap();
                    processParam.put("payTime", successTime);
                    processParam.put("orderSn", orderSn);
                    qzOrderMapper.updateOrderProcessRecord(processParam);
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {//订单未支付
                    Map orderRaram = new HashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        Map param = new HashMap();
                        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 if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_CLOSED.getItem())) {
                    Map orderRaram = new HashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_7.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_500.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    Map param = new HashMap();
                    param.put("id", storeRelaId);
                    param.put("stock_num", stock_num + number);
                    qzOrderMapper.updateStockNum(param);//库存还原
                    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 = new HashMap();
                    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 = new HashMap();
                    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("order_id", 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 = new HashMap();
                    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 = new HashMap();
                    processParam.put("payTime", successTime);
                    processParam.put("orderSn", orderSn);
                    qzOrderMapper.updateOrderProcessRecord(processParam);
                } else if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_NOTPAY.getItem())) {//订单未支付
                    Map orderRaram = new HashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        Map param = new HashMap();
                        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 if (result.getTrade_state().equalsIgnoreCase(Dict.tradeState.item_CLOSED.getItem())) {
                    Map orderRaram = new HashMap();
                    orderRaram.put("payStatus", Dict.payStatus.item_7.getItem());
                    orderRaram.put("orderStatus", Dict.orderStatus.item_500.getItem());
                    orderRaram.put("orderId", orderId);
                    qzOrderMapper.updateOrderInfo(orderRaram);
                    Map param = new HashMap();
                    param.put("id", storeRelaId);
                    param.put("stock_num", stock_num + number);
                    qzOrderMapper.updateStockNum(param);//库存还原
                    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 = new HashMap();
                    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 = new HashMap();
                    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("order_id", map);
                String orderSn = MapUtils.getString("order_sn", map);
                String add_time = MapUtils.getString("add_time", map);
                Integer number = MapUtils.getInteger("number", map);
                Integer stockNum = MapUtils.getInteger("stock_num", map);
                Long storeRelaId = MapUtils.getLong("storeRelaId", 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 = new HashMap();
                            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 = new HashMap();
                            processParam.put("payTime", payOrderDto.getTradeTime());
                            processParam.put("orderSn", orderSn);
                            qzOrderMapper.updateOrderProcessRecord(processParam);
                        } else {
                            Map orderRaram = new HashMap();
                            if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                                orderRaram.put("payStatus", 0);//支付状态未支付
                                orderRaram.put("orderStatus", 101);//订单状态已取消
                                Map param = new HashMap();
                                param.put("id", storeRelaId);
                                param.put("stock_num", stockNum + number);
                                qzOrderMapper.updateStockNum(param);
                            } 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 = new HashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        Map param = new HashMap();
                        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 = new HashMap();
                    if (getDateBetween(addTime, nowDate) >= 15) {//订单下单时间超过15分钟直接取消订单
                        Map param = new HashMap();
                        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 = new HashMap();
                    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 = new HashMap();
                            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();
        if (null != shipmentOrderList && shipmentOrderList.size() > 0) {
            for (Map map : shipmentOrderList) {
                Map orderMap = new HashMap();
                orderMap.put("orderId", MapUtils.getLong("orderId", map));
                qzOrderMapper.updateShipmentOrder(orderMap);
            }
        }
        //查询保税备货发货后7天的订单，保税备货根据发货完成时间后7天
        List<Map> shipmentBondedOrderList = qzOrderMapper.queryShipmentBondedOrderList();
        if (null != shipmentBondedOrderList && shipmentBondedOrderList.size() > 0) {
            for (Map map : shipmentBondedOrderList) {
                Map orderMap = new HashMap();
                orderMap.put("orderId", MapUtils.getLong("orderId", map));
                qzOrderMapper.updateShipmentOrder(orderMap);
            }
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>shipmentOrderAutoTakeGoods is end ");
    }

    /**
     * 确认收货后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 = new HashMap();
                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());
                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(">>>>>>>>>>>>>>>>>>>>receiptOrderAutoComment is end ");
    }

    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);
    }
}
