package com.yami.shop.service.hb.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.dto.hb.*;
import com.yami.shop.bean.enums.*;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.OrderRefundParam;
import com.yami.shop.bean.vo.OrderRefundSkuVo;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.CommonUtils;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.*;
import com.yami.shop.service.*;
import com.yami.shop.service.hb.IHBOrderService;
import com.yami.shop.utils.CullenUtils;
import com.yami.shop.utils.HBSignUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.validation.Valid;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

import static com.yami.shop.common.util.HttpUtil.post;


/**
 * 商品信息管理实现
 *
 * @author fubojin
 * @version 1.0.0
 * @since 2025-09-5
 */
@Slf4j
@Service
@AllArgsConstructor
public class HBOrderService implements IHBOrderService {
    private final HBSignUtil hbSignUtil;
    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final ShopDetailMapper shopDetailMapper;
    private final UserService userService;
    private final UserAddrOrderService userAddrOrderService;
    private final ProductMapper productMapper;
    private final SkuMapper skuMapper;
    private final OrderRiderLocationMapper orderRiderLocationMapper;
    private final OrderRefundService orderRefundService;
    private final OrderService orderService;
    private final OrderRefundSkuMapper orderRefundSkuMapper;


    public HBR addHBGoods(JSONObject hbRequest) {
        try {
            String bodyStr = hbRequest.getString("body");
            log.info("订单信息，body：{}", bodyStr);
            JSONObject bodyJson = JSON.parseObject(bodyStr);
            JSONArray productList = bodyJson.getJSONArray("productList");
            List<Product> spuList = new ArrayList<>();
            List<Sku> skuList = new ArrayList<>();

            for (Object product : productList) {
                JSONObject jsonObject = JSON.parseObject(product.toString());
                String outSkuId = jsonObject.getString("outSkuId");
                String goodsInfoStr = selectHBGoodsInfo(outSkuId);
                JSONObject goodsInfoJson = JSON.parseObject(goodsInfoStr);

                // 2. 逐层解析获取productHostInfoDTOS数组
                JSONObject result = goodsInfoJson.getJSONObject("result");
                JSONObject innerResult = result.getJSONObject("result");
                JSONArray productHostInfoDTOS = innerResult.getJSONArray("productHostInfoDTOS");


                // 3. 遍历获取每个商品信息
                for (int i = 0; i < productHostInfoDTOS.size(); i++) {
                    JSONObject productInfo = productHostInfoDTOS.getJSONObject(i);

                }
            }
            // 这里可以保存到数据库
            // ProductService.saveBatch(spuList);
            // SkuService.saveBatch(skuList);

            return HBR.success("商品信息处理成功，共处理 " + spuList.size() + " 个SPU和SKU");

        } catch (Exception e) {
            log.error("处理商品信息失败：{}", e.getMessage(), e);
            return HBR.error("处理商品信息失败: " + e.getMessage());
        }
    }

    public String selectHBGoodsInfo(String outSkuId) {

        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        JSONObject skuItem = new JSONObject();
//        skuItem.put("skuId", "1328633");      // 海博商品编码
        skuItem.put("outSkuId", outSkuId);    // 商家商品编码
        // 2. 创建商品列表并添加SKU对象
        List<JSONObject> productList = new ArrayList<>();
        productList.add(skuItem);
        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("productList", productList);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 订单查询请求参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/product/getSku", build);
        log.info("post 订单查询结果：{}", post);
        return post;
    }

    @Override
    public String createOrderAsync(String channelOrderId) {

        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("channelOrderId", channelOrderId);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 创建订单推送单号参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/order/createOrderAsync", build);
        log.info("post 创建订单推送结果：{}", post);
        return post;
    }

    @Override
    public String changeOrderStatus(String channelOrderId, Integer type) {
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("channelOrderId", channelOrderId);
        requestBody.put("operator", "admin");
        // 订单操作时间戳毫秒数
        requestBody.put("operatorTime", System.currentTimeMillis());
        //操作类型 （20：订单已接单 30：订单待配送 60：订单已取消 80：订单已完成）
        requestBody.put("operatorType", type);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 订单推送单号参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/order/changeOrderStatus", build);
        log.info("post 订单推送结果：{}", post);
        return post;
    }

