package com.hai.schedule;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hai.common.utils.HttpsUtils;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.config.QianZhuConfig;
import com.hai.config.WxOrderConfig;
import com.hai.entity.*;
import com.hai.model.OrderRefundModel;
import com.hai.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import javax.xml.ws.RespectBinding;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: 胡锐
 * @Description: 订单定时任务
 * @Date: 2021/3/27 15:41
 */
@Configuration
public class HighOrderSchedule {

    private static final Logger log = LoggerFactory.getLogger(HighOrderSchedule.class);

    @Resource
    private HighOrderService highOrderService;

    @Resource
    private OutRechargeOrderService outRechargeOrderService;

    @Resource
    private OutRechargeChildOrderService rechargeChildOrderService;

    @Resource
    private HighGoldRecService highGoldRecService;

    @Resource
    private BsIntegralRebateService bsIntegralRebateService;

    /**
     * @Author 胡锐
     * @Description 取消订单  15分钟
     * @Date 2021/4/4 22:45
     **/
    @Scheduled(cron = "0 0/1 * * * ?")   //每1分钟执行一次
    public void cancelOrder() {
        List<HighOrder> orderList = highOrderService.getCloseOrder();
        if (orderList != null && orderList.size() > 0) {
            for (HighOrder order : orderList) {
                try {
                    highOrderService.cancelOrder(order.getId());
                } catch (Exception e) {
                    log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                }
            }
        }
    }

    /**
     * @return void
     * @Author Sum1Dream
     * @name cancelMobileOrder.java
     * @Description // 取消话费订单
     * @Date 3:33 下午 2021/12/10
     * @Param []
     */
    @Scheduled(cron = "0 0/1 * * * ?")   //每15分钟执行一次
    public void cancelMobileOrder() {
        List<OutRechargeOrder> orderList = outRechargeOrderService.getOutRechargeOrderList();
        if (orderList != null && orderList.size() > 0) {
            for (OutRechargeOrder order : orderList) {
                try {
                    outRechargeOrderService.cancelOrder(order.getId());
                } catch (Exception e) {
                    log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                }
            }
        }
    }

    /**
     * @return void
     * @Author Sum1Dream
     * @name cancelOrder.java
     * @Description // 定时发起
     * @Date 14:18 2022/5/31
     * @Param []
     */
    @Scheduled(cron = "0 0/1 * * * ?")   //每5分钟执行一次
    public void initRechargeOrder() {
        Map<String, Object> map = new HashMap<>();
        map.put("payStatus", String.valueOf(102));
        map.put("rechargeStatus", String.valueOf(204));
        List<OutRechargeOrder> orderList = outRechargeOrderService.getListRechargeOrder(map);
        if (orderList.size() > 0) {
            for (OutRechargeOrder order : orderList) {
                try {
                    // 查询充值子订单
                    Map<String, Object> childOrderMap = new HashMap<>();
                    childOrderMap.put("parent_order_id", order.getId());
                    childOrderMap.put("status", 102);

                    List<OutRechargeChildOrder> childOrderList = rechargeChildOrderService.getListRechargeChildOrder(childOrderMap);

                    System.out.println("话费定时任务 -> 判断是否存在已支付订单：订单id：" + order.getId());
                    if (childOrderList.size() == 0) {
                        Date rechargeTime = order.getCreateTimed();
                        Date currentTime = new Date();
                        int hours = (int) ((currentTime.getTime() - rechargeTime.getTime()) / (1000 * 60 * 60));

                        // 判断快充 并且 充值时间小于6
//                        if (order.getRechargeType() == 1 && hours < 6) {
//                            System.out.println("话费定时任务 -> 请求快充：订单id：" + order.getId());
//                            outRechargeOrderService.pollRequest(order);
//                            continue;
//                        }
                        // 判断慢充 并且 充值时间小于72
                        if (hours < 72) {
                            System.out.println("话费定时任务 -> 请求慢充：订单id：" + order.getId());
                            outRechargeOrderService.pollRequest(order);
                            continue;
                        }
                        System.out.println("话费定时任务 -> 退款任务" + order.getId());
                        outRechargeOrderService.rechargeOrderToRefund(order.getId());

                    }
                } catch (Exception e) {
                    log.error("HighCouponSchedule --> expiredCoupon() error!", e);
                }
            }
        }
        System.out.println("话费定时任务 -> 结束任务");
    }

