package cn.ysk.cashier.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.mybatis.mapper.MpShopInfoMapper;
import cn.ysk.cashier.pojo.shop.TbShopInfo;
import cn.ysk.cashier.resp.PhpCommonResp;
import cn.ysk.cashier.service.ThirdPartyCouponService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class ThirdPartyCouponServiceImpl implements ThirdPartyCouponService {

    private final MpShopInfoMapper mpShopInfoMapper;
    @Value("${phpServer}")
    private String phpServerUrl;

    public ThirdPartyCouponServiceImpl(RestTemplate restTemplate, MpShopInfoMapper mpShopInfoMapper) {
        this.restTemplate = restTemplate;
        this.mpShopInfoMapper = mpShopInfoMapper;
    }
    private final RestTemplate restTemplate;

    private <T> T getData(String url, Integer shopId, Object data) {
        // 获取店铺信息
        TbShopInfo shopInfo = mpShopInfoMapper.selectById(shopId);
        if (shopInfo == null) {
            throw new BadRequestException("店铺信息不存在");
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("account", shopId.toString());

        // 构造请求实体，根据 data 是否为空设置请求体
        HttpEntity<Object> entity;
        if (data != null) {
            Map<String, Object> map = BeanUtil.beanToMap(data);
            map.put("title", shopInfo.getShopName());
            entity = new HttpEntity<>(map, headers);
        } else {
            entity = new HttpEntity<>(new HashMap<String, Object>(){{
                put("title", shopInfo.getShopName());
            }},headers);
        }

        // 发起请求
        ResponseEntity<PhpCommonResp> response = restTemplate.exchange(
                phpServerUrl + url,
                HttpMethod.POST, // 使用 POST 请求发送 body 数据
                entity,
                PhpCommonResp.class
        );

        // 处理响应
        PhpCommonResp<?> resp = response.getBody();
        if (resp == null) {
            throw new BadRequestException("请求php服务器失败");
        }
        if (!"1".equals(resp.getCode())) {
            throw new BadRequestException(resp.getMsg());
        }

        // 返回数据
        return (T) resp.getData();
    }


    @Override
    public String getBindUrl(Integer shopId) {
        return getData("/meituan/getuisdkurl", shopId, null);
    }
}