    @Override
    public HBR createOrderResult(JSONObject hBRequest) {
        log.info("海博订单创建完成结果通知请求参数{}", hBRequest);
        JSONObject body = hBRequest.getJSONObject("body");
        String code = body.getString("code");
        if (!"0".equals(code)) {
            log.error("海博订单创建失败：{}", body.getString("message"));
        }
        return HBR.success();
    }

    @Override
    public void orderStatusNotify(JSONObject hBRequest) {
        log.info("海博订单状态变更通知请求参数{}", hBRequest);
        String bodyStr = hBRequest.getString("body");
        log.info("订单信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Integer operatorType = bodyJson.getInteger("operatorType");
        String channelOrderId = bodyJson.getString("channelOrderId");
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(channelOrderId);
        //如果是已送达直接完成并且通知海博
        order.setHbOrderStatus(operatorType);
        if (operatorType == 70 && order.getDvyType() == 3) {
            order.setHbOrderStatus(80);
        }
        orderMapper.updateById(order);


        //取消订单
        if (operatorType == 60) {
            log.info("取消订单{}", channelOrderId);
            changeOrderStatus(channelOrderId, 60);
            //创建退款单
            OrderRefundParam orderRefundParam = new OrderRefundParam();
            orderRefundParam.setOrderNumber(order.getOrderNumber());
            orderRefundParam.setApplyType(1);
            orderRefundParam.setRefundType(1);
            orderRefundParam.setIsReceiver(false);
            orderRefundParam.setBuyerReason("17");
            orderRefundParam.setBuyerDesc(bodyJson.getString("reason"));
            orderRefundParam.setBuyerMobile(order.getUserMobile());
            orderRefundParam.setGoodsNum(order.getProductNums());
            orderRefundParam.setRefundAmount(order.getActualTotal());
            orderRefundParam.setPhotoFiles("");

            List<OrderItem> listByOrderNumber = orderItemMapper.getListByOrderNumber(order.getOrderNumber());
            List<OrderRefundSku> orderRefundSkuList = new ArrayList<>();
            for (OrderItem orderItem : listByOrderNumber) {

                // 查询该订单项的所有退款记录
                List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                        .eq(OrderRefund::getOrderNumber, orderRefundParam.getOrderNumber())
                        .eq(OrderRefund::getReturnMoneySts, 70)
                        .eq(OrderRefund::getOrderItemId, orderItem.getOrderItemId()));

                if (ObjectUtil.isNotEmpty(orderRefundList)) {
                    // 计算该订单项已退款的总数量(通过退款单查询退款商品)
                    List<OrderRefundSkuVo> orderRefundSkuVos = orderRefundSkuMapper.selectByRefundId(orderItem.getOrderItemId());
                    Integer totalRefundedCount = orderRefundSkuVos.stream()
                            .mapToInt(OrderRefundSkuVo::getProductCount)
                            .sum();

                    // 计算剩余可退款数量
                    Integer remainingCount = orderItem.getProdCount() - totalRefundedCount;

                    if (remainingCount > 0) {
                        // 数量不同，添加剩余数量
                        OrderRefundSku orderRefundSku = new OrderRefundSku();
                        orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                        orderRefundSku.setSkuId(orderItem.getSkuId());
                        orderRefundSku.setProductCount(remainingCount); // 设置剩余数量
                        orderRefundSku.setSkuPrice(orderItem.getPrice());
                        orderRefundSkuList.add(orderRefundSku);
                    }
                    // 如果remainingCount <= 0，说明已全部退款，不添加到列表
                } else {
                    // 没有退款记录，正常添加全部数量
                    OrderRefundSku orderRefundSku = new OrderRefundSku();
                    orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                    orderRefundSku.setSkuId(orderItem.getSkuId());
                    orderRefundSku.setProductCount(orderItem.getProdCount());
                    orderRefundSku.setSkuPrice(orderItem.getPrice());
                    orderRefundSkuList.add(orderRefundSku);
                }
            }
            if (ObjectUtil.isEmpty(orderRefundSkuList)){
                return;
            }
            orderRefundParam.setOrderRefundSkuList(orderRefundSkuList);

            OrderRefund orderRefund1 = orderRefundService.getOne(new LambdaQueryWrapper<OrderRefund>()
                    .eq(OrderRefund::getOrderNumber, orderRefundParam.getOrderNumber())
                    .notIn(OrderRefund::getReturnMoneySts, Arrays.asList(30, 40, 70)));
            log.info(" 申请系统退款未处理数据参数:{}", JSONObject.toJSONString(orderRefund1));
            if (ObjectUtil.isNotEmpty(orderRefund1)) {
                orderRefund1.setReturnMoneySts(ReturnMoneyStsType.REJECT.value());
                orderRefundService.updateById(orderRefund1);
                //退款单状态同步驳回
                orderRefundService.changeStatus(orderRefund1.getRefundSn(), ReturnMoneyStsType.REJECT.value());

                //生成流程记录
                orderRefundService.addOrderRefundRecord( orderRefund1.getRefundId(), 20, 10,"驳回单个商家整单处理");
            }
            OrderRefund orderRefund = orderService.applyAgain(orderRefundParam, ReturnMoneyStsType.SUCCESS.value());
            orderRefundService.createRefundOrder(order.getOrderNumber(), orderRefund.getRefundSn());


        }
        //成功直接通知海博
        if (order.getHbOrderStatus() == 80) {
            changeOrderStatus(channelOrderId, OrderStatus.SUCCESS.value());
        }
    }

