
package com.yami.shop.api.controller;

import com.alibaba.fastjson2.JSONObject;
import com.yami.shop.bean.app.dto.SimpleDeliveryDto;
import com.yami.shop.bean.model.Delivery;
import com.yami.shop.bean.model.Order;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.delivery.comment.api.paotui.PaoTuiApi;
import com.yami.shop.delivery.comment.api.paotui.model.request.OrderDetailRequest;
import com.yami.shop.delivery.comment.api.paotui.model.response.OrderStatusResponse;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.DeliveryService;
import com.yami.shop.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.util.List;
import java.util.Scanner;

@Slf4j
@RestController
@RequestMapping("/p/delivery")
@Api(tags = "查看物流接口")
public class DeliveryController {

    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private PaoTuiApi paoTuiApi;

    /**
     * 查看物流接口
     */
    @GetMapping("/check")
    @ApiOperation(value = "查看物流", notes = "根据订单号查看物流")
    @ApiImplicitParam(name = "orderNumber", value = "订单号", required = true, dataType = "String")
    public ResponseEntity<OrderStatusResponse> checkDelivery(String orderNumber) {
        // 获取用户id
        String userId = SecurityUtils.getUser().getUserId();
        // 查询订单
        Order order = orderService.getOrderByOrderNumberAndUserId(orderNumber, userId, true);
        // 查询交易单
        Delivery delivery = deliveryService.getById(order.getDvyId());
        if (null == delivery) {
            throw new GlobalException("交易单号不存在");
        }
        // 查询物流详情信息
        // 物流公司名称、官网、订单号、物流详情信息
        OrderStatusResponse orderStatusResponse = null;
        try {
            // 解析的物流详情明细
            OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
            orderDetailRequest.setOrder_id(order.getDvyFlowId());
            orderStatusResponse = paoTuiApi.deliveryRoute(orderDetailRequest);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("物流详情查询出错  => {}", e);
            throw new GlobalException("查询出错");
        }
        return ResponseEntity.ok(orderStatusResponse);
    }

    @GetMapping("/list")
    @ApiOperation(value = "查看物流列表", notes = "查看物流列表")
    public ResponseEntity<List<SimpleDeliveryDto>> checkDelivery() {
        List<Delivery> list = deliveryService.list();
        List<SimpleDeliveryDto> deliveryDtos = mapperFacade.mapAsList(list, SimpleDeliveryDto.class);
        return ResponseEntity.ok(deliveryDtos);
    }

    @GetMapping("/getDeliveryList")
    @ApiOperation("获取快递信息2.0")
    public ResponseEntity<JSONObject> info() {
        ClassLoader classLoader = DeliveryController.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("deliver.txt");
        if (inputStream == null) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.ok(JSONObject.parseObject(getText(inputStream)));
        }
    }

    public static String getText(InputStream inputStream) {
        Scanner scanner = new Scanner(inputStream);
        StringBuilder text = new StringBuilder();
        while (scanner.hasNextLine()) {
            text.append(scanner.nextLine()).append("\n");
        }
        scanner.close();
        return text.toString();
    }
}