/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.bo.PayInfoBo;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.OrderDto;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.RedisUtil;
import com.yami.shop.dao.DeviceFeyMapper;
import com.yami.shop.delivery.comment.api.paotui.PaoTuiApi;
import com.yami.shop.delivery.comment.param.DeliveryOrderItemParam;
import com.yami.shop.delivery.comment.service.DeliveryOrderService;
import com.yami.shop.service.*;
import com.yami.shop.service.hb.IHBOrderService;
import com.yami.shop.service.impl.FeiEYunApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.JsonUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
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.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Component("orderTask")
public class OrderTask {


    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private PayService payService;
    @Autowired
    private OrderSettlementService orderSettlementService;
    @Autowired
    private PayManagerService payManagerService;
    @Autowired
    private IHBOrderService ihbOrderService;

    @Autowired
    RedissonClient redissonClient;
    private String lockKey = "cancel_timeout_orders_lock";

    public void cancelOrder() {
        Date now = new Date();
        RLock lock = redissonClient.getLock(lockKey);
        logger.info("取消超时未支付订单。。。");
        // 使用分布式锁或数据库行锁
        try {
            boolean locked = lock.tryLock(0, 30, TimeUnit.SECONDS);
            if (!locked) {
                logger.info("任务正在执行中，跳过本次执行");
                return;
            }
            // 获取15分钟之前未支付的订单

            List<Order> orders = orderService.selectCancelOrders(OrderStatus.UNPAY.value(), DateUtil.offsetMinute(now, -15));
            if (CollectionUtil.isEmpty(orders)) {
                return;
            }
            //TODO zx定时任务加回积分待完善
            orderService.cancelOrders(orders, "未按时支付");

            // 移除缓存
            this.removeCache(orders);

        } catch (Exception e) {
            // 释放锁
            Thread.currentThread().interrupt();
        }finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

    }

    /**
     * 确认收货
     */
    public void confirmOrder() {
        Date now = new Date();
        logger.info("系统自动确认收货订单。。。");
        // 获取10天之前等待确认收货的订单
        List<Order> orders = orderService.listUnRefundOrderAndOrderItems(OrderStatus.RECEIVED.value(), DateUtil.offsetDay(now, -10));
        if (CollectionUtil.isEmpty(orders)) {
            return;
        }
        orderService.receiptOrder(orders);

        //海博同步订单状态
        for (Order order : orders) {
            //海博订单完成
            ihbOrderService.changeOrderStatus(order.getOrderNumber(), OrderStatus.SUCCESS.value());
        }
        // 移除缓存
        this.removeCache(orders);
    }

//    public void createDistributionOrder(){
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date now = new Date();
//        logger.info("用户订单五分钟后未取消则创建物流订单。。。");
//        List<Order> orders = orderService.listUnRefundOrderAndOrderItems(OrderStatus.PADYED.value(),DateUtil.offsetMinute(now, -5));
//        if(CollectionUtil.isEmpty(orders)){
//            return;
//        }
////        List<Order> orders =orderService.list(new QueryWrapper<Order>().lambda().like(Order::getOrderNumber,"1879830276981526528"));
//        for (Order order:orders){
//            //创建物流订单
//            if (!Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value()) && Objects.equals(order.getDvyType(), DvyType.FETCH.value())){
//                System.out.println("订单不处于已付款状态，无法进行发货");
//                continue;
//            }else if (!Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value())){
//                System.out.println("订单不处于待发货状态，无法进行发货");
//                continue;
//            }
//            UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
//            if(ObjectUtil.isEmpty(userAddrOrder)){
//                System.out.println("该订单地址存在问题，请检查");
//                continue;
//            }
//            int count = orderRefundService.count(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getOrderId, order.getOrderId()));
//            if(count>0){
//                LambdaQueryWrapper<OrderRefund> orderRefundLambdaQueryWrapper = new LambdaQueryWrapper<>();
//                orderRefundLambdaQueryWrapper.eq(OrderRefund::getOrderId,order.getOrderId());
//                //发货时只有订单不存在退款或退款被拒绝才会创建仓储与物流订单
//                orderRefundLambdaQueryWrapper.and(wrapper->wrapper.eq(OrderRefund::getReturnMoneySts,-1).or().eq(OrderRefund::getReturnMoneySts,7).or().eq(OrderRefund::getReturnMoneySts,6));
//                List<OrderRefund> orderRefunds = orderRefundService.list(orderRefundLambdaQueryWrapper);
//                if (CollectionUtil.isEmpty(orderRefunds)) {
//                    System.out.println("该订单有退款信息正在处理或已退款中，无法进行发货操作");
//                    continue;
//                }
//            }
//            try {
//                boolean success = createQNHOrder(order);
//                if(!success){
//                    continue;
//                }
//            }catch (Exception e){
//                System.out.println(e.getMessage());
//                continue;
//            }
//
//            List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
//
//            //先创建物流订单
//            DeliveryOrderItemParam deliveryOrderItemParam = new DeliveryOrderItemParam();
//            deliveryOrderItemParam.setOrderNumber(order.getOrderNumber());
//            deliveryOrderItemParam.setDvyId(16l);
//            deliveryOrderItemParam.setDeliveryType(1);
//            deliveryOrderItemParam.setDvyFlowId("sdfsf");
//            deliveryOrderItemParam.setSelectOrderItems(orderItems);
//            for (OrderItem orderItem:deliveryOrderItemParam.getSelectOrderItems()){
//                orderItem.setChangeNum(orderItem.getProdCount());
//            }
//
//            try {
//                deliveryOrderService.saveDeliveriesInfo(deliveryOrderItemParam);
//                order=orderService.getById(order.getOrderId());
//                order.setDvyStatus(1);
//            }catch (Exception e){
//                System.out.println(e.getMessage());
//                order.setDvyStatus(0);
//            }
//            orderService.updateById(order);
//        }
////        this.removeCache(orders);
//    }