    @Override
    public void updateLogisticStatus(JSONObject hBRequest) {
        log.info("海博订单更新通知请求参数{}", hBRequest);
        JSONObject body = hBRequest.getJSONObject("body");
        String channelOrderId = body.getString("channelOrderId");
        Long changeTime = body.getLong("changeTime");
        Integer logisticStatus = body.getInteger("logisticStatus");
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(channelOrderId);
        order.setHbLogisticStatus(logisticStatus);
        order.setDvyFlowId(body.getString("carrierNo"));
        order.setUpdateTime(new Date(changeTime));
        orderMapper.updateById(order);
    }

    @Override
    public void riderLocation(JSONObject hBRequest) {
        String bodyStr = hBRequest.getString("body");
        log.info("订单信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        String channelOrderId = bodyJson.getString("channelOrderId");
        OrderRiderLocation orderRiderLocation = new OrderRiderLocation();
        orderRiderLocation.setOrderNumber(channelOrderId);
        orderRiderLocation.setCourierName(bodyJson.getString("courierName"));
        orderRiderLocation.setCourierPhone(bodyJson.getString("courierPhone"));
        orderRiderLocation.setLatitude(bodyJson.getDouble("latitude"));
        orderRiderLocation.setLongitude(bodyJson.getDouble("longitude"));
        orderRiderLocation.setPushTime(bodyJson.getLong("pushTime"));
        orderRiderLocation.setUpdateTime(new Date());

        OrderRiderLocation orderRiderLocation1 = orderRiderLocationMapper.selectOne(new LambdaQueryWrapper<OrderRiderLocation>().eq(OrderRiderLocation::getOrderNumber, channelOrderId));
        if (orderRiderLocation1 != null) {
            orderRiderLocation.setId(orderRiderLocation1.getId());
            orderRiderLocationMapper.updateById(orderRiderLocation);
        } else {
            orderRiderLocation.setCreateTime(new Date());
            orderRiderLocationMapper.insert(orderRiderLocation);
        }
    }

    @Override
    public void deliveryMsg(JSONObject hBRequest) {
        String bodyStr = hBRequest.getString("body");
        log.info("订单-发货消息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(bodyJson.getString("channelOrderId"));

    }


    @Override
    public HBR details(JSONObject hbRequest) {
        String bodyStr = hbRequest.getString("body");
        log.info("订单信息，body：{}", bodyStr);
        JSONObject bodyJson = JSON.parseObject(bodyStr);
        Order order = orderMapper.getOrderAndOrderItemByOrderNumber(bodyJson.getString("channelOrderId"));

        if (order == null) {
            log.error("系统订单信息查询不到，单号：{}", bodyJson.getString("channelOrderId"));
            return HBR.error("系统订单信息查询不到，单号：" + bodyJson.getString("channelOrderId"));
        }

        CreateOrderRequest createOrderRequest = new CreateOrderRequest();
        createOrderRequest.setChannelOrderId(order.getOrderNumber());
        createOrderRequest.setViewOrderId(order.getOrderNumber());
        createOrderRequest.setOrderStatus(20);
//      createOrderRequest.setDaySeq(Order.getDaySeq());门店流水号

        ShopDetail shopDetail = shopDetailMapper.selectById(order.getShopId());
        createOrderRequest.setOutStationNo(shopDetail.getOutStationNo());
        createOrderRequest.setOutStationName(shopDetail.getShopName());

        User userByUserId = userService.getUserByUserId(order.getUserId());
        createOrderRequest.setCaution(userByUserId.getUserMobile() + "*" + order.getRemarks());

        UserAddrOrder userAddrOrder = userAddrOrderService.selectByAddrOrderId(order.getAddrOrderId());
        if (userAddrOrder == null) {
            log.error("收货地址信息查询不到，单号：{}", bodyJson.getString("Order"));
            createOrderRequest.setRecipientName(shopDetail.getMobile());
            createOrderRequest.setRecipientPhone(shopDetail.getMobile());
            createOrderRequest.setRecipientLatitude(Double.parseDouble(shopDetail.getShopLat()));
            createOrderRequest.setRecipientLongitude(Double.parseDouble(shopDetail.getShopLng()));
            createOrderRequest.setRecipientAddress(shopDetail.getShopAddress());
        } else {
            createOrderRequest.setRecipientName(userAddrOrder.getReceiver());
            createOrderRequest.setRecipientPhone(userAddrOrder.getMobile());
            createOrderRequest.setRecipientLatitude(userAddrOrder.getLatitude());
            createOrderRequest.setRecipientLongitude(userAddrOrder.getLongitude());
            createOrderRequest.setRecipientAddress(userAddrOrder.getAddress() + userAddrOrder.getAddressName() + userAddrOrder.getAddrDetail());
        }

        int dvyType = 10;
//        if (order.getDvyType() == 1) {
//            dvyType = 80;
//        } else
        if (order.getDvyType() == 2) {
            dvyType = 40;
        }

        createOrderRequest.setLogisticsType(dvyType);

        OrderRiderLocation orderRiderLocation = orderRiderLocationMapper.selectOne(new LambdaQueryWrapper<OrderRiderLocation>().eq(OrderRiderLocation::getOrderNumber, order.getOrderNumber()));
        if (orderRiderLocation != null) {
            createOrderRequest.setCarrierNo(orderRiderLocation.getOrderNumber());//运单号，快递单号
            createOrderRequest.setLogisticsDispatcherName(orderRiderLocation.getCourierName());// 骑士姓名
            createOrderRequest.setLogisticsDispatcherMobile(orderRiderLocation.getCourierPhone());//骑士电话
//        createOrderRequest.setLogisticsStationTips(Order.getLogisticsStationTips());配送小费
        }
        createOrderRequest.setOrderAgingType(0);
        createOrderRequest.setOrderConfirmTime(order.getCreateTime().getTime());

        if (order.getPayTime() != null) {
            createOrderRequest.setOrderPayTime(order.getPayTime().getTime());
            //配送预计开始时间
            long time = order.getPayTime().getTime();
            //加一个小时
            time += 60 * 60 * 1000;
            createOrderRequest.setLogisticsPreEndTime(time);
        }
//        createOrderRequest.setOrderPickTime(order.getUpdateTime().getTime());//实际拣货完成时间
//        createOrderRequest.setOrderPickPreEndTime(order.getOrderPickPreEndTime());
        if (order.getDvyTime() != null) {
            createOrderRequest.setOrderOutStockTime(order.getDvyTime().getTime());
        }
//        createOrderRequest.setOrderLogisticsEndTime();
        if (order.getFinallyTime() != null) {
            createOrderRequest.setOrderCompletedTime(order.getFinallyTime().getTime());
        }
        if (order.getCancelTime() != null) {
            createOrderRequest.setOrderCancelTime(order.getCancelTime().getTime());
        }
//        createOrderRequest.setOrderCancelRemark(order.getOrderCancelRemark());
        createOrderRequest.setPreSaleOrder(0);
        createOrderRequest.setAdjusted(0);
//        createOrderRequest.setSelfPickCode(order.getSelfPickCode());
//        createOrderRequest.setExtra(order.getExtra());

        //订单费用信息
        OrderFee orderFee = new OrderFee();
        long totalPrice = (long) (order.getTotal() * 100);
        orderFee.setOriginalPrice(totalPrice);
        long actualTotal = (long) (order.getActualTotal() * 100);
        orderFee.setUserPayPrice(actualTotal);
        orderFee.setOrderSettlement(actualTotal);
//        orderFee.setPackingPay(0);
//        orderFee.setLunchboxPay(0);
//        orderFee.setCashOnDeliveryMedicine(0);
//        orderFee.setPointDeduction(0);
//        orderFee.setColdBoxFee(0);
//        orderFee.setPickUpPartsServerFee(0);
        long freightAmount = (long) (order.getFreightAmount() * 100);
        orderFee.setShippingFee(freightAmount);
        orderFee.setBusinessShippingFeeSubsidy(0L);
        orderFee.setPlatformShippingFeeSubsidy(0L);
        orderFee.setBusinessOrderSubsidy(0L);
        orderFee.setPlatformOrderSubsidy(0L);
        orderFee.setBusinessProductSubsidy(0L);
        orderFee.setPlatformProductSubsidy(0L);
        orderFee.setTotalOrderDiscount(0L);
        orderFee.setProductSaleTotalPrice(totalPrice);
//        orderFee.setUserIntegralDeduction(0L);用户积分抵扣金额
//        orderFee.setAdjustFee(0);
        createOrderRequest.setOrderFee(orderFee);


        //订单商品明细
        List<OrderProduct> orderProductList = new ArrayList<>();

        List<OrderItem> listByOrderNumber = orderItemMapper.getListByOrderNumber(order.getOrderNumber());
        for (OrderItem orderItem : listByOrderNumber) {
            Product product1 = productMapper.selectById(orderItem.getProdId());
            Sku sku = skuMapper.selectById(orderItem.getSkuId());
            OrderProduct orderProduct = new OrderProduct();
            orderProduct.setChannelSkuId(sku.getSkuId().toString());
            orderProduct.setOutSkuId(sku.getPartyCode());
            orderProduct.setHbSkuId(Long.parseLong(sku.getHbSkuId()));
            orderProduct.setPreSale(0);
//            orderProduct.setSkuUpc();
            orderProduct.setSkuName(product1.getProdName());
            orderProduct.setSkuWeight(sku.getWeight());
            orderProduct.setUnit(sku.getWeightUnit());
            orderProduct.setCount((long) orderItem.getProdCount());
            orderProduct.setOriginSkuPrice((long) (orderItem.getPrice() * 100));
            orderProduct.setActivitySkuPrice((long) (orderItem.getPrice() * 100));
            orderProduct.setSkuBasicSpec(sku.getSpec());
//            orderProduct.setSkuImg(sku.getPic());
            orderProduct.setBusinessSingleProductSubsidy(0L);
            orderProduct.setPlatformSingleProductSubsidy(0L);
            orderProduct.setBusinessOrderSubsidy(0L);
            orderProduct.setPlatformOrderSubsidy(0L);
            orderProduct.setTransId(sku.getSkuId().toString());
            orderProduct.setParentHBSkuId(0L);
//            orderProduct.setPromotionType(sku.getPromotionType());
//            orderProduct.setProductFeatures(sku.getProductFeatures());

            orderProductList.add(orderProduct);
        }

        createOrderRequest.setProducts(orderProductList);


        //订单支付信息
        List<OrderPayment> orderPaymentList = new ArrayList<>();
        OrderPayment orderPayment = new OrderPayment();
        if (order.getPayType() == null || order.getPayType() == 0) {
            orderPayment.setPaymentType(1301);
        } else if (order.getPayType() == 1) {
            orderPayment.setPaymentType(1002);
        } else if (order.getPayType() == 2) {
            orderPayment.setPaymentType(1001);
        } else {
            orderPayment.setPaymentType(9999);
        }

        orderPayment.setPaymentAmount(totalPrice);
        orderPayment.setPaymentNum(0);
        orderPaymentList.add(orderPayment);
        createOrderRequest.setOrderPayments(orderPaymentList);


        //订单商品活动
//        createOrderRequest.setProductActivities(order.getProductActivities());

        //订单发票信息
//        List<OrderInvoice> orderInvoiceList = new ArrayList<>();
//        OrderInvoice orderInvoice = new OrderInvoice();
//        orderInvoiceList.add(orderInvoice);
//        createOrderRequest.setOrderInvoices(orderInvoiceList);
        //打印json格式
        log.info("海博查询系统订单详情返回数据:{}", JSONObject.toJSONString(createOrderRequest));
        return HBR.success(createOrderRequest);
    }

}
