package com.hai.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;


import com.hai.common.utils.*;
import com.hai.config.*;

import com.hai.dao.OutRechargeOrderMapper;
import com.hai.dao.OutRechargeOrderMapperExt;
import com.hai.entity.*;
import com.hai.enum_type.*;
import com.hai.model.*;
import com.hai.order.service.OrderService;
import com.hai.order.topic.OrderTopic;
import com.hai.order.type.OrderChildStatus;
import com.hai.order.type.OrderPayType;
import com.hai.order.type.OrderRefundOpUserType;
import com.hai.order.utils.OrderUtil;
import com.hai.service.*;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;

import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

import java.text.SimpleDateFormat;
import java.util.*;


@Service("outRechargeOrderService")
public class OutRechargeOrderServiceImpl implements OutRechargeOrderService {

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

    @Resource
    private OutRechargeOrderMapper outRechargeOrderMapper;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private OutRechargeOrderMapperExt outRechargeOrderMapperExt;

    @Resource
    private OrderService orderService;

    @Resource
    private HighUserService highUserService;

    @Resource
    private OutRechargeOrderService outRechargeOrderService;

    @Resource
    private OutRechargePriceService outRechargePriceService;

    @Resource
    private HighDiscountUserRelService highDiscountUserRelService;

    @Resource
    private HighDiscountAgentCodeService highDiscountAgentCodeService;

    @Resource
    private OutRechargeChildOrderService outRechargeChildOrderService;


    @Resource
    private BsRechargeCodeService rechargeCodeService;

    @Resource
    private HighOrderService highOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OutRechargeChildOrderService childOrderService;

    @Resource
    private SecConfigService secConfigService;