    /**
     * 查询订单，去除已支付的订单
     *
     * @param orders
     */
    private List<Order> chackOrders(List<Order> orders) {
        List<String> orderNumbers = orders.stream().map(Order::getOrderNumber).collect(Collectors.toList());
        // 收集未支付的订单
        List<Order> orderList = new ArrayList<>();
        //获取订单对应的订单结算数据
        List<OrderSettlement> orderSettlementList = orderSettlementService.list(new LambdaQueryWrapper<OrderSettlement>()
                .in(OrderSettlement::getOrderNumber, orderNumbers));
        Map<String, OrderSettlement> orderSettlementMap = orderSettlementList.stream()
                .collect(Collectors.toMap(OrderSettlement::getOrderNumber, orderSettlement -> orderSettlement));
        for (Order order : orders) {
            OrderSettlement orderSettlement = orderSettlementMap.get(order.getOrderNumber());
            if (Objects.isNull(orderSettlement) || Objects.isNull(orderSettlement.getPayType()) || Objects.isNull(orderSettlement.getPayNo())) {
                orderList.add(order);
                continue;
            }
            PayInfoBo payInfo = payManagerService.getPayInfo(PayType.instance(orderSettlement.getPayType()), orderSettlement.getPayNo());
            if (payInfo.getIsPaySuccess()) {
                // 根据内部订单号更新order settlement
                List<Order> successOrderList = payService.paySuccess(payInfo.getPayNo(), payInfo.getBizPayNo(), order.getPayType());
                // 移除缓存
                this.removeCache(successOrderList);
            } else {
                orderList.add(order);
            }
        }
        return orderList;
    }

