package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.shop.entity.*;
import com.gxwebsoft.shop.mapper.ShopOrderDeliveryMapper;
import com.gxwebsoft.shop.service.*;
import com.gxwebsoft.shop.param.ShopOrderDeliveryParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.BOrderReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 发货单Service实现
 *
 * @author 科技小王子
 * @since 2025-01-11 10:45:12
 */
@Service
@Slf4j
public class ShopOrderDeliveryServiceImpl extends ServiceImpl<ShopOrderDeliveryMapper, ShopOrderDelivery> implements ShopOrderDeliveryService {
    @Resource
    private ShopExpressService expressService;
    @Resource
    private KuaiDi100Impl kuaiDi100;
    @Resource
    private ShopOrderService shopOrderService;
    @Resource
    private ShopOrderGoodsService shopOrderGoodsService;
    @Resource
    private ShopGoodsService shopGoodsService;
    @Resource
    private ShopUserAddressService shopUserAddressService;
    @Resource
    private ShopWechatShippingSyncService shopWechatShippingSyncService;

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

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

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

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

    @Override
    public Map<String, Object> setExpress(User user, ShopOrderDelivery orderDelivery, ShopOrder order) throws Exception {
        ShopExpress express = expressService.getByIdRel(orderDelivery.getExpressId());
        ShopUserAddress userAddress = shopUserAddressService.getByIdRel(order.getAddressId());

        BOrderReq bOrderReq = new BOrderReq();
        bOrderReq.setKuaidicom(express.getKuaidi100Code());
        bOrderReq.setSendManName(orderDelivery.getSendName());
        bOrderReq.setSendManMobile(orderDelivery.getSendPhone());
        bOrderReq.setSendManPrintAddr(order.getSendAddress());
        bOrderReq.setRecManName(userAddress.getName());
        bOrderReq.setRecManMobile(userAddress.getPhone());
        bOrderReq.setRecManPrintAddr(order.getAddress());
        bOrderReq.setCallBackUrl("https://cms-api.websoft.top/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 (updateById(orderDelivery)) {
            order.setDeliveryStatus(20);
            order.setDeliveryTime(LocalDateTime.now());
            shopOrderService.updateById(order);

            // 同步发货信息到微信小程序后台（发货信息录入），避免人工录入
            try {
                shopWechatShippingSyncService.uploadExpressShippingInfo(order, orderDelivery, express);
            } catch (Exception e) {
                // 不影响本地发货流程，记录日志即可（可配合定时任务后补偿重试）
                log.warn("同步微信发货信息失败(不影响发货成功) - orderId={}", order.getOrderId(), e);
            }
            return new HashMap<>() {{
                put("res", true);
                put("msg", "操作成功");
            }};
        }
        return new HashMap<>() {{
            put("res", false);
            put("msg", "未知错误");
        }};
    }
}
