package com.multictrl.modules.business.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.multictrl.common.exception.RenException;
import com.multictrl.common.utils.CacheUtils;
import com.multictrl.common.utils.DJIErrorCodeUtils;
import com.multictrl.common.utils.Utils;
import com.multictrl.modules.business.dto.error.DJICloudErrorCode;
import com.multictrl.modules.business.service.DockSetService;
import com.multictrl.modules.business.service.MqttPushService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 机场属性设置
 *
 * @author Sdy
 * @since 1.0.0 2026/6/17
 */
@Service
@RequiredArgsConstructor
public class DockSetServiceImpl implements DockSetService {
    private final MqttPushService mqttPushService;

    @Override
    public String setDockProperty(String dockSn, String property, Object value) {
        JSONObject message = new JSONObject();
        JSONObject data = new JSONObject();
        JSONObject state = new JSONObject();
        state.set("state", value);
        data.set(property, state);
        message.set("data", data);
        String bid = IdUtil.randomUUID();
        String tid = IdUtil.randomUUID();
        message.set("bid", bid);
        message.set("tid", tid);
        message.set("timestamp", System.currentTimeMillis());
        mqttPushService.pushMessageByClient1("thing/product/" + dockSn + "/property/set", message.toString());
        String key = bid + "_" + tid;
        int tryCount = 100;
        while (tryCount-- > 0) {
            Object object = CacheUtils.get(key);
            if (object != null) {
                CacheUtils.delete(key);
                JSONObject dataJson = (JSONObject) object;
                JSONObject propertyObject = dataJson.getJSONObject(property);
                JSONObject stateObject = propertyObject.getJSONObject("state");
                Integer result = stateObject.getInt("result");
                if (result == 0) {
                    return "执行成功";
                } else if (result == 1) {
                    throw new RenException("执行失败");
                } else if (result == 2) {
                    throw new RenException("执行超时");
                } else {
                    String msg = "执行失败";
                    DJICloudErrorCode errorMsg = DJIErrorCodeUtils.getErrorMsg(String.valueOf(result));
                    if (errorMsg != null) {
                        msg = errorMsg.toString();
                    }
                    throw new RenException(msg);
                }
            }
            Utils.sleep(100);
        }
        throw new RenException("执行超时");
    }

}
