package com.ruoyi.logistics.callback;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.logistics.domain.BizWaybillOrder;
import com.ruoyi.logistics.dto.JDOrderStatusRequestDTO;
import com.ruoyi.logistics.enums.OrderStatusEnum;
import com.ruoyi.logistics.service.IBizWaybillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/callback/jd")
public class JDPushOrderStatausCallback {

    @Autowired
    private IBizWaybillOrderService bizWaybillOrderService;

    @PostMapping(value = "/orderStatus", consumes = MediaType.TEXT_PLAIN_VALUE)
    public AjaxResult orderStatus(@RequestBody String requestBody) {
        log.info("京东物流运单状态回调，参数：{}", requestBody);

        JDOrderStatusRequestDTO request = JSON.parseObject(requestBody, JDOrderStatusRequestDTO.class);

        // 根据运单号查询订单
        BizWaybillOrder query = new BizWaybillOrder();
        query.setWaybillNo(request.getCustomerOrderNo());
        query.setExternalWaybillNo(request.getWaybillNo());
        BizWaybillOrder bizWaybillOrder = bizWaybillOrderService.selectBizWaybillOrderByQuery(query);
        if (bizWaybillOrder == null) {
            return AjaxResult.error("订单不存在");
        }
        Boolean update = Boolean.FALSE;
        switch (request.getOperationCode()) {
            case "200001"://揽收
                bizWaybillOrder.setOrderStatus(OrderStatusEnum.ORDER_STATUS_2.getCode());
                bizWaybillOrder.setPickupTime(DateUtils.getNowDate());
                update = Boolean.TRUE;
                break;
            case "10054"://运输
                bizWaybillOrder.setOrderStatus(OrderStatusEnum.ORDER_STATUS_3.getCode());
                update = Boolean.TRUE;
                break;
            case "200056"://派送
            case "11000"://派送
                bizWaybillOrder.setOrderStatus(OrderStatusEnum.ORDER_STATUS_4.getCode());
                bizWaybillOrder.setDeliveryTime(DateUtils.getNowDate());
                update = Boolean.TRUE;
                break;
            case "10034"://妥投
                bizWaybillOrder.setOrderStatus(OrderStatusEnum.ORDER_STATUS_5.getCode());
                bizWaybillOrder.setSignTime(DateUtils.getNowDate());
                update = Boolean.TRUE;
                break;
        }
        if (update) {
            bizWaybillOrderService.updateBizWaybillOrder(bizWaybillOrder);
        }

        return AjaxResult.success();
    }
}