    /**
     * @Author 胡锐
     * @Description 处理话费充值订单
     * @Date 2021/4/4 22:45
     **/
    @Scheduled(cron = "0 0/1 * * * ?")   //每1分钟执行一次
    public void handleMobileOrder() {
        List<HighOrder> orderList = highOrderService.getAlreadyPaidMobileOrder();
        if (orderList != null && orderList.size() > 0) {
            for (HighOrder order : orderList) {
                try {
                    HighOrder highOrder = highOrderService.getOrderById(order.getId());
                    if (highOrder != null) {
                        JSONObject mobileOrderJson = QianZhuConfig.getMobileOrderByOrderNo(highOrder.getOrderNo());
                        if (mobileOrderJson != null && mobileOrderJson.getBoolean("success") == true) {
                            JSONObject data = mobileOrderJson.getJSONObject("data");

                            // 订单状态 0:待付款 5:已支付 10:充值中 15:交易成功 -5:已取消 -10:充值失败
                            if (data.getInteger("status") == 15) {
                                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                                    childOrder.setChildOrdeStatus(3);
                                }
                                highOrder.setOrderStatus(3);
                                highOrder.setFinishTime(new Date());
                                highOrderService.updateOrder(highOrder);
                            }
                            if (data.getInteger("status") == -10 || data.getInteger("status") == -5) {
                                if (highOrder.getPaySerialNo() != null && highOrder.getPayRealPrice() != null) {
                                    OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(highOrder.getPaySerialNo(), highOrder.getPayRealPrice(), highOrder.getPayRealPrice());
                                    if (orderRefundModel.getResult_code().equals("SUCCESS")) {
                                        for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                                            childOrder.setChildOrdeStatus(4);
                                        }
                                        highOrder.setOrderStatus(4);
                                        highOrder.setRefundTime(new Date());
                                        highOrder.setRefundPrice(highOrder.getPayRealPrice());
                                        highOrderService.updateOrder(highOrder);
                                    }
                                } else {
                                    for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                                        childOrder.setChildOrdeStatus(5);
                                    }
                                    highOrder.setCancelTime(new Date());
                                    highOrder.setOrderStatus(5);
                                    highOrderService.updateOrder(highOrder);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("HighCouponSchedule --> handleMobileOrder() error!", e);
                }
            }
        }
    }

    /**
    * @Author Sum1Dream
    * @name handleThirdOrder.java
    * @Description // 处理第三方订单
    * @Date 16:24 2022/7/8
    * @Param []
    * @return void
    */
    @Scheduled(cron = "0 0/1 * * * ?")   //每1分钟执行一次
    public void handleThirdOrder() {
        List<HighOrder> orderList = highOrderService.getThirdOrder();
        // 判断是否存在订单
        if (orderList != null && orderList.size() > 0) {
            for (HighOrder order : orderList) {
                try {
                    HighOrder highOrder = highOrderService.getOrderById(order.getId());
                    if (highOrder != null) {
                        // 肯德基订单
                        if (highOrder.getHighChildOrderList().get(0).getGoodsType() == 4) {
                            JSONObject orderObject = QianZhuConfig.getKfcOrderByOrderNo(highOrder.getOrderNo());
                            if (orderObject != null && orderObject.getBoolean("success")) {
                                JSONObject data = orderObject.getJSONObject("data");
                                // 订单状态 0:待付款 5:排队中 15:TRAN_SUCCESS:交易成功 -5:已取消
                                if (data.getInteger("status") == 15) {
                                    for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                                        childOrder.setChildOrdeStatus(3);
                                    }
                                    highOrder.setOrderStatus(3);
                                    highOrder.setFinishTime(new Date());
                                    highOrderService.updateOrder(highOrder);
                                }
                                // 订单失败
                                if (data.getInteger("status") == -5) {
                                    if (highOrder.getOrderStatus() == 2) {
                                        highOrderService.thirdOrderToRefund(order.getId());
                                    } else {
                                        highOrderService.thirdCancelOrder(order.getId());
                                    }
                                }
                            }
                        } else if (highOrder.getHighChildOrderList().get(0).getGoodsType() == 9) {
                            // 星巴克订单
                            // 根据订单号查询订单详情
                            JSONObject orderObject = QianZhuConfig.starbucksOrderByOrderNo(highOrder.getOrderNo());
                            if (orderObject != null && orderObject.getBoolean("success")) {
                                JSONObject data = orderObject.getJSONObject("data");
                                // 订单状态 0:待付款 5:已支付 10:出单中 15:出单成功 20:配送中 25:配送完成 -5:已取消 -10:失败
                                if (data.getInteger("status") == 15) {
                                    for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                                        childOrder.setChildOrdeStatus(3);
                                    }
                                    highOrder.setOrderStatus(3);
                                    highOrder.setFinishTime(new Date());
                                    highOrderService.updateOrder(highOrder);
                                }
                                // 订单失败
                                if (data.getInteger("status") == -5) {
                                    if (highOrder.getOrderStatus() == 2) {
                                        highOrderService.thirdOrderToRefund(order.getId());
                                    } else {
                                        highOrderService.thirdCancelOrder(order.getId());
                                    }
                                }
                            }
                        } else if (highOrder.getHighChildOrderList().get(0).getGoodsType() == 10) {
                            // 会员充值订单
                            // 根据订单号查询订单详情
                            JSONObject orderObject = QianZhuConfig.QueryV2(highOrder.getOrderNo());

                            if (orderObject != null && orderObject.getLong("Code") == 999) {
                                // 订单失败  // 订单状态 1:订单正在处理中 2;订单成功:	3 订单失败
                                if (orderObject.getJSONObject("Data").getInteger("OrderState") == 3) {
                                    // 订单失败
                                    if (order.getOrderStatus() == 2) {
                                        highOrderService.thirdOrderToRefund(order.getId());
                                    } else {
                                        highOrderService.thirdCancelOrder(order.getId());
                                    }
                                }
                                // 订单状态 1:订单正在处理中 2;订单成功:	3 订单失败
                                if (orderObject.getJSONObject("Data").getInteger("OrderState") == 2) {
                                    for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
                                        childOrder.setChildOrdeStatus(3);
                                    }
                                    highOrder.setOrderStatus(3);
                                    highOrder.setFinishTime(new Date());
                                    highOrderService.updateOrder(highOrder);
                                }
                            }

                        }
                    }
                } catch (Exception e) {
                    log.error("HighOrderSchedule --> handleThirdOrder() error!", e);
                }
            }
        }
    }

