package com.jeequan.jeepay.thirdparty.device.speaker.bsjSpeaker;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.device.ISpeakerService;
import com.jeequan.jeepay.core.model.device.BsjParams;
import com.jeequan.jeepay.core.model.device.PayOrderInfo4Device;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/*
* 云喇叭厂商： 博实结
*
* @author zx
*
* @date 2021/6/8 18:10
*/
@Slf4j
@Service
public class BsjSpeakerService implements ISpeakerService {

    private static final String REQ_URL = "https://ioe.car900.com/v1/openApi/dev/controlDevice.json";

    @Override
    public void send(JSONObject deviceParams, PayOrderInfo4Device payOrderInfo) throws BizException {
        sendCustomMsg(deviceParams, payOrderInfo);
    }

    @Override
    public void sendCustomMsg(JSONObject deviceParams, PayOrderInfo4Device payOrderInfo) {

        BsjParams bsjParams = getBsjParams(deviceParams);
        JSONObject reqParams = BsjUtil.getSpeakData(bsjParams.getProviderParams().getCustomContent(), payOrderInfo);

        JSONObject resJSON = BsjUtil.get(REQ_URL, bsjParams, reqParams);

        if (resJSON == null) {
            throw new BizException("请求失败");
        }
        if (resJSON.getIntValue("code") != 0) {
            throw new BizException(resJSON.getString("msg"));
        }
    }

    private BsjParams getBsjParams(JSONObject deviceParams) {
        JSONObject bsjJSON = new JSONObject();
        bsjJSON.put("providerParams", JSON.parseObject(deviceParams.getString("providerParams")));
        bsjJSON.put("deviceParams", JSON.parseObject(deviceParams.getString("deviceParams")));

        return JSON.parseObject(bsjJSON.toJSONString(), BsjParams.class);
    }

}
