package com.kym.service.awoara;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.kym.common.exception.BusinessException;
import com.kym.common.utils.CommUtil;
import com.kym.service.awoara.entity.ApiList;
import com.kym.service.awoara.entity.Config;
import com.kym.service.awoara.entity.MethodHelp;
import com.kym.service.awoara.entity.event.OrderInfo;
import com.kym.service.awoara.entity.response.AwoaraResponse;
import com.kym.service.awoara.entity.response.CreateOrder;
import com.kym.service.awoara.entity.response.HardwareInfo;
import com.kym.service.awoara.entity.response.State;
import com.kym.service.mq.AliyunLotClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

import static cn.hutool.http.HttpStatus.HTTP_OK;

/**
 * 石斑鱼主板API
 *
 * @author skyline
 */
@Service
@Slf4j
public class AwoaraServiceImpl implements AwoaraService {


    /**
     * BASE64解码器
     */
    private static final Base64.Decoder DECODER = Base64.getDecoder();

    static <T> T doRequest(String productKey, String deviceName, String params, TypeReference<AwoaraResponse<T>>... typeReference) {
        try {
            var response = AliyunLotClient.rRpc(productKey, deviceName, params);
            AwoaraResponse<T> res;
            if (HTTP_OK == response.getStatusCode()) {
                if (CommUtil.isNotEmptyAndNull(typeReference)) {
                    res = JSONObject.parseObject(new String(DECODER.decode(response.getBody().payloadBase64Byte), StandardCharsets.UTF_8), typeReference[0]);
                    log.debug("AliyunLot返回结果：{}", res);
                } else {
                    res = JSONObject.parseObject(new String(DECODER.decode(response.getBody().payloadBase64Byte), StandardCharsets.UTF_8), AwoaraResponse.class);
                }
                if (HTTP_OK == res.getCode()) {
                    return res.getData();
                } else {
                    log.error("AliyunLot响应异常:{}", res);
                    throw new BusinessException("AliyunLot响应异常");
                }
            } else {
                log.error("AliyunLot响应码:{}", response.getStatusCode());
                throw new BusinessException("AliyunLot响应异常");
            }
        } catch (Exception e) {
            log.error("AliyunLot请求异常:{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    @Override
    public ApiList help(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "help",
                    "params": []
                }
                """;
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<ApiList>>() {
        });
    }

    @Override
    public MethodHelp methodHelp(String productKey, String deviceName, String method) {
        var params = """
                {
                    "version": "2.0",
                    "method": "help",
                    "params": {
                        "method": "%s"
                     }
                }
                """.formatted(method);
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<MethodHelp>>() {
        });

    }

    @Override
    public void showMsgbox(String productKey, String deviceName, String title, String content, int seconds) {
        var params = """
                {
                    "version": "2.0",
                        "method": "show_msgbox",
                        "params": {
                            "title": "%s",
                            "content": "%s",
                            "seconds": %d
                        }
                }
                """.formatted(title, content, seconds);

        doRequest(productKey, deviceName, params, null);
    }

    @Override
    public void hideMsgbox(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "hide_msgbox",
                    "params": []
                }
                """;
        doRequest(productKey, deviceName, params, null);
    }

    @Override
    public void reboot(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "reboot",
                    "params": []
                }
                """;
        doRequest(productKey, deviceName, params, null);
    }

    @Override
    public State queryState(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "query_state",
                    "params": []
                }
                """;
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<State>>() {
        });
    }

    @Override
    public HardwareInfo queryHardwareInfo(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "query_hardware_info",
                    "params": []
                }
                """;
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<HardwareInfo>>() {
        });
    }

    @Override
    public CreateOrder createOrder(String productKey, String deviceName, String orderId, String memberName, int memberBalance, int memberDiscount, int prepayMoney) {
        var params = """
                {
                    "version": "2.0",
                    "method": "create_order",
                    "params": {
                        "order_id": "%s",
                        "member_name": "%s",
                        "member_balance": %d,
                        "member_discount": %d,
                        "prepay_money": %d
                    }
                }
                """.formatted(orderId, memberName, memberBalance, memberDiscount, prepayMoney);
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<CreateOrder>>() {
        });
    }

    @Override
    public void closeOrder(String productKey, String deviceName, String orderId) {
        var params = """
                {
                    "version": "2.0",
                    "method": "close_order",
                    "params": {
                        "order_id": "%s"
                     }
                }
                """.formatted(orderId);
        doRequest(productKey, deviceName, params, null);
    }
    @Override
    public void forceCloseOrder(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "close_order",
                    "params": {
                        "force_close": 1
                     }
                }
                """;
        doRequest(productKey, deviceName, params, null);
    }

    @Override
    public OrderInfo queryOrder(String productKey, String deviceName, String orderId) {
        var params = """
                {
                    "version": "2.0",
                    "method": "query_order",
                    "params": {
                        "order_id": "%s"
                     }
                }
                """.formatted(orderId);
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<OrderInfo>>() {
        });
    }

    @Override
    public Config readConfig(String productKey, String deviceName) {
        var params = """
                {
                    "version": "2.0",
                    "method": "read_config",
                    "params": []
                }
                """;
        return doRequest(productKey, deviceName, params, new TypeReference<AwoaraResponse<Config>>() {
        });
    }

    @Override
    public void writeConfig(String productKey, String deviceName, Config config) {
        var params = """
                {
                    "version": "2.0",
                    "method": "write_config",
                    "params": {
                        "version":2,
                        "maintenance_mode": 0,
                        "user_message.1": "超级进化车生活",
                        "user_message.2": "客服电话：13018061579",
                        "sensor_water": 0,
                        "price_space": 10,
                        "price_water": 150,
                        "price_foam": 250,
                        "price_tap": 100,
                        "price_cleaner": 120,
                        "price_user_ext": 100,
                        "idle_timeout": 1200,
                        "operation_timeout": 3600,
                        "quick_open_money": 2000,
                        "work_mode": 1,
                        "work_time_period.1": "00:00 - 00:00",
                        "work_time_period.2": "00:00 - 00:00",
                        "light_mode": 2,
                        "light_time_period.1": "00:00 - 05:30",
                        "light_time_period.2": "18:30 - 00:00",
                        "sound_volume": 70,
                        "screen_type": 0,
                        "video_source": 0,
                        "video_play_delay": 20,
                        "work_light_delay": 30,
                        "bill_delay": 60,
                        "notice_throshold_idle": 300,
                        "notice_throshold_operation": 600,
                        "motor_mode": 0
                     }
                }
                """;
        doRequest(productKey, deviceName, params, null);
    }
}