    @Override
    public List<OutRechargeOrder> getListRechargeOrder(Map<String, Object> map) {
        OutRechargeOrderExample example = new OutRechargeOrderExample();
        OutRechargeOrderExample.Criteria criteria = example.createCriteria();

        if (MapUtils.getLong(map, "userId") != null) {
            criteria.andUserIdEqualTo(MapUtils.getLong(map, "userId"));
        }
        if (MapUtils.getLong(map, "companyId") != null) {
            criteria.andCompanyIdEqualTo(MapUtils.getLong(map, "companyId"));
        }
        if (MapUtils.getInteger(map, "payType") != null) {
            criteria.andPayTypeEqualTo(MapUtils.getInteger(map, "payType"));
        }
        if (MapUtils.getInteger(map, "laborUnionCard") != null) {
            criteria.andLaborUnionCardEqualTo(MapUtils.getString(map, "laborUnionCard"));
        }
        if (MapUtils.getInteger(map, "payStatus") != null) {
            criteria.andPayStatusEqualTo(MapUtils.getInteger(map, "payStatus"));
        }
        if (MapUtils.getInteger(map, "rechargeType") != null) {
            criteria.andRechargeTypeEqualTo(MapUtils.getInteger(map, "rechargeType"));
        }
        if (MapUtils.getString(map, "orderNo") != null) {
            criteria.andOrderNoLike("%" + MapUtils.getString(map, "orderNo") + "%");
        }
        if (MapUtils.getString(map, "userPhone") != null) {
            criteria.andUserPhoneEqualTo(MapUtils.getString(map, "userPhone"));
        }
        if (MapUtils.getString(map, "rechargeContent") != null) {
            criteria.andRechargeContentLike("%" + MapUtils.getString(map, "rechargeContent") + "%");
        }
        if (MapUtils.getInteger(map, "operatorType") != null) {
            criteria.andOperatorTypeEqualTo(MapUtils.getInteger(map, "operatorType"));
        }
        if (MapUtils.getString(map, "merchId") != null) {
            criteria.andMerchIdEqualTo(MapUtils.getString(map, "merchId"));
        }

        if (MapUtils.getInteger(map, "rechargeStatus") != null) {
            criteria.andRechargeStatusEqualTo(MapUtils.getInteger(map, "rechargeStatus"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "payTimeS")) && StringUtils.isNotBlank(MapUtils.getString(map, "payTimeE"))) {
            criteria.andPayTimeBetween(
                    DateUtil.format(MapUtils.getString(map, "payTimeS"), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.format(MapUtils.getString(map, "payTimeE"), "yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.isNotBlank(MapUtils.getString(map, "createTimeS")) && StringUtils.isNotBlank(MapUtils.getString(map, "createTimeE"))) {
            criteria.andCreateTimedBetween(
                    DateUtil.format(MapUtils.getString(map, "createTimeS"), "yyyy-MM-dd HH:mm:ss"),
                    DateUtil.format(MapUtils.getString(map, "createTimeE"), "yyyy-MM-dd HH:mm:ss"));
        }

        if (MapUtils.getBoolean(map , "whetherTimeOut") != null && MapUtils.getBoolean(map , "whetherTimeOut")) {
            // 获取当前时间
            Date date= new Date();
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            // 把日期往前减少三天,整数  往后推,负数往前移动
            calendar.add(Calendar.DATE, -3);
            // 这个时间就是日期往后推一天的结果
            date = calendar.getTime();
            criteria.andCreateTimedLessThan(date);
        }


        example.setOrderByClause("create_timed desc");
        return outRechargeOrderMapper.selectByExample(example);
    }

    @Override
    public OutRechargeOrder findByOrderId(Long orderId) {
        return outRechargeOrderMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public OutRechargeOrder findByOrderNo(String orderNo) {

        OutRechargeOrderExample example = new OutRechargeOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);

        List<OutRechargeOrder> list = outRechargeOrderMapper.selectByExample(example);

        if (list.size() == 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
        }

        OutRechargeOrder outRechargeOrder = list.get(0);

        // 充值子订单
        outRechargeOrder.setOutRechargeChildOrders(outRechargeChildOrderService.getListRechargeChildOrderByOrderId(outRechargeOrder.getId()));

        return outRechargeOrder;
    }

    @Override
    public OutRechargeOrder findByOrderNoNotChild(String orderNo) {

        OutRechargeOrderExample example = new OutRechargeOrderExample();
        example.createCriteria().andOrderNoEqualTo(orderNo);

        List<OutRechargeOrder> list = outRechargeOrderMapper.selectByExample(example);

        if (list.size() == 0) {
            return null;
        }

        return list.get(0);
    }

    @Override
    public void updateOrder(OutRechargeOrder outRechargeOrder) {
        outRechargeOrderMapper.updateByPrimaryKey(outRechargeOrder);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void cancelOrder(Long orderId) {
        OutRechargeOrder order = findByOrderId(orderId);
        if (order != null && order.getPayStatus() == 101) {
            // 101.待支付 102.已支付 100.已完成 104.已取消 105.已退款
            order.setPayStatus(104);
            order.setCancelTime(new Date());

            if (order.getMemDiscountId() != null) {
                HighDiscountUserRel rel = highDiscountUserRelService.getRelById(order.getMemDiscountId());
                if (rel != null) {
                    rel.setStatus(1);  // 状态  0:已过期  1：未使用  2：已使用
                    rel.setUseTime(null);
                    highDiscountUserRelService.updateDiscountUserRel(rel);

                    HighDiscountAgentCode code = highDiscountAgentCodeService.getCodeById(rel.getDiscountAgentCodeId());
                    code.setStatus(2);
                    highDiscountAgentCodeService.updateCode(code);
                }
            }

            if (order.getIntegralNum() != null) {
                // 积分返回
                String remark = "话费订单" + order.getOrderNo() + "取消，退还积分：" +  order.getIntegralNum().intValue();
                highUserService.goldHandle(order.getUserId(), order.getIntegralNum().intValue(), 1, 3, order.getId() , remark , order.getOrderNo());
            }

            updateOrder(order);
        }

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void finishOrder(Long orderId) {
        OutRechargeOrder order = findByOrderId(orderId);
        if (order != null) {
            order.setRechargeStatus(202); // 订单状态：1 待支付  2 已支付  3.已完成  4. 已取消  5.已退款
            order.setPayStatus(100); // 订单状态：1 待支付  2 已支付  3.已完成  4. 已取消  5.已退款
            order.setFinishTime(new Date());
            updateOrder(order);
        }
    }

    @Override
    public List<OutRechargeOrderModel> getOrderCount(Map<String, Object> map) throws Exception {


        if (MapUtils.getLong(map, "createTimeS") != null) {
            map.put("createTimeS", MapUtils.getString(map, "createTimeS"));
        }

        if (MapUtils.getLong(map, "createTimeE") != null) {
            map.put("createTimeE", MapUtils.getString(map, "createTimeE"));
        }

        if (MapUtils.getLong(map, "payTimeS") != null) {
            map.put("payTimeS", MapUtils.getString(map, "payTimeS"));
        }

        if (MapUtils.getLong(map, "payTimeE") != null) {
            map.put("payTimeE", MapUtils.getString(map, "payTimeE"));
        }

        return outRechargeOrderMapper.selectOrderCount(map);
    }


    @Override
    public List<OutOrderModel> getListOrderCount(Map<String, String> map) throws Exception {
        String finishTimeS = map.get("finishTimeS");
        String finishTimeE = map.get("finishTimeE");
        Integer status;
        if (StringUtils.isNotBlank(map.get("status"))) {
            status = Integer.valueOf(map.get("status"));
        } else {
            status = null;
        }
        String fTimeS;
        String fTimeE;
        if (StringUtils.isNotBlank(finishTimeS)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(Long.parseLong(finishTimeS)));
            //时
            calendar.set(Calendar.HOUR_OF_DAY, 00);
            //分
            calendar.set(Calendar.MINUTE, 00);
            //秒
            calendar.set(Calendar.SECOND, 00);
            fTimeS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

        } else {
            fTimeS = "2010-09-13 22:36:01";
        }
        if (StringUtils.isNotBlank(finishTimeE)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(Long.parseLong(finishTimeE)));
            //时
            calendar.set(Calendar.HOUR_OF_DAY, 00);
            //分
            calendar.set(Calendar.MINUTE, 00);
            //秒
            calendar.set(Calendar.SECOND, 00);
            fTimeE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        } else {
            fTimeE = DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss");
        }
        return outRechargeOrderMapperExt.getListOrderCount(fTimeS, fTimeE, status);
    }

    @Override
    public List<OutUserOrderModel> getUserCountList(Map<String, String> map) throws Exception {
        String finishTimeS = map.get("finishTimeS");
        String finishTimeE = map.get("finishTimeE");
        String fTimeS;
        String fTimeE;
        if (StringUtils.isNotBlank(finishTimeS)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(Long.parseLong(finishTimeS)));
            //时
            calendar.set(Calendar.HOUR_OF_DAY, 00);
            //分
            calendar.set(Calendar.MINUTE, 00);
            //秒
            calendar.set(Calendar.SECOND, 00);
            fTimeS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

        } else {
            fTimeS = "2010-09-13 22:36:01";
        }
        if (StringUtils.isNotBlank(finishTimeE)) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date(Long.parseLong(finishTimeE)));
            //时
            calendar.set(Calendar.HOUR_OF_DAY, 00);
            //分
            calendar.set(Calendar.MINUTE, 00);
            //秒
            calendar.set(Calendar.SECOND, 00);
            fTimeE = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
        } else {
            fTimeE = DateUtil.date2String(new Date(), "yyyy-MM-dd HH:mm:ss");
        }
        return outRechargeOrderMapperExt.getListUserCount(fTimeS, fTimeE);
    }

