package com.tmerclub.cloud.order.task;

import cn.binarywang.wx.miniapp.api.WxMaOrderShippingService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaOrderShippingServiceImpl;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.OrderKeyBean;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.PayerBean;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.ShippingListBean;
import cn.binarywang.wx.miniapp.bean.shop.request.shipping.WxMaOrderShippingInfoUploadRequest;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaOrderShippingInfoBaseResponse;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaOrderShippingInfoGetListResponse;
import cn.hutool.core.collection.CollectionUtil;
import com.tmerclub.cloud.api.auth.feign.AccountFeignClient;
import com.tmerclub.cloud.api.auth.feign.AuthSocialFeignClient;
import com.tmerclub.cloud.api.payment.dto.PayInfoApiDto;
import com.tmerclub.cloud.api.payment.feign.PaymentFeignClient;
import com.tmerclub.cloud.config.WxConfig;
import com.tmerclub.cloud.common.order.constant.DeliveryType;
import com.tmerclub.cloud.common.order.vo.OrderItemLangVO;
import com.tmerclub.cloud.common.order.vo.OrderItemVO;
import com.tmerclub.cloud.common.util.Json;
import com.tmerclub.cloud.order.model.Order;
import com.tmerclub.cloud.order.service.OrderItemService;
import com.tmerclub.cloud.order.service.OrderService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 小程序虚拟和自提订单发货定时任务
 * @author zp
 */
@Component
public class OrderDeliveryTask {

    @Autowired
    private WxConfig wxConfig;
    @DubboReference
    private AuthSocialFeignClient authSocialFeignClient;
    @DubboReference
    private AccountFeignClient accountFeignClient;
    @DubboReference
    private PaymentFeignClient paymentFeignClient;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderItemService orderItemService;

    /**
     * 小程序发货
     */
    @XxlJob("wxAppShipment")
    public void wxAppShipment() {
        XxlJobHelper.log("小程序发货定时任务");
        Boolean tradeManaged = wxConfig.getTradeManaged();
        if (tradeManaged) {
            WxMaOrderShippingInfoGetListResponse response = wxConfig.getOrderIdList();
            if (CollectionUtil.isNotEmpty(response.getOrderList())) {
                for (WxMaOrderShippingInfoBaseResponse.Order wxOrder : response.getOrderList()) {
                    WxMaOrderShippingInfoUploadRequest request = new WxMaOrderShippingInfoUploadRequest();
                    OrderKeyBean orderKey = new OrderKeyBean();
                    orderKey.setOrderNumberType(2);
                    orderKey.setTransactionId(wxOrder.getTransactionId());
                    request.setOrderKey(orderKey);
                    request.setDeliveryMode(1);
                    PayInfoApiDto payInfoApiDto = paymentFeignClient.getPayInfoByPayId(Long.parseLong(wxOrder.getMerchantTradeNo())).getData();
                    if (Objects.isNull(payInfoApiDto)) {
                        continue;
                    }
                    String[] orderIds = payInfoApiDto.getOrderIds().split(",");
                    // 因为只获取虚拟订单和自提订单，所以其实只有一个orderId
                    Order order = orderService.getByOrderId(Long.parseLong(orderIds[0]));
                    if (Objects.isNull(order)) {
                        // 不是虚拟订单或自提订单，不需要定时任务发货
                        continue;
                    }
                    if (order.getDeliveryType().equals(DeliveryType.STATION.value())) {
                        request.setLogisticsType(4);
                    }else if (order.getOrderMold() == 1 ) {
                        request.setLogisticsType(3);
                    }else {
                        continue;
                    }
                    request.setLogisticsType(order.getDeliveryType());
                    ShippingListBean shippingListBean = new ShippingListBean();
                    String itemDesc = "";
                    for (OrderItemVO orderItem : orderItemService.listOrderItemAndLangByOrderId(order.getOrderId())) {
                        if (CollectionUtil.isNotEmpty(orderItem.getOrderItemLangList())) {
                            Map<Integer, String> nameMap = orderItem.getOrderItemLangList().stream().collect(Collectors.toMap(OrderItemLangVO::getLang, OrderItemLangVO::getSpuName));
                            itemDesc += nameMap.get(1) + "*" + orderItem.getCount() + "    ";
                        } else {
                            itemDesc += orderItem.getSpuName() + "*" + orderItem.getCount() + "    ";
                        }
                    }
                    shippingListBean.setItemDesc(itemDesc);
                    request.setShippingList(Collections.singletonList(shippingListBean));
                    DateFormat dft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
                    request.setUploadTime(dft.format(new Date()));
                    PayerBean payerBean = new PayerBean();
                    payerBean.setOpenid(payInfoApiDto.getBizUserId());
                    request.setPayer(payerBean);
                    try {
                        WxMaService wxMaService = wxConfig.getWxMaService();
                        WxMaOrderShippingService wxMaOrderShippingService = new WxMaOrderShippingServiceImpl(wxMaService);
                        XxlJobHelper.log("虚拟订单发货录入的参数" + Json.toJsonString(request));
                        wxMaOrderShippingService.upload(request);
                    } catch (WxErrorException wxErrorException) {
                        wxErrorException.printStackTrace();
                        XxlJobHelper.log("订单id为"+ order.getOrderId() +"的小程序发货错误信息：" + wxErrorException.getError().getErrorMsg());
                    }
                }
            }
        }
    }
}
