package com.ylx.massage.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ylx.common.core.domain.R;
import com.ylx.common.exception.ServiceException;
import com.ylx.massage.domain.vo.ShareVolutionDetailVO;
import com.ylx.massage.service.ShareVolutionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ShareVolutionServiceImpl implements ShareVolutionService {

    @Value("${remote.local-live.base-url}")
    private String localLiveBaseUrl;

    private static final String GET_VOLUTION_DETAIL_PATH = "/customer/volution/getVolutionDetailByShareVolutionId";

    private static final int DEFAULT_TIMEOUT = 5000;

    @Override
    public R<ShareVolutionDetailVO> getVolutionDetailByShareVolutionId(String shareVolutionId) {
        if (StrUtil.isBlank(shareVolutionId)) {
            return R.fail("分享优惠券ID不能为空");
        }

        try {
            String url = localLiveBaseUrl + GET_VOLUTION_DETAIL_PATH + "?shareVolutionId=" + shareVolutionId;
            log.info("调用远程接口查询分享优惠券详情, URL: {}, shareVolutionId: {}", url, shareVolutionId);

            String result = HttpUtil.get(url, DEFAULT_TIMEOUT);
            if (StrUtil.isEmpty(result)) {
                log.error("调用远程接口返回为空, shareVolutionId: {}", shareVolutionId);
                return R.fail("查询分享优惠券详情失败");
            }
            log.info("调用远程接口返回结果: {}", result);

            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject == null) {
                return R.fail("解析分享优惠券详情失败");
            }
            Boolean success = jsonObject.getBoolean("success");
            if (success == null || !success) {
                String message = jsonObject.getString("message");
                return R.fail(StrUtil.isNotBlank(message) ? message : "查询分享优惠券详情失败");
            }
            JSONObject resultData = jsonObject.getJSONObject("result");
            if (resultData == null) {
                return R.fail("分享优惠券详情数据为空");
            }
            ShareVolutionDetailVO detailVO = JSON.parseObject(resultData.toJSONString(), ShareVolutionDetailVO.class);
            return R.ok(detailVO);
        } catch (Exception e) {
            log.error("调用远程接口异常, shareVolutionId: {}", shareVolutionId, e);
            throw new ServiceException("查询分享优惠券详情异常: " + e.getMessage());
        }
    }
}