package com.ruoyi.framework.web.service;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.Order;
import com.ruoyi.system.domain.OrderDetail;
import com.ruoyi.system.mapper.OrderDetailMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MachineSericeImpl {
    @Value("machine.url")
    private String url;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    public void createOrder(Order order){
        String interfaceName = "/v1/order";
        String postUrl = url+interfaceName;
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId());
        List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailList(orderDetail);
        List<JSONObject> jsonObjects = new ArrayList<>();
        for (OrderDetail detail : orderDetails) {
            JSONObject jsonObject = new JSONObject();
            jsonObjects.add(jsonObject);
            String skuId = detail.getSkuId();
            String num = detail.getNum();
            String amount = detail.getAmount().stripTrailingZeros().toString();
            String realAmount = detail.getRealAmount().stripTrailingZeros().toString();
            jsonObject.put("skuID",skuId);
            jsonObject.put("skuCount",num);
            jsonObject.put("originAmount",amount);
            jsonObject.put("subtotal",realAmount);
        }
        JSONObject orderInfo =new JSONObject();
        orderInfo.put("shopID",order.getShopId());
        orderInfo.put("memberID",order.getUserId());
        orderInfo.put("goodsList",jsonObjects);
        orderInfo.put("source",order.getSource());
        orderInfo.put("orderAmount",order.getAmount().stripTrailingZeros().toString());
        orderInfo.put("cteatedAt",order.getCreatedAt());
        orderInfo.put("robotID",order.getMachineId());
        log.info("请求创建订单接口：【{}】",orderInfo.toJSONString());
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(postUrl, orderInfo, String.class);
        log.info("请求创建订单接口返回结果为：【{}】",stringResponseEntity.getBody());



    }
}
