package com.gxwebsoft.shop.service.impl;

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.*;
import cn.binarywang.wx.miniapp.bean.shop.response.WxMaOrderShippingInfoBaseResponse;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.controller.WeChatController;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.mapper.OrderDeliveryMapper;
import com.gxwebsoft.shop.service.ExpressService;
import com.gxwebsoft.shop.service.KuaiDi100;
import com.gxwebsoft.shop.service.OrderDeliveryService;
import com.gxwebsoft.shop.param.OrderDeliveryParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.shop.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.gxwebsoft.shop.consts.OrderPayType.PAY_TYPE_FRIEND;
import static com.gxwebsoft.shop.consts.OrderPayType.PAY_TYPE_WECHAT;

/**
 * 发货单Service实现
 *
 * @author 科技小王子
 * @since 2024-09-24 01:39:23
 */
@Service
public class OrderDeliveryServiceImpl extends ServiceImpl<OrderDeliveryMapper, OrderDelivery> implements OrderDeliveryService {
    @Resource
    private KuaiDi100 kuaiDi100;
    @Resource
    private ExpressService expressService;
    @Resource
    private OrderService orderService;
    @Autowired
    private WeChatController weChatController;

    @Override
    public PageResult<OrderDelivery> pageRel(OrderDeliveryParam param) {
        PageParam<OrderDelivery, OrderDeliveryParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<OrderDelivery> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<OrderDelivery> listRel(OrderDeliveryParam param) {
        List<OrderDelivery> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<OrderDelivery, OrderDeliveryParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public OrderDelivery getByIdRel(Integer deliveryId) {
        OrderDeliveryParam param = new OrderDeliveryParam();
        param.setDeliveryId(deliveryId);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public OrderDelivery getByOrderId(Integer orderId) {
        return getOne(
                new LambdaQueryWrapper<OrderDelivery>()
                        .eq(OrderDelivery::getOrderId, orderId)
                        .orderByDesc(OrderDelivery::getCreateTime)
                        .last("limit 1")
        );
    }

    @Override
    public List<OrderDelivery> listByOrderIds(List<Integer> orderIds) {
        return list(
                new LambdaQueryWrapper<OrderDelivery>()
                        .in(OrderDelivery::getOrderId, orderIds)
        );
    }

    @Override
    public Map<String, Object> setExpress(OrderDelivery orderDelivery, Order order, List<OrderGoods> orderGoodsList) throws Exception {
//            order.setExpressMerchantId(merchant.getMerchantId());
//            order.setExpressMerchantName(merchant.getMerchantName());
//            order.setDeliveryStatus(20);
//            order.setDeliveryTime(DateUtil.date());
//            orderService.updateById(order);

//        if (order.getPayType().equals(PAY_TYPE_WECHAT) || (order.getPayType().equals(PAY_TYPE_FRIEND) && order.getFriendPayType().equals(PAY_TYPE_WECHAT))) {
        // 上传小程序发货信息
        WxMaOrderShippingInfoUploadRequest uploadRequest = new WxMaOrderShippingInfoUploadRequest();
        uploadRequest.setLogisticsType(4);
        uploadRequest.setDeliveryMode(1);

        OrderKeyBean orderKeyBean = new OrderKeyBean();
        orderKeyBean.setOrderNumberType(2);
        orderKeyBean.setTransactionId("4200002653202503096477455081");
        uploadRequest.setOrderKey(orderKeyBean);

        List<ShippingListBean> shippingList = new ArrayList<>();
        ShippingListBean shippingListBean = new ShippingListBean();
//        shippingListBean.setTrackingNo((String) bOrderData.get("kuaidinum"));
//        shippingListBean.setExpressCompany(express.getWxCode());
//        ContactBean contactBean = new ContactBean();
//        contactBean.setReceiverContact(user.getMobile());
//        shippingListBean.setContact(contactBean);

//        String itemDesc = orderGoodsList.get(0).getGoods().getGoodsName();
//        if (orderGoodsList.size() > 1) itemDesc += "等" + orderGoodsList.size() + "件商品";
        shippingListBean.setItemDesc("祥安瑞选");
        shippingList.add(shippingListBean);
        uploadRequest.setShippingList(shippingList);

        uploadRequest.setUploadTime(new DateTime().toString(DatePattern.UTC_WITH_ZONE_OFFSET_PATTERN));

        PayerBean payerBean = new PayerBean();

        payerBean.setOpenid("o1sKh7YtZcSHPrROJPHeJVqOmMUI");
        uploadRequest.setPayer(payerBean);

        WxMaService wxMaService = weChatController.wxMaService();
        WxMaOrderShippingService wxMaOrderShippingService = new WxMaOrderShippingServiceImpl(wxMaService);
        WxMaOrderShippingInfoBaseResponse response = wxMaOrderShippingService.upload(uploadRequest);
        System.out.println("response" + response);
//        }
        return new HashMap<>() {{
            put("res", true);
            put("msg", "操作成功");
        }};
    }


    @Override
    public Map<String, Object> setExpress(User user, OrderDelivery orderDelivery, Merchant merchant, Order order, List<OrderGoods> orderGoodsList) throws Exception {
//        Express express = expressService.getByIdRel(orderDelivery.getExpressId());
//        BOrderReq bOrderReq = new BOrderReq();
//        bOrderReq.setKuaidicom(express.getKuaidi100Code());
//        bOrderReq.setSendManName(merchant.getMerchantName());
//        bOrderReq.setSendManMobile(merchant.getPhone());
//        bOrderReq.setSendManPrintAddr(merchant.getProvince() + merchant.getCity() + merchant.getRegion() + merchant.getAddress());
//        bOrderReq.setRecManName(order.getRealName());
//        bOrderReq.setRecManMobile(order.getPhone());
//        bOrderReq.setRecManPrintAddr(order.getAddress());
//        bOrderReq.setCallBackUrl("https://modules.gxwebsoft.com/api/shop/order-delivery/notify");
//        HttpResult res = kuaiDi100.border(bOrderReq);
//        if (res.getStatus() != 200) return new HashMap<>() {{
//            put("res", false);
//            put("msg", "快递100接口异常");
//        }};
//        KuaiDi100Resp kuaiDi100Resp = JSONUtil.parseObject(res.getBody(), KuaiDi100Resp.class);
//        if (kuaiDi100Resp == null) return new HashMap<>() {{
//            put("res", false);
//            put("msg", "快递100接口异常");
//        }};
//
//        if (!kuaiDi100Resp.getResult())
//            return new HashMap<>() {{
//                put("res", false);
//                put("msg", kuaiDi100Resp.getMessage());
//            }};
//        Map<String, Object> bOrderData = (Map<String, Object>) kuaiDi100Resp.getData();
//        orderDelivery.setExpressNo((String) bOrderData.get("kuaidinum"));
        if (save(orderDelivery)) {
            order.setExpressMerchantId(merchant.getMerchantId());
            order.setExpressMerchantName(merchant.getMerchantName());
            order.setDeliveryStatus(20);
            order.setDeliveryTime(DateUtil.date());
            orderService.updateById(order);

            if (order.getPayType().equals(PAY_TYPE_WECHAT) || (order.getPayType().equals(PAY_TYPE_FRIEND) && order.getFriendPayType().equals(PAY_TYPE_WECHAT))) {
                // 上传小程序发货信息
                WxMaOrderShippingInfoUploadRequest uploadRequest = new WxMaOrderShippingInfoUploadRequest();
                uploadRequest.setLogisticsType(4);
                uploadRequest.setDeliveryMode(1);

                OrderKeyBean orderKeyBean = new OrderKeyBean();
                orderKeyBean.setOrderNumberType(2);
                orderKeyBean.setTransactionId("174152451321810350379");
                uploadRequest.setOrderKey(orderKeyBean);

//                List<ShippingListBean> shippingList = new ArrayList<>();
//                ShippingListBean shippingListBean = new ShippingListBean();
//                shippingListBean.setTrackingNo((String) bOrderData.get("kuaidinum"));
//                shippingListBean.setExpressCompany(express.getWxCode());
//                ContactBean contactBean = new ContactBean();
//                contactBean.setReceiverContact(user.getMobile());
//                shippingListBean.setContact(contactBean);

                String itemDesc = orderGoodsList.get(0).getGoods().getGoodsName();
                if (orderGoodsList.size() > 1) itemDesc += "等" + orderGoodsList.size() + "件商品";
//                shippingListBean.setItemDesc(itemDesc);
//                shippingList.add(shippingListBean);
//                uploadRequest.setShippingList(shippingList);

                uploadRequest.setUploadTime(new DateTime().toString(DatePattern.UTC_WITH_ZONE_OFFSET_PATTERN));

                PayerBean payerBean = new PayerBean();

                payerBean.setOpenid("o1sKh7YtZcSHPrROJPHeJVqOmMUI");
                uploadRequest.setPayer(payerBean);

                WxMaService wxMaService = weChatController.wxMaService();
                WxMaOrderShippingService wxMaOrderShippingService = new WxMaOrderShippingServiceImpl(wxMaService);
                WxMaOrderShippingInfoBaseResponse response = wxMaOrderShippingService.upload(uploadRequest);
                System.out.println("response" + response);
            }
            return new HashMap<>() {{
                put("res", true);
                put("msg", "操作成功");
            }};
        }
        return new HashMap<>() {{
            put("res", false);
            put("msg", "未知错误");
        }};
    }
}