    @Override
    public OrderCountModel rechargeOrderByIndex(Integer code) {
        return outRechargeOrderMapper.rechargeOrderByIndex(code);
    }

    @Override
    public void rechargeOrderToRefund(Long orderId) throws Exception {

    }

    @Override
    @Transactional(
            propagation= Propagation.REQUIRES_NEW,
            isolation = Isolation.READ_COMMITTED,
            timeout = 25,
            rollbackFor = Exception.class)
    public void refundOrder(Long orderId) throws Exception {
        OutRechargeOrder outRechargeOrder = outRechargeOrderService.findByOrderId(orderId);

        log.info("发起话费订单退款" + outRechargeOrder.getOrderNo() + "");

        // 101.待支付 102.已支付 100.已完成 104.已取消 105.已退款
        if (outRechargeOrder.getPayStatus() != 102) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法退款，订单不处于已支付状态");
        }

        //  充值状态：201:充值中 202：充值成功 203：充值失败 204:未充值
        if (outRechargeOrder.getRechargeStatus() == 202) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法退款，订单已充值成功无法退款");
        }
        log.info("发起话费订单订单处理" + outRechargeOrder.getOrderNo() + "");
        // 订单处理
        HighOrder highOrder = highOrderService.getOrderByOrderNo(outRechargeOrder.getOrderNo());
        orderService.refundOrder(highOrder, "话费自动退款",OrderRefundOpUserType.TYPE1,
                null,
                "系统自动退款");

        // 话费充值业务订单处理
        outRechargeOrder.setPayStatus(105);
        outRechargeOrder.setRechargeStatus(203);
        outRechargeOrder.setRefundTime(new Date());
        outRechargeOrderService.updateOrder(outRechargeOrder);

    }



    @Override
    public void prepaidRechargeHandle(OutRechargeOrder outRechargeOrder){

        String key = "recharge_" + outRechargeOrder.getId();

        if (outRechargeOrderService.rechargeOrderAbnormal(outRechargeOrder)) {
            return;
        }

        try {

            // 分布式锁占坑
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(key, outRechargeOrder.getOrderNo());

            if(Boolean.TRUE.equals(lock)) {
                // 加锁成功，处理业务
                // 判断订单是否可以继续充值 1：满足继续充值条件 2：订单满足退款条件 3：订单不可以退款不可以继续充值 4:订单存在多个充值订单 5:订单充值完成 6：充值订单号未查询到任何充值记录
                int orderStatus = orderWhetherRecharge(outRechargeOrder);
                log.info("处理话费" + outRechargeOrder.getOrderNo() + "订单状态:" + orderStatus);
                if (orderStatus == 1) {
                    getPrepaidRechargeApi(outRechargeOrder);
                }
                if (orderStatus == 2) {
                    refundOrder(outRechargeOrder.getId());
                }
                if (orderStatus == 4) {
                    HighOrder highOrder = highOrderService.getOrderByOrderNo(outRechargeOrder.getOrderNo());
                    highOrder.setExceptionStatus(true);
                    highOrder.setExceptionContent("订单存在多个充值订单");
                    highOrderService.updateOrder(highOrder);
                }
                if (orderStatus == 6) {
                    HighOrder highOrder = highOrderService.getOrderByOrderNo(outRechargeOrder.getOrderNo());
                    highOrder.setExceptionStatus(true);
                    highOrder.setExceptionContent("充值订单号未查询到任何充值记录");
                    highOrderService.updateOrder(highOrder);
                }
                if (orderStatus == 5) {
                    completeOrder(outRechargeOrder.getId());
                }
            } else {
                // 加锁失败，重试
                Thread.sleep(100);
                prepaidRechargeHandle(outRechargeOrder);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除key，释放锁
            redisTemplate.delete(key);
        }


    }

//    @Override
//    public void getPrepaidRechargeApi(OutRechargeOrder outRechargeOrder) {
//
//        JSONObject object = new JSONObject();
//        object.put("rechargePrice" , outRechargeOrder.getRechargePrice());
//        object.put("rechargeMobile" , outRechargeOrder.getRechargeContent());
//        object.put("productId" , outRechargeOrder.getGoodsId());
//        object.put("parentOrderId" , outRechargeOrder.getId());
//
//        // 判断参数是否为空
//        if (
//                object.getBigDecimal("rechargePrice") == null ||
//                        object.getString("rechargeMobile") == null ||
//                        object.getInteger("productId") == null ||
//                        object.getLong("parentOrderId") == null
//        ) {
//            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
//        }
//
//        // 定义子订单对象
//        OutRechargeChildOrder childOrder = new OutRechargeChildOrder();
//
//        // 补充下单参数
//        object = prepaidRechargeOrderHandle(object);
//
//        // 补充子订单参数
//        childOrder.setParentOrderId(object.getLong("parentOrderId"));
//        childOrder.setRechargePlatform(object.getInteger("rechargePlatform"));
//        childOrder.setStatus(102);
//        childOrder.setOrderNo("CZ" + OrderUtil.generateOrderNo());
//        childOrder.setUpdateTime(new Date());
//        childOrder.setCreateTime(new Date());
//
//        outRechargeChildOrderService.insertOrder(childOrder);
//
//        // -1 取消，0充值中 ，1充值成功，2充值失败，3部分成功
//        Integer status = outRechargeOrderService.getRechargeOrderLegality(childOrder);
//
//        if (status == 2 || status == -1) {
//            // 补充下单参数
//            object = outRechargeOrderService.prepaidRechargeOrderHandle(object);
//
//            // 尖椒充值
//            if (object.getInteger("rechargePlatform") == 1) {
//                object.put("out_order_id", childOrder.getOrderNo());
//                object.put("amount", object.getBigDecimal("rechargePrice"));
//                object.put("mobile", object.getString("rechargeMobile"));
//                object.put("notifyUrl", CommonSysConst.getSysConfig().getJjNotifyUrl());
//                JSONObject returnObject = RechargeConfig.rechargeOrderByJj(object);
//                childOrder.setExt1(returnObject.toJSONString());
//            }
//
//            // 龙阅
//            if (object.getInteger("rechargePlatform") == 2) {
//
//                if (object.getString("code") == null) {
//                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
//                }
//
//                object.put("out_trade_num", childOrder.getOrderNo());
//                object.put("product_id", object.getString("code"));
//                object.put("mobile", object.getString("rechargeMobile"));
//                object.put("notifyUrl", CommonSysConst.getSysConfig().getLyNotifyUrl());
//                JSONObject returnObject = RechargeConfig.rechargeOrderByLy(object);
//                childOrder.setExt1(returnObject.toJSONString());
//            }
//
//            // 畅停充值
//            if (object.getInteger("rechargePlatform") == 4) {
//
//                if (object.getString("code") == null) {
//                    throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
//                }
//
//                object.put("orderid", childOrder.getOrderNo());
//                object.put("product_id", object.getString("code"));
//                object.put("phone", object.getString("rechargeMobile"));
//                object.put("price", object.getBigDecimal("rechargePrice"));
//                JSONObject returnObject = RechargeConfig.rechargeOrderByHg(object);
//                childOrder.setExt1(returnObject.toJSONString());
//            }
//
//
//            System.out.println("消费内容：" + childOrder);
//
//            childOrder.setUpdateTime(new Date());
//            outRechargeChildOrderService.updateOrder(childOrder);
//        }
//    }

    @Override
    public void getPrepaidRechargeApi(OutRechargeOrder outRechargeOrder) {

        if (rechargeOrderAbnormal(outRechargeOrder)) {
            return;
        }

        JSONObject object = new JSONObject();
        object.put("rechargePrice" , outRechargeOrder.getRechargePrice());
        object.put("rechargeMobile" , outRechargeOrder.getRechargeContent());
        object.put("productId" , outRechargeOrder.getGoodsId());
        object.put("parentOrderId" , outRechargeOrder.getId());

        // 判断参数是否为空
        if (
                object.getBigDecimal("rechargePrice") == null ||
                        object.getString("rechargeMobile") == null ||
                        object.getInteger("productId") == null ||
                        object.getLong("parentOrderId") == null
        ) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        }

        // 定义子订单对象
        OutRechargeChildOrder childOrder = new OutRechargeChildOrder();

        // 补充下单参数
        object = prepaidRechargeOrderHandle(object);

        // 补充子订单参数
        childOrder.setParentOrderId(object.getLong("parentOrderId"));
        childOrder.setRechargePlatform(object.getInteger("rechargePlatform"));
        childOrder.setStatus(102);
        childOrder.setOrderNo("CZ" + OrderUtil.generateOrderNo());
        childOrder.setUpdateTime(new Date());
        childOrder.setCreateTime(new Date());
        outRechargeChildOrderService.insertOrder(childOrder);
        // 尖椒充值
        if (object.getInteger("rechargePlatform") == 1) {
            object.put("out_order_id", childOrder.getOrderNo());
            object.put("amount", object.getBigDecimal("rechargePrice"));
            object.put("mobile", object.getString("rechargeMobile"));
            object.put("notifyUrl", CommonSysConst.getSysConfig().getJjNotifyUrl());
            JSONObject returnObject = RechargeConfig.rechargeOrderByJj(object);
            childOrder.setRechargePlatform(1);
            childOrder.setExt1("尖椒" + returnObject.toJSONString());
            childOrder.setExt2(object.toJSONString());
        }

        // 龙阅
        if (object.getInteger("rechargePlatform") == 2) {

            if (object.getString("code") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            object.put("out_trade_num", childOrder.getOrderNo());
            object.put("product_id", object.getString("code"));
            object.put("mobile", object.getString("rechargeMobile"));
            object.put("notifyUrl", CommonSysConst.getSysConfig().getLyNotifyUrl());
            JSONObject returnObject = RechargeConfig.rechargeOrderByLy(object);
            childOrder.setRechargePlatform(2);
            childOrder.setExt1("龙阅充值" + returnObject.toJSONString());
            childOrder.setExt2("龙阅请求参数" + object.toJSONString());
            childOrder.setExt3("龙阅充值" + returnObject.toJSONString());

        }

        // 畅停充值
        if (object.getInteger("rechargePlatform") == 4) {

            if (object.getString("code") == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            object.put("orderid", childOrder.getOrderNo());
            object.put("product_id", object.getString("code"));
            object.put("phone", object.getString("rechargeMobile"));
            object.put("price", object.getBigDecimal("rechargePrice"));
            JSONObject returnObject = RechargeConfig.rechargeOrderByHg(object);
            childOrder.setRechargePlatform(4);
            childOrder.setExt1("畅停充值" + returnObject.toJSONString());
            childOrder.setExt2("畅停请求参数" + object.toJSONString());
            childOrder.setExt3("畅停充值" + returnObject.toJSONString());
        }
        childOrder.setUpdateTime(new Date());
        outRechargeChildOrderService.updateOrder(childOrder);
    }

    @Override
    public void completeOrder(Long orderId) {

        OutRechargeChildOrder childOrder = outRechargeChildOrderService.findByOrderId(orderId);
        // 查询充值订单
        OutRechargeOrder order = outRechargeOrderService.findByOrderId(childOrder.getParentOrderId());

        // 修改话费充值业务订单状态
        childOrder.setStatus(101);
        order.setRechargeStatus(202);
        order.setPayStatus(100);
        order.setFinishTime(new Date());
        outRechargeOrderService.updateOrder(order);
        outRechargeChildOrderService.updateOrder(childOrder);

        // 修改订单状态
        HighOrder highOrder = highOrderService.getOrderByOrderNo(order.getOrderNo());
        if (highOrder != null) {
            highOrder.setOrderStatus(OrderStatusEnum.type3.getType());
            highOrder.setFinishTime(new Date());
            highOrder.setExceptionStatus(false);
            highOrder.setExceptionContent(null);
            for (HighChildOrder highChildOrder : highOrder.getHighChildOrderList()) {
                highChildOrder.setChildOrderStatus(OrderChildStatus.STATUS3.getNumber());
                highChildOrder.setFinishTime(new Date());
            }
            orderService.updateOrderData(highOrder);
        }


        // 推送小程序消息
        new Thread(() -> {
            HighUser highUser = highUserService.findByUserId(highOrder.getMemId());
            WxMsgConfig.rechargedSuccess(
                    order.getRechargeContent() + "充值成功",
                    String.valueOf(order.getPayRealPrice()),
                    order.getOrderNo(),
                    order.getFinishTime(),
                    OrderPayType.getDataByType(order.getPayType()).getName(),
                    highUser.getOpenId());
        }).start();

    }


    @Override
    public void editOutRechargeOrder(HighOrder orderData , OutRechargeOrder outRechargeOrder) {

        // 201:充值中 202：充值成功 203：充值失败 204：未充值
        outRechargeOrder.setRechargeStatus(201);
        // 101.待支付 102.已支付 100.已完成 104.已取消 105.已退款
        outRechargeOrder.setPayStatus(102);
        outRechargeOrder.setMemDiscountId(orderData.getMemDiscountId());
        outRechargeOrder.setMemDiscountName(orderData.getMemDiscountName());
        outRechargeOrder.setPayType(orderData.getPayType());
        outRechargeOrder.setLaborUnionCard(orderData.getMemCardNo());
        outRechargeOrder.setDiscountDeductionPrice(orderData.getDeductionCouponPrice());
        outRechargeOrder.setIntegralDeductionPrice( new BigDecimal(orderData.getPayGold().toString()).divide(new BigDecimal(100)));
        outRechargeOrder.setIntegralNum(new BigDecimal(orderData.getPayGold()));
        outRechargeOrder.setPayPrice(orderData.getPayPrice());
        outRechargeOrder.setPayRealPrice(orderData.getPayRealPrice());
        outRechargeOrderService.updateOrder(outRechargeOrder);
    }
    @Override
    public List<ApiRechargePhoneModel> getApiRechargePhoneByList(Map<String, Object> map) {
        return outRechargeOrderMapper.getApiRechargePhoneByList(map);
    }

    @Override
    public Integer getRechargeOrderLegality(OutRechargeChildOrder childOrder)  {

        try {

            JSONObject object = new JSONObject();

            Integer status = 99;

            // 龙阅
            if (childOrder.getRechargePlatform() == 2) {

                object.put("out_trade_nums" , childOrder.getOrderNo());

                JSONObject jsonObject = RechargeConfig.checkOrderByLy(object);
                childOrder.setExt3("龙阅查询"+ jsonObject);

                JSONArray objectJSONArray = jsonObject.getJSONArray("data");

                JSONObject objectData = new JSONObject();
                for (Object objects : objectJSONArray) {
                    objectData =  (JSONObject) objects;
                }
                if (objectData.size() > 0) {
                    // -1取消，0充值中 ，1充值成功，2充值失败，3部分成功
                    status =  objectData.getInteger("state");
                }

            }
            // 畅停
            if (childOrder.getRechargePlatform() == 4) {
                object.put("orderid" , childOrder.getOrderNo());

                JSONObject jsonObject = RechargeConfig.checkOrderByHg(object);
                childOrder.setExt3("畅停查询"+ jsonObject);
                if (jsonObject.getJSONArray("data") != null) {
                    JSONArray objectJSONArray = jsonObject.getJSONArray("data");

                    JSONObject objectData;
                    for (Object objects : objectJSONArray) {
                        objectData =  (JSONObject) objects;
                        // 0充值中，1成功，2失败，3已取消，4部分充值，5缓存订单
                        // -1取消，0充值中 ，1充值成功，2充值失败，3部分成功
                        if (objectData.getInteger("status") == 0 || objectData.getInteger("status") == 5) {
                            status = 0;
                        } else if (objectData.getInteger("status") == 1) {
                            status =  1;
                        } else if (objectData.getInteger("status") == 2) {
                            status = 2;
                        } else if (objectData.getInteger("status") == 3) {
                            status = -1;
                        } else if (objectData.getInteger("status") == 4) {
                            status = 3;
                        }

                    }
                }
            }

            if (status == 1) {
                childOrder.setStatus(101);
            }
            if (status == 2 || status == -1) {
                childOrder.setStatus(103);
            }
            if (status == 99 ) {
                childOrder.setStatus(104);
            }

            childOrder.setUpdateTime(new Date());
            outRechargeChildOrderService.updateOrder(childOrder);
            return status;
        }catch (Exception e) {
            return 99;
        }


    }

    // 获取当前最新的充值平台
    private Integer getRechargePlatformType() {
        OutRechargeChildOrder outRechargeChildOrder = outRechargeChildOrderService.findOutRechargeChildOrderByDesc();

        if (outRechargeChildOrder != null) {
            return outRechargeChildOrder.getRechargePlatform();
        }
        return  null;
    }

    /**
     * @Author Sum1Dream
     * @Name prepaidRechargeOrderHandle
     * @Description // 充值订单下单数据操作
     * @Date 18:54 2023/3/28
     * @Param [object]
     * @Return com.alibaba.fastjson.JSONObject
     */

    @Override
    public JSONObject prepaidRechargeOrderHandle(JSONObject object) {

        if (object.getLong("productId") == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "产品编码为空");
        }

        // 查询充值产品
        OutRechargePrice outRechargePrice = outRechargePriceService.findByGoodsId(object.getLong("productId"));

        if (outRechargePrice == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知产品编码");
        }

        // 初始化充值平台 1:尖椒 2：龙阅 3：城宇 4.畅停
        Integer platformType = getRechargePlatformType();

        // 截取可平台字符串
        String rechargePlatformString = outRechargePrice.getRechargePlatform().substring(1,outRechargePrice.getRechargePlatform().length()-1);
        String[] rechargePlatform = rechargePlatformString.split("-");

        if (rechargePlatform.length == 1) {
            platformType = Integer.parseInt(rechargePlatformString);
        }
        if (rechargePlatform.length > 1) {
            // 如果平台充值记录暂无 则充值第一个
            if (platformType == null) {
                platformType = Integer.parseInt(rechargePlatform[0]);
            } else {
                // 获取上一条充值平台的下一个平台内容
                platformType = Integer.parseInt(rechargePlatform[ArrayUtils.arrayIndex(rechargePlatform , String.valueOf(platformType))]);
            }
        }

        Map<String , Object> rechargeCodeMap = new HashMap<>();

        rechargeCodeMap.put("sourceId" , outRechargePrice.getId());
        rechargeCodeMap.put("rechargePlatform" , platformType);
        BsRechargeCode rechargeCode = rechargeCodeService.findByMap(rechargeCodeMap);

        object.put("code" , rechargeCode.getGoodsId());
        object.put("rechargePlatform" , platformType);

        return object;

    }

    @Override
    public Integer orderWhetherRecharge(OutRechargeOrder rechargeOrder) {

        // 查询子订单
        List<OutRechargeChildOrder> childOrderList = outRechargeChildOrderService.getListRechargeChildOrderByOrderId(rechargeOrder.getId());

        if (childOrderList.size() == 0) {
            return 6;
        }

        // 充值订单充值时间
        Date rechargeTime = rechargeOrder.getCreateTimed();
        Date currentTime = new Date();
        int hours = (int) ((currentTime.getTime() - rechargeTime.getTime()) / (1000 * 60 * 60));

        // 判断订单是否存在充值完成订单
        Map<String , Object> childMap = new HashMap<>();
        childMap.put("parent_order_id", rechargeOrder.getId());
        childMap.put("status", 101);
        List<OutRechargeChildOrder> childOrders101 = outRechargeChildOrderService.getListRechargeChildOrder(childMap);

        // 判断充值成功是否存在多个 存在返回异常
        if (childOrders101.size() > 1) {
            return 4;
        }
        // 判断是否存在充值成功的订单
        if (childOrders101.size() == 1) {
            return 5;
        }

        // 查询充值中的订单
        childMap.put("status", 102);
        List<OutRechargeChildOrder> childOrders102 = outRechargeChildOrderService.getListRechargeChildOrder(childMap);


        // 充值中的订单存在多个 返回异常
        if (childOrders102.size() > 1) {
            return 4;
        }
        // 只存在一个充值中的订单需要查询当前充值中的订单状态
        if (childOrders102.size() == 1) {

            // -1 取消，0充值中 ，1充值成功，2充值失败，3部分成功
            Integer status = getRechargeOrderLegality(childOrders102.get(0));
            if (status == 2 || status == -1) {
                // 修改充值订单状态
                rechargeChildOrderHandle(childOrders102.get(0) , 103);
                // 如果订单记录超过2条退款 反之继续充值
                if (childOrderList.size() > 1) {
                    return 2;
                } else {
                    // 如果订单记录超过71小时 反之继续充值
                    return hours > 71 ? 2 : 1;
                }
            }
            if (status == 99) {
                return 6;
            }
            // 充值订单为充值成功
            if (status == 1) {
                // 修改充值订单状态
                rechargeChildOrderHandle(childOrders102.get(0) , 101);
                return 5;
            }

        }

        // 没有充值中的订单 查询所有订单中最新的一条订单状态
        if (childOrders102.size() == 0) {
            if (childOrderList.size() > 0) {
                // -1 取消，0充值中 ，1充值成功，2充值失败，3部分成功
                Integer status = getRechargeOrderLegality(childOrderList.get(0));
                if (status == 2 || status == -1) {
                    // 修改充值订单状态
                    rechargeChildOrderHandle(childOrderList.get(0) , 103);
                    // 如果订单记录超过2条退款 反之继续充值
                    if (childOrderList.size() > 1) {
                        return 2;
                    } else {
                        // 如果订单记录超过71小时 反之继续充值
                        return hours > 71 ? 2 : 1;
                    }

                }
                if (status == 99) {
                    return 6;
                }
                if (status == 1) {
                    // 修改充值订单状态
                    rechargeChildOrderHandle(childOrderList.get(0) , 101);
                    return 5;
                }
            }
        }
        return 3;
    }

    /**
     * @Author Sum1Dream
     * @Name rechargeChildOrderHandle
     * @Description // 处理子订单
     * @Date 18:50 2023/3/28
     * @Param [rechargeChildOrder]
     * @Return void
     */
    private void rechargeChildOrderHandle(OutRechargeChildOrder rechargeChildOrder , Integer status) {
        rechargeChildOrder.setUpdateTime(new Date());
        rechargeChildOrder.setStatus(status);
        outRechargeChildOrderService.updateOrder(rechargeChildOrder);
    }

    @Override
    public OutRechargeChildOrder mobileChildOrderHandle(HighOrder highOrder, OutRechargeOrder outRechargeOrder) {
        // 组装查询子订单数据
        Map<String , Object> childOrderMap101 = new HashMap<>();
        childOrderMap101.put("parent_order_id", outRechargeOrder.getId());
        childOrderMap101.put("status", "101,102");
        // 查询充值订单
        List<OutRechargeChildOrder> childOrders = childOrderService.getListRechargeChildOrder(childOrderMap101);

        OutRechargeChildOrder childOrder;

        // 判读是否存在多个充值中的订单
        if (childOrders.size() > 0) {
            childOrder = childOrders.get(0);
            if (childOrders.size() > 1) {
                childOrder.setExt1("当前订单存在多个充值订单");
            }

        } else {
            childOrder = childOrderService.findByOrderId(outRechargeOrder.getId());
            if (childOrder != null && highOrder != null && childOrder.getStatus() != null && highOrder.getOrderStatus() != null) {
                if (highOrder.getOrderStatus() == 2 && childOrder.getStatus() != 102) {
                    childOrder.setExt1("主订单充值中，但是充值订单状态不为充值中");
                }
                if (highOrder.getOrderStatus() == 3 && childOrder.getStatus() != 101) {
                    childOrder.setExt1("主订单充值成功，但是充值订单状态不为充值成功");
                }
                if (highOrder.getOrderStatus() == 4 && !(childOrder.getStatus() == 103 || childOrder.getStatus() == 104)) {
                    childOrder.setExt1("主订单退款，但是充值订单状态不为退款");
                }
            }

        }

        return childOrder;
    }


    @Override
    public boolean rechargeOrderAbnormal(OutRechargeOrder order) {

        HighOrder highOrder = highOrderService.getOrderByOrderNo(order.getOrderNo());


        if (secConfigService.isConfig("RECHARGE_ORDER" , order.getRechargeContent())) {
            highOrder.setExceptionStatus(true);
            highOrder.setExceptionContent("当前订单存在以前多充值！");
            order.setRechargeStatus(204);
            orderService.updateOrderData(highOrder);
            outRechargeOrderMapper.updateByPrimaryKey(order);
            return true;
        }
        if (highOrder.getPayType() == 4) {

            if (secConfigService.isConfig("RECHARGE_ORDER" , order.getLaborUnionCard())) {
                highOrder.setExceptionStatus(true);
                highOrder.setExceptionContent("当前订单存在以前多充值！");
                order.setRechargeStatus(204);
                orderService.updateOrderData(highOrder);
                outRechargeOrderMapper.updateByPrimaryKey(order);
                return true;
            }
        }

        return false;
    }
}
