package com.ruoyi.api.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.api.constant.yz.ApiConstant;
import com.ruoyi.api.downstream.YzResult;
import com.ruoyi.api.fake.PushProductFake;
import com.ruoyi.api.pojo.bo.ProductsBO;
import com.ruoyi.api.service.IProductService;
import com.ruoyi.api.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl implements IProductService {
    @Value("${downstream.url}")
    private String url;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public YzResult pushProduct() throws JsonProcessingException {
        String realUrl = url + ApiConstant.PUSH_PRODUCT;

        // TODO:没有第三方供应链，伪造测试数据
        ProductsBO productsBO = PushProductFake.productsBO();
        objectMapper.setPropertyNamingStrategy(com.fasterxml.jackson.databind.PropertyNamingStrategy.SNAKE_CASE);

        String data = objectMapper.writeValueAsString(productsBO);
        System.out.println("data: " + data);

        ResponseEntity<String> responseEntity = HttpUtils.sendPostWithHeaders(realUrl, data);
        return objectMapper.readValue(responseEntity.getBody(), YzResult.class);
    }

    @Override
    public YzResult updateCloudProduct() {
        String realUrl = url + ApiConstant.UPDATE_CLOUD_PRODUCT;

        // TODO:没有第三方供应链，伪造测试数据
        ProductsBO productsBO = PushProductFake.productsBO();
        productsBO.setId(397L);
        productsBO.setCode("t0001");

        // 属性
        List<ProductsBO.ProductsAttrsBO> attrList = new ArrayList<>();
        String jsonStr = "[{\"name\":\"颜色\", \"value\":\"粉\"},{\"name\":\"颜色\", \"value\":\"紫色\"}]";
        JSONArray jsonArray = JSONUtil.parseArray(jsonStr);
        for (Object o: jsonArray) {
            ProductsBO.ProductsAttrsBO productsAttrsBO = productsBO.new ProductsAttrsBO();
            Map<String, String> map = (Map<String, String>) o;
            productsAttrsBO.setName(map.get("name"));
            productsAttrsBO.setValue(map.get("value"));
            attrList.add(productsAttrsBO);
        }

        productsBO.setAttrs(attrList);
        System.out.println(productsBO);
        return null;
    }
}
