package com.kmall.schedule.service;

import com.kmall.common.utils.Constant;
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.schedule.dao.QzGroupMapper;
import com.kmall.schedule.dao.QzOrderMapper;
import com.kmall.common.dao.TemplateConfDao;
import com.kmall.common.entity.TemplateConfVo;
import com.kmall.schedule.quartz.OrderTask;
import com.kmall.common.utils.DateUtils;
import com.kmall.common.utils.MapUtils;
import com.kmall.common.utils.StringUtils;
import com.kmall.common.utils.wxtemplate.TemplateData;
import com.kmall.common.utils.wxtemplate.WxTemplate;
import com.kmall.common.utils.wxtemplate.WxTemplateUtil;
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;

    /**
     * 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 ");
        // 获取快过期订单
        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 ");
        // 获取退款中或更新退款信息异常订单
        List<Map> refundOrderList = qzOrderMapper.queryRefundOrderList();
        if (null != refundOrderList && refundOrderList.size() > 0) {
            for (Map map : refundOrderList) {
                String out_trade_no = MapUtils.getString("merch_order_sn", map);
                String order_id = MapUtils.getString("order_id", map);
                WechatRefundQueryResult result = WechatUtil.wxRefundquery(out_trade_no);
                if (result.getReturn_code().equalsIgnoreCase("SUCCESS")) {
                    if(result.getResult_code().equalsIgnoreCase("SUCCESS")) {
                        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 (result.getReturn_code().equalsIgnoreCase("SUCCESS")) {
                                if (result.getResult_code().equalsIgnoreCase("SUCCESS")) {
                                    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("SUCCESS")) {
                                        refundRaram.put("refundStatus", 2);
                                        refundRaram.put("wechat_refund_status_des", "退款成功");
                                    } else if (result.getRefund_status().equalsIgnoreCase("REFUNDCLOSE")) {
                                        refundRaram.put("refundStatus", 4);
                                        refundRaram.put("wechat_refund_status_des", "退款关闭");
                                    } else if (result.getRefund_status().equalsIgnoreCase("PROCESSING")) {
                                        refundRaram.put("refundStatus", 5);
                                        refundRaram.put("wechat_refund_status_des", "退款处理中");
                                    } else if (result.getRefund_status().equalsIgnoreCase("CHANGE")) {
                                        refundRaram.put("refundStatus", 4);
                                        refundRaram.put("wechat_refund_status_des", "退款异常");
                                    }
                                    refundRaram.put("refundRecvAccout", result.getRefund_recv_accout());
                                    refundRaram.put("orderRefundId", result.getOut_refund_no());
                                    qzOrderMapper.updateOrderRefund(refundRaram);//更新订单退款信息
                                }
                            }
                        }

                        Map orderRaram = new HashMap();
                        orderRaram.put("payStatus", 4);
                        orderRaram.put("orderStatus", 401);
                        orderRaram.put("orderId", order_id);
                        orderRaram.put("payTransactionId", result.getTransaction_id());
                        qzOrderMapper.updateOrderInfo(orderRaram);
                    }else{
                        logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate 微信退款查询接口返回失败信息：code 【"+result.getErr_code()+"】，des【"+result.getErr_code_des()+"】");
                    }
                }else {
                    logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate 微信退款查询接口调用失败： "+result.getReturn_msg());
                }
            }
        }else{
            logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate 未查到退款数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>refundUpdate is end ");
    }


    /**
     * 查询支付中的订单以及小程序更新支付信息异常订单，查询微信订单更新订单状态
     */
    @Transactional
    public void orderQueryUpdate() {
        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate is start ");
        // 获取支付中的订单以及小程序更新支付信息异常订单
        List<Map> orderList = qzOrderMapper.queryPayingOrderList();
        if (null != orderList && orderList.size() > 0) {
            for (Map map : orderList) {
                String out_trade_no = MapUtils.getString("merch_order_sn", map);
                String orderId = MapUtils.getString("order_id", map);
                WechatRefundApiResult result = WechatUtil.wxOrderQuery(out_trade_no);
                if (result.getReturn_code().equalsIgnoreCase("SUCCESS")) {
                    if(result.getResult_code().equalsIgnoreCase("SUCCESS") && result.getTrade_state().equalsIgnoreCase("SUCCESS")) {
                        Date successTime = DateUtils.convertStringToDate(result.getTime_end(),DateUtils.DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS);

                        Map orderRaram = new HashMap();
                        orderRaram.put("payStatus", 2);
                        orderRaram.put("orderStatus", 201);
                        orderRaram.put("payTransactionId", result.getTransaction_id());
                        orderRaram.put("payTime", successTime);
                        orderRaram.put("orderId", orderId);
                        qzOrderMapper.updateOrderInfo(orderRaram);
                    }else{
                        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate 微信查询接口返回失败信息：code 【"+result.getErr_code()+"】，des【"+result.getErr_code_des()+"】");
                    }
                }else {
                    logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate 微信查询接口调用失败： "+result.getReturn_msg());
                }
            }
        }else{
            logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate 未查到订单数据 ");
        }
        logger.info(">>>>>>>>>>>>>>>>>>>>orderQueryUpdate is end ");
    }

    public static void main(String[] args) {
//        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");
        System.out.println(successTime);
    }
}
