package org.dromara.zhishu.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonArray;
import lombok.RequiredArgsConstructor;


import org.dromara.system.service.ISysConfigService;
import org.dromara.zhishu.domain.Shop;
import org.dromara.zhishu.domain.ZhishuShopGoods;
import org.dromara.zhishu.domain.vo.*;
import org.dromara.zhishu.service.*;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;


/**
 * 店铺主表Service业务层处理
 *
 * @author yxy
 * @date 2025-05-8
 */
@RequiredArgsConstructor
@Service
public class GoofishServiceImpl implements IGoofishService {

    private final IShopService shopService;
    private final ISysConfigService configService;
    private final IPriceTemplateService priceTemplateService;


    @Override
    public void goodAdd(ShopVo shop, ZhishuShopGoods zhishuShopGoods, ShopDetailVo shopDetailVo) {
        long timestamp = System.currentTimeMillis() / 1000L;
        // 生成签名
        String domain = "https://open.goofish.pro"; // 域名

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("product_id",  Long.parseLong(zhishuShopGoods.getProductId()));
        jsonObject.put("stock", zhishuShopGoods.getInventory());
        System.out.println("入参goofish"+jsonObject.toJSONString());

        // 生成签名
        String sign = genSign(timestamp, jsonObject.toJSONString(), shop.getMallId().toString(), shop.getToken());
        //调用编辑库存的接口
        String   apiUrl = domain + "/api/open/product/edit/stock?appid=" + shop.getMallId().toString() + "&timestamp=" + timestamp + "&sign="
                + sign;
        try {
            // 创建URL对象
            URL url = new URL(apiUrl);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头部
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            // 启用输出流
            connection.setDoOutput(true);

            // 获取输出流并写入请求体
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
            outputStream.close();

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            System.out.println("API Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                response.append(line);
            }
            bufferedReader.close();

            // 关闭连接
            connection.disconnect();

            System.out.println("API Response: " + response.toString());

        } catch (IOException e) {
            // 在此处处理异常
            e.printStackTrace();
        }
    }




    /**
     * 调用闲鱼服务接口修改商品库存
     * @param
     */
    public void goodUpdateStock(ShopVo shop, String itemId, String number,Integer  type){

        long timestamp = System.currentTimeMillis() / 1000L;
        // 生成签名
        String domain = "https://open.goofish.pro"; // 域名

        // 请求体JSON字符串
        //String productId = itemId;

        JSONObject jsonObject = new JSONObject();


        // 生成签名

        String apiUrl=null;
        String sign=null;

        if (2==type){
            jsonObject.put("product_id",  Long.parseLong(itemId));
           jsonObject.put("stock", Long.parseLong(number));
            System.out.println("入参goofish"+jsonObject.toJSONString());
            sign = genSign(timestamp, jsonObject.toJSONString(), shop.getMallId().toString(), shop.getToken());
            if ("0".equals(number)){

                //调用下架商品
                // 拼接请求地址
                apiUrl = domain + "/api/open/product/downShelf?appid=" + shop.getMallId().toString() + "&timestamp=" + timestamp + "&sign="
                        + sign;

            }else{
                //调用编辑库存的接口
                apiUrl = domain + "/api/open/product/edit/stock?appid=" + shop.getMallId().toString() + "&timestamp=" + timestamp + "&sign="
                        + sign;
            }
        } else if (3==type) {

            //调用上架商品
            if ("1".equals(number)){
                List<String> jsonArray=new ArrayList<>();
                jsonArray.add(shop.getShopKey());
                jsonObject.put("product_id",  Long.parseLong(itemId));
                jsonObject.put("user_name",  jsonArray);
                System.out.println("入参goofish1 3"+jsonObject.toJSONString());
                sign = genSign(timestamp, jsonObject.toJSONString(), shop.getMallId().toString(), shop.getToken());

                //调用下架商品
                // 拼接请求地址
                apiUrl = domain + "/api/open/product/publish?appid=" + shop.getMallId().toString() + "&timestamp=" + timestamp + "&sign="
                        + sign;

            }else{
                jsonObject.put("product_id",  Long.parseLong(itemId));
                jsonObject.put("stock", Long.parseLong(number));
                System.out.println("入参goofish 3"+jsonObject.toJSONString());
                sign = genSign(timestamp, jsonObject.toJSONString(), shop.getMallId().toString(), shop.getToken());

                //调用编辑库存的接口
                apiUrl = domain + "/api/open/product/edit/stock?appid=" + shop.getMallId().toString() + "&timestamp=" + timestamp + "&sign="
                        + sign;
            }

        }


        try {
            // 创建URL对象
            URL url = new URL(apiUrl);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");

            // 设置请求头部
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            // 启用输出流
            connection.setDoOutput(true);

            // 获取输出流并写入请求体
            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8));
            outputStream.close();

            // 获取响应状态码
            int responseCode = connection.getResponseCode();
            System.out.println("API Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                response.append(line);
            }
            bufferedReader.close();

            // 关闭连接
            connection.disconnect();

            System.out.println("API Response: " + response.toString());

        } catch (IOException e) {
            // 在此处处理异常
            e.printStackTrace();
        }

    }




    // 生成签名
    private static String genSign(long timestamp, String jsonStr, String apiKey, String apiKeySecret) {
        // 拼接字符串
        String data = apiKey + "," + genMd5(jsonStr) + "," + timestamp + "," + apiKeySecret;

        // 商务对接模式 拼接字符串
        // String data = apiKey + "," + genMd5(jsonStr) + "," + timestamp + "," + seller_id + "," + apiKeySecret;

        // 生成签名
        return genMd5(data);
    }

    // md5加密
    private static String genMd5(String str) {
        StringBuilder result = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes(StandardCharsets.UTF_8));
            for (byte b : digest) {
                result.append(String.format("%02x", b & 0xff));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        return result.toString();
    }

}


