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

package com.yami.shop.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.bo.PayInfoBo;
import com.yami.shop.bean.model.Channel;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.RefundDelivery;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.service.*;
import com.yami.shop.service.hb.IHBOrderService;
import com.yami.shop.wx.service.WxProviderService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

//@ApiIgnore
@RestController
@RequestMapping("/notice/pay")
@AllArgsConstructor
public class PayNoticeController {

    private final PayService payService;

    private final OrderService orderService;

    private final ProductService productService;

    private final SkuService skuService;

    private final PayManagerService payManagerService;

    private final RefundDeliveryService refundDeliveryService;

    private final WxProviderService wxProviderService;

    private final IHBOrderService hbOrderService;
    private final ChannelService channelService;

    @ApiOperation(value = "回调")
    @SneakyThrows
    @RequestMapping("/order/wxNotify")
    public ResponseEntity<String> wxNotify(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入回调...");
        PayInfoBo payInfoBo = wxProviderService.notifyParse(request,response);

        if (payInfoBo.getPayNo().contains("refundSn")) {
            String[] split = payInfoBo.getPayNo().split("refundSn");
            RefundDelivery refundDelivery = refundDeliveryService.getOne(new LambdaQueryWrapper<RefundDelivery>()
                    .eq(RefundDelivery::getRefundSn, split[1]));
            refundDelivery.setPay(true);
            refundDeliveryService.update(refundDelivery, new LambdaQueryWrapper<RefundDelivery>()
                    .eq(RefundDelivery::getRefundSn, split[1]));

        } else {
            // 根据内部订单号更新order settlement
            List<Order> orders = payService.paySuccess(payInfoBo.getPayNo(), payInfoBo.getBizPayNo(), 1);

            //进行拆单处理
//            List<Order> objects = new ArrayList<>();
//            for (Order order : orders) {
//                Channel byId = channelService.getById(order.getChannelId());
//                orderService.cd(order, byId, objects);
//            }
//
//            for (Order order : objects) {
//                //创建子订单
//                orderService.save(order);
//                //推送海博订单
//                hbOrderService.createOrderAsync(order.getOrderNumber());
//            }

            // 移除缓存
            for (Order order : orders) {
                List<OrderItem> orderItems = order.getOrderItems();
                for (OrderItem orderItem : orderItems) {
                    productService.removeProductCacheByProdId(orderItem.getProdId());
                    skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
                }
            }

            //推送海博订单
            for (Order order : orders) {
                hbOrderService.createOrderAsync(order.getOrderNumber());
            }
        }
        return ResponseEntity.ok(payInfoBo.getSuccessString());
    }


    @SneakyThrows
    @RequestMapping("/order/refundNotify")
    public ResponseEntity<String> refundNotify(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("进入退款回调...");
         wxProviderService.refundNotifyParse(request,response);
        return ResponseEntity.ok().build();
    }



    @SneakyThrows
    //@RequestMapping("/order/{payType}")
    public ResponseEntity<String> submit(HttpServletRequest request, @PathVariable Integer payType, @RequestBody(required = false) String xmlData) {
        PayInfoBo payInfoBo = payManagerService.validateAndGetPayInfo(request, PayType.instance(payType), xmlData);
        if (payInfoBo.getPayNo().contains("refundSn")) {
            String[] split = payInfoBo.getPayNo().split("refundSn");
            RefundDelivery refundDelivery = refundDeliveryService.getOne(new LambdaQueryWrapper<RefundDelivery>()
                    .eq(RefundDelivery::getRefundSn, split[1]));
            refundDelivery.setPay(true);
            refundDeliveryService.update(refundDelivery, new LambdaQueryWrapper<RefundDelivery>()
                    .eq(RefundDelivery::getRefundSn, split[1]));
        } else {
            // 根据内部订单号更新order settlement
            List<Order> orders = payService.paySuccess(payInfoBo.getPayNo(), payInfoBo.getBizPayNo(), payType);
            // 移除缓存
            for (Order order : orders) {
                List<OrderItem> orderItems = order.getOrderItems();
                for (OrderItem orderItem : orderItems) {
                    productService.removeProductCacheByProdId(orderItem.getProdId());
                    skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
                }
            }
        }
        return ResponseEntity.ok(payInfoBo.getSuccessString());
    }

}