//    /**
//     * @Author 胡锐
//     * @Description 处理话KFC订单
//     * @Date 2021/4/4 22:45
//     **/
//    @Scheduled(cron = "0 0/1 * * * ?")   //每1分钟执行一次
//    public void handleKfcOrder() {
//        List<HighOrder> orderList = highOrderService.getAlreadyPaidKfcOrder();
//        if (orderList != null && orderList.size() > 0) {
//            for (HighOrder order : orderList) {
//                try {
//                    HighOrder highOrder = highOrderService.getOrderById(order.getId());
//                    if (highOrder != null) {
//                        JSONObject mobileOrderJson = QianZhuConfig.getKfcOrderByOrderNo(highOrder.getOrderNo());
//                        if (mobileOrderJson != null && mobileOrderJson.getBoolean("success")) {
//                            JSONObject data = mobileOrderJson.getJSONObject("data");
//
//                            // 订单状态 0:待付款 5:排队中 15:TRAN_SUCCESS:交易成功 -5:已取消
//                            if (data.getInteger("status") == 15) {
//                                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
//                                    childOrder.setChildOrdeStatus(3);
//                                }
//                                highOrder.setOrderStatus(3);
//                                highOrder.setFinishTime(new Date());
//                                highOrderService.updateOrder(highOrder);
//                            }
//
//                            if (data.getInteger("status") == -5) {
//                                if (highOrder.getPaySerialNo() != null && highOrder.getPayRealPrice() != null) {
//                                    OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(highOrder.getPaySerialNo(), highOrder.getPayRealPrice(), highOrder.getPayRealPrice());
//                                    if (orderRefundModel.getResult_code().equals("SUCCESS")) {
//                                        for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
//                                            childOrder.setChildOrdeStatus(4);
//                                        }
//                                        highOrder.setOrderStatus(4);
//                                        highOrder.setRefundTime(new Date());
//                                        highOrder.setRefundPrice(highOrder.getPayRealPrice());
//                                        highOrderService.updateOrder(highOrder);
//                                    }
//                                } else {
//                                    for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
//                                        childOrder.setChildOrdeStatus(5);
//                                    }
//                                    highOrder.setCancelTime(new Date());
//                                    highOrder.setOrderStatus(5);
//                                    highOrderService.updateOrder(highOrder);
//                                }
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                    log.error("HighCouponSchedule --> handleMobileOrder() error!", e);
//                }
//            }
//        }
//    }