    /**
     * 移除缓存
     */
    private void removeCache(List<Order> orders) {
        for (Order order : orders) {
            List<OrderItem> orderItems = order.getOrderItems();
            for (OrderItem orderItem : orderItems) {
                productService.removeProductCacheByProdId(orderItem.getProdId());
                skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
            }
        }
    }
//
//    /**
//     * 创建牵牛花订单
//     * @param order
//     * @return
//     */
//    public boolean createQNHOrder(Order order) {
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        // 待添加创建牵牛花订单
//        OrderDto orderDto = new OrderDto();
//        orderDto.setChannelSheetno(order.getOrderNumber());
//        orderDto.setChannelKeyword("YYG");
//        orderDto.setPayOver(true);
//        orderDto.setBilltype(1+"");
//        orderDto.setTotalSaleValue(BigDecimal.valueOf(order.getTotal()));
//        orderDto.setTotalDiscValue(BigDecimal.ZERO);
//        orderDto.setTotalSjDisc(BigDecimal.ZERO);
//        orderDto.setTotalSaleValue(BigDecimal.ZERO);
//        orderDto.setTotalPtDp(BigDecimal.ZERO);
//        orderDto.setTotalSjDp(BigDecimal.ZERO);
//        orderDto.setTotalPtDisc(BigDecimal.ZERO);
//        orderDto.setCommissionValue(BigDecimal.ZERO);
//        orderDto.setPayableValue(BigDecimal.valueOf(order.getTotal()));
//        orderDto.setTotalItemValue(BigDecimal.valueOf(order.getTotal()));
//        orderDto.setLogisticsModeKeyword(order.getFreightAmount().toString());
//
//
//        ShopDetail shopDetailByShopId = shopDetailService.getById(order.getShopId());
////            orderDto.setOrgName(shopDetailByShopId.getShopName());
//        orderDto.setOrgCode(shopDetailByShopId.getThirdPartyCode());
//        orderDto.setOrgName(shopDetailByShopId.getShopName());
//        orderDto.setPreOrder(false);
//        orderDto.setOfflineOrder(false);
//        orderDto.setOrderTime(formatter.format(order.getCreateTime()));
//        orderDto.setGroupId(0);
//        orderDto.setGoodsReturn("true");
//        UserAddrOrder addrOrder = userAddrOrderService.getById(order.getAddrOrderId());
//        User user = userService.getUserByUserId(order.getUserId());
//
//        //填充收件人信息
//        orderDto.setReceiver(new OrderDto.Receiver());
//        orderDto.getReceiver().setAddress(addrOrder.getAddress());
//        orderDto.getReceiver().setMobile(user.getUserMobile());
//        orderDto.getReceiver().setName(user.getNickName());
//        orderDto.getReceiver().setType("0");
//        orderDto.getReceiver().setLatitude(String.valueOf(addrOrder.getLatitude()));
//        orderDto.getReceiver().setLongitude(String.valueOf(addrOrder.getLongitude()));
//        orderDto.setPayableLogisticsValue(BigDecimal.valueOf(order.getPlatformAmount()));
//        orderDto.setLogisticsModeKeyword("0");
//
//        //填充买家信息
//        orderDto.setBuyer(new OrderDto.Buyer());
//        orderDto.getBuyer().setAddress(addrOrder.getAddress());
//        orderDto.getBuyer().setNick(user.getNickName());
//        orderDto.getBuyer().setEmail(user.getUserMail());
//        orderDto.getBuyer().setNote(order.getRemarks());
//        orderDto.getBuyer().setTel(user.getUserMobile());
//
//        //填充支付信息
//        orderDto.setOrderPayments(new OrderDto.OrderPayments());
//        orderDto.getOrderPayments().setPayment(BigDecimal.valueOf(order.getTotal()));
//        orderDto.getOrderPayments().setKeyword("10002");
//        orderDto.getOrderPayments().setName("商城系统支付");
//        ArrayList<OrderDto.OrderDetails> orderDetails = new ArrayList<>();
//        int weight = 0;
//        List<OrderItem> orderItems1 = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
//        for (OrderItem orderItem:orderItems1){
//            OrderDto.OrderDetails orderDetails1 = new OrderDto.OrderDetails();
//            Sku sku = skuService.getById(orderItem.getSkuId());
//            orderDetails1.setSkuId(sku.getPartyCode());
//            orderDetails1.setItemCode("");
//            orderDetails1.setBarcode("");
//            orderDetails1.setOrderItemId(orderItem.getOrderItemId().toString());
//            orderDetails1.setName(orderItem.getProdName());
//            orderDetails1.setOriginalPrice(BigDecimal.valueOf(sku.getOriPrice()));
//            orderDetails1.setWeight((int)Math.round(sku.getWeight()));
//            weight+=orderDetails1.getWeight();
//            orderDetails1.setSalePrice(BigDecimal.valueOf(sku.getPrice()));
//            orderDetails1.setQty(orderItem.getProdCount());
//            orderDetails1.setMoney(orderDetails1.getSalePrice().multiply(BigDecimal.valueOf(orderDetails1.getQty())));
//            orderDetails.add(orderDetails1);
//        }
//        orderDto.setOrderDetails(orderDetails);
//        orderDto.setWeight(weight);
//        String s = qnhService.addOrder(orderDto);
////        ResponseEntity responseEntity = qnhService.addOrder(orderDto);
//        if(!StringUtils.isBlank(s)){
//            order.setQnhOrderId(s);
//            order.setQnhOrderStatus("1");
//            orderService.updateById(order);
//            DeviceFey deviceFey = deviceFeyMapper.selectOne(Wrappers.<DeviceFey>lambdaQuery().eq(DeviceFey::getShopId, order.getShopId()).last("limit 1"));
//            FeiEYunApi.print(deviceFey.getDeviceSn(),print(order.getOrderNumber()));
//            return true;
//        }
//        return false;
//    }
//    private String print(String orderByOrderNumber){
//        Order order = orderService.getOrderByOrderNumber(orderByOrderNumber);
//        List<OrderItem> orderItemsByOrderNumber = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
//        String lastFourDigits = order.getOrderNumber().length() >= 4
//                ? order.getOrderNumber().substring(order.getOrderNumber().length() - 4)
//                : order.getOrderNumber(); // 如果长度不足4位，直接返回原字符串
//        UserAddrOrder userAddrOrder = userAddrOrderService.selectByAddrOrderId(order.getAddrOrderId());
//        String userMobile = userAddrOrder.getMobile().length() >= 4
//                ? userAddrOrder.getMobile().substring(userAddrOrder.getMobile().length() - 4)
//                : userAddrOrder.getMobile(); // 如果长度不足4位，直接返回原字符串
//        String receiverName = userAddrOrder.getReceiver();
//        String maskedName = receiverName.length() > 1
//                ? receiverName.substring(0, 1) + "*".repeat(receiverName.length() - 1)
//                : receiverName;
//        StringBuilder content = new StringBuilder();
//        content.append("<BR>");
//        content.append("<BR>");
//        content.append("<CB>#").append(lastFourDigits).append(" 海马购外卖</CB><BR>");
//        content.append("--------------------------------<BR>");
//        content.append("<BR>");
//        content.append("备注：").append(order.getRemarks()).append("<BR>");
//        content.append("<BR>");
//        content.append("--------------------------------<BR>");
//        content.append("下单时间：").append(DateUtil.date(order.getCreateTime())).append("<BR>");
//        content.append("<BR>");
//        content.append("订单编号：").append(order.getOrderNumber()).append("<BR>");
//        content.append("<BR>");
//        content.append("名称　　　　　 单价  数量 金额<BR>");
//        content.append("----------商品信息----------<BR>");
//        for (OrderItem orderItem:orderItemsByOrderNumber){
//            content.append("<BR>");
//            content.append(orderItem.getProdName()).append("<BR>").append("　　　　   　　 ").append(orderItem.getPrice()).append("    ").append(orderItem.getProdCount()).append("   ").append(orderItem.getActualTotal()).append("<BR>");
//        }
//        content.append("<BR>");
//        content.append("----------付款情况----------<BR>");
//        content.append("<BR>");
//        content.append("订单金额：").append(order.getTotal()).append("元<BR>");
//        content.append("<BR>");
//        content.append("实际支付：<B>").append(order.getActualTotal()).append("元</B><BR>");
//        content.append("--------------------------------<BR>");
//        content.append("<BR>");
//        content.append(maskedName);
//        content.append("<BR>");
//        content.append("顾客号码：手机尾号").append(userMobile).append("<BR>");
//        String add = userAddrOrder.getAddress() + userAddrOrder.getAddressName() + userAddrOrder.getAddrDetail();
//        content.append("顾客地址：").append(add).append("<BR>");
//        content.append("########海马购外卖#").append(lastFourDigits).append("########<BR>");
//        content.append("<BR>");
//        content.append("<BR>");
//        return content.toString();
//    }
}
