package com.ruoyi.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.ResultVo;
import com.ruoyi.system.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class MachineApiServiceImpl {
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShopGoodsSkuMapper shopGoodsSkuMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Value("${machine.url}")
    private String url;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private MachineMapper machineMapper;
    public String shopGoodsUpdate(JSONObject jsonObject) {
        String shopID = jsonObject.getString("shopId");
        String skuIDs = jsonObject.getString("skuId");
        List<String> skuIds = JSONObject.parseArray(skuIDs, String.class);
        String robotID = jsonObject.getString("robotId");
        String status = jsonObject.getString("status");
        int i = shopGoodsSkuMapper.updateSkuStatus(skuIds, robotID, shopID, status);
        return ""+i;

    }

    public String updateOrder(JSONObject jsonObject) {
        long orderID = jsonObject.getLong("orderId");
        String status = jsonObject.getString("status");
        Order order = new Order();
        order.setId(orderID);
        order.setState(status);
        int i = orderMapper.updateOrder(order);
        return i+"";

    }

    public void testOrder(String orderId) {
        try{
            if(StringUtils.isEmpty(orderId)){
                orderId = "8";
            }
            Order order = orderMapper.selectOrderById(orderId);
            OrderDetail orderDetail =new OrderDetail();
            orderDetail.setOrderId(order.getId());
            List<OrderDetail> orderDetails = orderDetailMapper.selectOrderDetailList(orderDetail);
            order.setOrderDetails(orderDetails);
            ObjectMapper objectMapper = new ObjectMapper();
            String orderInfo = objectMapper.writeValueAsString(order);
            ResultVo resultVo =sendRequest(orderInfo,"/v1/order");

            String code = resultVo.getCode();
            if("2001".equals(code)){
                throw  new ServiceException("库存不足");
            }else   if("3001".equals(code)){
                throw  new ServiceException("机器繁忙");
            }
        }catch (Exception e){
            log.error("",e);
        }

    }

    public ResultVo createOrder(Order order){
        String orderInfo = null;
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            orderInfo = objectMapper.writeValueAsString(order);
        }catch (Exception e){
            throw new ServiceException("初始订单数据异常，请重试");
        }

        ResultVo resultVo =sendRequest(orderInfo,"/v1/order");

        String code = resultVo.getCode();
        if("2001".equals(code)){
            throw  new ServiceException("库存不足");
        }else   if("3001".equals(code)){
            throw  new ServiceException("机器繁忙");
        }
        return resultVo;

    }




    public ResultVo sendRequest(String  param,String interfaceName){
        try{
            String postUrl = url+interfaceName;
            log.info("请求创建订单接口：【{}】",param);
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity requestEntity = new HttpEntity(param,requestHeaders);
            ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity(postUrl, requestEntity, String.class);
            log.info("请求创建订单接口返回结果为：【{}】",stringResponseEntity.getBody());
            ResultVo resultVo = JSONObject.parseObject(stringResponseEntity.getBody(), ResultVo.class);
            return resultVo;
        }catch (Exception e){
            log.error("请求发生异常：",e);
            throw  new ServiceException("服务器繁忙，请重试");
        }

    }

    public void testOrderUpdate(String orderId) {
        if(StringUtils.isEmpty(orderId)){
            orderId = "8";
        }
        JSONObject param = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("state",2);
        data.put("payTime",new Date());
        param.put("data",data.toJSONString());
        param.put("orderId",orderId);
        sendRequest(param.toJSONString(),"/v1/order/update");
    }

    public Object robotUpdate(JSONObject jsonObject) {
        String robotID = jsonObject.getString("robotID");
        String status = jsonObject.getString("status");
        Long shopID = jsonObject.getLong("shopID");
        Machine machine = new Machine();
        machine.setShopId(shopID);
        machine.setId(robotID);
        List<Machine> machines = machineMapper.selectMachineList(machine);
        if(machines.isEmpty()){
            throw new ServiceException("该机器未绑定店铺") ;
        }
        machine.setState(status);
        return machineMapper.updateMachine(machine);


    }

    public void updateOrder(Order order1) {

    }
}