//    /**
//     * @Author 胡锐
//     * @Description 处理电影票订单
//     * @Date 2021/4/4 22:45
//     **/
//    @Scheduled(cron = "0 0/1 * * * ?")   //每1分钟执行一次
//    public void handleCinemaOrder() {
//        List<HighOrder> orderList = highOrderService.getAlreadyPaidCinemaOrder();
//        if (orderList != null && orderList.size() > 0) {
//            for (HighOrder order : orderList) {
//                try {
//                    HighOrder highOrder = highOrderService.getOrderById(order.getId());
//                    if (highOrder != null) {
//                        JSONObject mobileOrderJson = QianZhuConfig.getCinemaOrderByOrderNo(highOrder.getOrderNo());
//                        if (mobileOrderJson != null && mobileOrderJson.getBoolean("success") == true) {
//                            JSONObject data = mobileOrderJson.getJSONObject("data");
//
//                            // 	订单状态 0:待付款 5:待出票 10:已出票 15:交易成功 -5:已取消
//                            if (data.getInteger("status") == 10 || data.getInteger("status") == 15) {
//                                for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
//                                    childOrder.setChildOrdeStatus(3);
//                                }
//                                highOrder.setOrderStatus(3);
//                                highOrder.setFinishTime(new Date());
//                                highOrderService.updateOrder(highOrder);
//                            }
//
//                            if (data.getInteger("status") == -5) {
//                                if (highOrder.getPaySerialNo() != null && highOrder.getPayRealPrice() != null) {
//                                    OrderRefundModel orderRefundModel = WxOrderConfig.orderToRefund(highOrder.getPaySerialNo(), highOrder.getPayRealPrice(), highOrder.getPayRealPrice());
//                                    if (orderRefundModel.getResult_code().equals("SUCCESS")) {
//                                        for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
//                                            childOrder.setChildOrdeStatus(4);
//                                        }
//                                        highOrder.setOrderStatus(4);
//                                        highOrder.setRefundTime(new Date());
//                                        highOrder.setRefundPrice(highOrder.getPayRealPrice());
//                                        highOrderService.updateOrder(highOrder);
//                                    }
//                                } else {
//                                    for (HighChildOrder childOrder : highOrder.getHighChildOrderList()) {
//                                        childOrder.setChildOrdeStatus(5);
//                                    }
//                                    highOrder.setCancelTime(new Date());
//                                    highOrder.setOrderStatus(5);
//                                    highOrderService.updateOrder(highOrder);
//                                }
//                            }
//                        }
//                    }
//                } catch (Exception e) {
//                    log.error("HighCouponSchedule --> handleMobileOrder() error!", e);
//                }
//            }
//        }
//    }

    /**
     * @Author 胡锐
     * @Description 完成团油订单  超过支付时间24小时订单自动完成
     * @Date 2021/4/4 22:45
     **/
    @Scheduled(cron = "0 0/1 * * * ?")   //每1分钟执行一次
    public void finishGasOrder() {
        List<Map<String, Object>> mapList = highOrderService.getFinishGasOrder();
        if (mapList != null && mapList.size() > 0) {
            for (Map<String, Object> map : mapList) {
                HighOrder order = highOrderService.getOrderById(Long.parseLong(map.get("orderId").toString()));
                if (order != null) {
                    order.setOrderStatus(3);
                    order.setFinishTime(new Date());
                    highOrderService.updateOrderDetail(order);
                }
            }
        }
    }
    /**
    * @Author Sum1Dream
    * @name integralRebateOrder.java
    * @Description // 执行返利操作
    * @Date 15:13 2022/8/22
    * @Param []
    * @return void
    */
    @Scheduled(cron="0 0/1 * * * ?")   //每1分钟执行一次
    public void integralRebateOrder() {
        List<HighOrder> order = highOrderService.integralRebateOrder();
        for (HighOrder highOrder : order) {
            Map<String, Object> map = new HashMap<>();
            map.put("goldType", 1);
            map.put("resType", 4);
            map.put("userId", highOrder.getMemId());
            map.put("resId", highOrder.getId());

            List<HighGoldRec> goldRecs = highGoldRecService.getGoldRec(map);

            if (goldRecs.size() == 0) {
                List<HighChildOrder> childOrderList = highOrderService.getChildOrderByOrder(highOrder.getId());

                // 查询订单来源
                JSONObject object = highOrderService.orderSource(childOrderList.get(0).getGoodsType() , childOrderList.get(0).getGoodsId(),highOrder.getOrderNo() , highOrder.getCompanyId());

                object.put("price" , highOrder.getPayRealPrice());
                object.put("userId" , highOrder.getMemId());
                object.put("orderId" , highOrder.getId());
                object.put("companyId" , highOrder.getCompanyId());
                object.put("createTime" , highOrder.getCreateTime());

                bsIntegralRebateService.integralRebate(object);

            }
        }
    }


}
