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

import cn.hutool.core.util.IdUtil;
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.PayOrderInfo4Device;
import com.jeequan.jeepay.core.model.device.ZwParams;
import com.jeequan.jeepay.core.utils.AmountUtil;
import com.jeequan.jeepay.thirdparty.service.zw.model.request.NotifyMsgRequest;
import com.jeequan.jeepay.thirdparty.service.zw.model.response.BaseResponse;
import com.jeequan.jeepay.thirdparty.service.zw.uils.SmartLinkUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/*
 * 云喇叭厂商： 智网
 *
 * @author xiaoyu
 *
 * @date 2023/4/11 14:39
 */
@Slf4j
@Service
public class ZwSpeakerService implements ISpeakerService {

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

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

        ZwParams zwParams = getZwParams(deviceParams);

        NotifyMsgRequest request = new NotifyMsgRequest();
        request.setIndex(IdUtil.fastSimpleUUID());
        request.setSn(zwParams.getDeviceParams().getDeviceNo());
        request.setToken(zwParams.getProviderParams().getToken());

        // 会员余额支付
        if (PayOrderInfo4Device.BOARD_TYPE_MEMBER.equals(payOrderInfo.getWayCodeType())) {
            request.setMessage("会员余额支付" + AmountUtil.convertCent2Dollar(payOrderInfo.getAmount()) + "元");
        }if (PayOrderInfo4Device.BOARD_TYPE_CANCEL.equals(payOrderInfo.getWayCodeType())) {
            request.setMessage("客户取消付款" + AmountUtil.convertCent2Dollar(payOrderInfo.getAmount()) + "元");
        }else if (StringUtils.isNotBlank(zwParams.getProviderParams().getCustomContent())){
            request.setMessage(zwParams.getProviderParams().getCustomContent() + AmountUtil.convertCent2DollarShort(payOrderInfo.getAmount()+"")+ "元");
        }

        BaseResponse response = SmartLinkUtil.soundNotifyMsg(request);

        if (!response.isSuccess()) {
            throw new BizException(response.getRespMsg());
        }
    }

    private ZwParams getZwParams(JSONObject deviceParams) {
        JSONObject zwJSON = new JSONObject();
        zwJSON.put("providerParams", JSON.parseObject(deviceParams.getString("providerParams")));
        zwJSON.put("deviceParams", JSON.parseObject(deviceParams.getString("deviceParams")));

        return JSON.parseObject(zwJSON.toJSONString(), ZwParams.class);
    }

}
