package org.dromara.zhishu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Slf4j
@Service
public class XianYvQueryShopImpl {

    private final RestTemplate restTemplate;

    @Autowired
    public XianYvQueryShopImpl(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public R<List<Map<String, String>>> XianYvQueryShop(String appId, String appSecret) {
        try {
            String url = "http://119.45.237.193:9102/xianyv/getShopList";
            log.info("开始调用咸鱼API: {}", url);

            // 设置请求头 - 使用表单格式
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            // 创建表单参数
            MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
            formData.add("appId", appId);
            formData.add("appSecret", appSecret);

            HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers);

            // 使用POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url, HttpMethod.POST, entity, String.class);

            log.info("咸鱼API响应状态: {}", response.getStatusCode());
            log.info("咸鱼API响应内容: {}", response.getBody());

            if (response.getStatusCode().value() == 200) {
                JSONObject jsonObject = JSON.parseObject(response.getBody());

                if (jsonObject.getInteger("code") == 0) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data == null) {
                        log.warn("咸鱼API返回data为空");
                        return R.ok(Collections.emptyList());
                    }

                    JSONArray list = data.getJSONArray("list");
                    if (list == null || list.isEmpty()) {
                        log.info("咸鱼店铺列表为空");
                        return R.ok(Collections.emptyList());
                    }

                    List<Map<String, String>> shopList = new ArrayList<>();
                    for (int i = 0; i < list.size(); i++) {
                        JSONObject item = list.getJSONObject(i);
                        String userName = item.getString("user_name");
                        String shopName = item.getString("shop_name");
                        String expirationTime = item.getString("valid_end_time");

                        // 创建一个Map来存储用户名称和店铺名称
                        Map<String, String> shopInfo = new HashMap<>();
                        if (userName != null && !userName.trim().isEmpty()) {
                            shopInfo.put("user_name", userName);
                        }
                        if (shopName != null && !shopName.trim().isEmpty()) {
                            shopInfo.put("shop_name", shopName);
                        }
                        if (expirationTime != null && !expirationTime.trim().isEmpty()) {
                            shopInfo.put("expiration_time", expirationTime);
                        }

                        // 只有当至少有一个字段不为空时才添加到结果列表
                        if (!shopInfo.isEmpty()) {
                            shopList.add(shopInfo);
                            log.info("找到店铺 - 用户名称: {}, 店铺名称: {}", userName, shopName);
                        }
                    }

                    log.info("成功获取咸鱼店铺数量: {}", shopList.size());
                    return R.ok(shopList);
                } else {
                    String errorMsg = jsonObject.getString("msg");
                    log.error("咸鱼API业务异常: {}", errorMsg);
                    return R.fail("咸鱼API返回错误: " + errorMsg);
                }
            } else {
                log.error("咸鱼API请求失败，状态码: {}", response.getStatusCode().value());
                return R.fail("咸鱼API请求失败，状态码: " + response.getStatusCode().value());
            }

        } catch (Exception e) {
            log.error("调用咸鱼API异常: {}", e.getMessage(), e);
            return R.fail("调用咸鱼API异常: " + e.getMessage());
        }
    }
}