package com.bonait.bnframework.common.iot;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.alink.dm.api.BaseInfo;
import com.aliyun.alink.dm.api.DeviceInfo;
import com.aliyun.alink.dm.api.IThing;
import com.aliyun.alink.linkkit.api.LinkKit;
import com.aliyun.alink.linksdk.tmp.api.InputParams;
import com.aliyun.alink.linksdk.tmp.api.OutputParams;
import com.aliyun.alink.linksdk.tmp.device.payload.ValueWrapper;
import com.aliyun.alink.linksdk.tmp.devicemodel.Arg;
import com.aliyun.alink.linksdk.tmp.devicemodel.Event;
import com.aliyun.alink.linksdk.tmp.devicemodel.Property;
import com.aliyun.alink.linksdk.tmp.devicemodel.Service;
import com.aliyun.alink.linksdk.tmp.listener.IPublishResourceListener;
import com.aliyun.alink.linksdk.tmp.listener.ITResRequestHandler;
import com.aliyun.alink.linksdk.tmp.listener.ITResResponseCallback;
import com.aliyun.alink.linksdk.tmp.utils.ErrorInfo;
import com.aliyun.alink.linksdk.tmp.utils.GsonUtils;
import com.aliyun.alink.linksdk.tmp.utils.TmpConstant;
import com.aliyun.alink.linksdk.tools.AError;
import com.bonait.bnframework.MainApplication;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.iot.manager.IDemoCallback;
import com.bonait.bnframework.common.iot.manager.InitManager;
import com.bonait.bnframework.common.iot.mode.AppLog;
import com.bonait.bnframework.common.iot.mode.DeviceInfoData;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class AliyunIOTManager {

    //region 变量
    private static final String TAG = "阿里云";
    /**
     * 判断是否初始化完成
     * 未初始化完成，所有和云端的长链通信都不通
     */
    public static boolean isInitDone = false;
    public static boolean userDevInfoError = false;
    public static DeviceInfoData mDeviceInfoData = null;
    public static String productKey = null, deviceName = null, deviceSecret = null, productSecret = null,
            password = null, username = null, clientId = null, deviceToken = null, mqttHost = null, instanceId = null;
    private String registerType = null;
    private final static int DEF_VALUE = Integer.MIN_VALUE;
    final static Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
    private Map<String, ValueWrapper> reportData = null;
    private boolean isSubDev = false;
    private final static String SERVICE_SET = "set";
    private final static String SERVICE_GET = "get";
    //endregion

    //region 单例
    private static AliyunIOTManager instance;

    private AliyunIOTManager() {
        reportData =new HashMap<String, ValueWrapper>();
        // 从 raw 读取指定配置文件
        String testData = getFromRaw();
        // 解析数据
        getDeviceInfoFrom(testData);
    }

    public static synchronized AliyunIOTManager getInstance() {
        if (instance == null) {
            instance = new AliyunIOTManager();
        }
        return instance;
    }
    //endregion

    //region 公有

    /**
     * 打开设备
     */
    public void OpenDev(Context context) {
        try {
            if (userDevInfoError) {
                ToastUtils.warning("三元组文件格式不正确，请重新检查格式");
            } else {
                if (!TextUtils.isEmpty(deviceSecret) || !TextUtils.isEmpty(password) || !TextUtils.isEmpty(deviceToken)) {
                    connect(context);
                } else {
                    if (!userDevInfoError) {
                        ToastUtils.warning("三元组信息无效，请重新填写");
                    }
                    userDevInfoError = true;
                }
            }
        } catch (Exception ex) {

        }
    }

    /**
     * 耗时操作，建议放到异步线程
     * 反初始化同步接口
     */
    public void CloseDev() {
        AppLog.d(TAG, "deinit");
        isInitDone = false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 同步接口
                LinkKit.getInstance().deinit();
                ToastUtils.info("关闭IOT成功");
            }
        }).start();
    }

    /**
     * 获取设备属性
     *
     * @return
     */
    public List<Property> GetProperty() {
        return LinkKit.getInstance().getDeviceThing().getProperties();
    }

    /**
     * 上报属性
     * @param property
     */
    public void UploadProperty(Property property, String val) {
        try {
            if (property == null) {
                showToast("选择的property为空");
                return;
            }
            String value = val;
            if (property == null || value == null || property.getIdentifier() == null) {
                showToast("属性或值为空");
                return;
            }
            if (property.getDataType() == null) {
                showToast("属性类型为空");
                return;
            }
            if (TmpConstant.TYPE_VALUE_INTEGER.equals(property.getDataType().getType())) {
                int parseData = getInt(value);
                if (parseData != DEF_VALUE) {
                    report(property.getIdentifier(), new ValueWrapper.IntValueWrapper(parseData));
                } else {
                    showToast("数据格式不对");
                }
                return;
            }
            if (TmpConstant.TYPE_VALUE_FLOAT.equals(property.getDataType().getType())) {
                Double parseData = getDouble(value);
                if (parseData != null) {
                    report(property.getIdentifier(), new ValueWrapper.DoubleValueWrapper(parseData));
                } else {
                    showToast("数据格式不对");
                }
                return;
            }
            if (TmpConstant.TYPE_VALUE_DOUBLE.equals(property.getDataType().getType())) {
                Double parseData = getDouble(value);
                if (parseData != null) {
                    report(property.getIdentifier(), new ValueWrapper.DoubleValueWrapper(parseData));
                } else {
                    showToast("数据格式不对");
                }
                return;
            }
            if (TmpConstant.TYPE_VALUE_BOOLEAN.equals(property.getDataType().getType())) {
                int parseData = getInt(value);
                if (parseData == 0 || parseData == 1) {
                    report(property.getIdentifier(), new ValueWrapper.BooleanValueWrapper(parseData));
                } else {
                    showToast("数据格式不对");
                }
                return;
            }
            if (TmpConstant.TYPE_VALUE_TEXT.equals(property.getDataType().getType())) {
                report(property.getIdentifier(), new ValueWrapper.StringValueWrapper(value));
                return;
            }
            if (TmpConstant.TYPE_VALUE_DATE.equals(property.getDataType().getType())) {
                report(property.getIdentifier(), new ValueWrapper.DateValueWrapper(value));
                return;
            }
            if (TmpConstant.TYPE_VALUE_ENUM.equalsIgnoreCase(property.getDataType().getType())) {
                report(property.getIdentifier(), new ValueWrapper.EnumValueWrapper(getInt(value)));
                return;
            }
            if (TmpConstant.TYPE_VALUE_ARRAY.equalsIgnoreCase(property.getDataType().getType())) {
                ValueWrapper.ArrayValueWrapper arrayValueWrapper = GsonUtils.fromJson(value, new TypeToken<ValueWrapper>() {
                }.getType());
                report(property.getIdentifier(), arrayValueWrapper);
                return;
            }
            // 结构体数据解析  结构体不支持嵌套结构体和数组
            if (TmpConstant.TYPE_VALUE_STRUCT.equals(property.getDataType().getType())) {
                try {
                    List<Map<String, Object>> specsList = (List<Map<String, Object>>) property.getDataType().getSpecs();
                    if (specsList == null || specsList.size() == 0) {
                        showToast("云端创建的struct结构为空，不上传任何值。");
                        return;
                    }
                    JSONObject dataJson = JSONObject.parseObject(value);
                    Map<String, ValueWrapper> dataMap = new HashMap<>();
                    Map<String, Object> specsItem = null;
                    for (int i = 0; i < specsList.size(); i++) {
                        specsItem = specsList.get(i);
                        if (specsItem == null) {
                            continue;
                        }
                        String idKey = (String) specsItem.get("identifier");
                        String dataType = (String) ((Map) specsItem.get("dataType")).get("type");
                        if (idKey != null && dataJson.containsKey(idKey) && dataType != null) {
                            ValueWrapper valueItem = null;
                            if ("int".equals(dataType)) {
                                valueItem = new ValueWrapper.IntValueWrapper(getInt(String.valueOf(dataJson.get(idKey))));
                            } else if ("text".equals(dataType)) {
                                valueItem = new ValueWrapper.StringValueWrapper((String) dataJson.get(idKey));
                            } else if ("float".equals(dataType) || "double".equals(dataType)) {
                                valueItem = new ValueWrapper.DoubleValueWrapper(getDouble(String.valueOf(dataJson.get(idKey))));
                            } else if ("bool".equals(dataType)) {
                                valueItem = new ValueWrapper.BooleanValueWrapper(getInt(String.valueOf(dataJson.get(idKey))));
                            } else if ("date".equals(dataType)) {
                                if (isValidInt(String.valueOf(dataJson.get(idKey)))) {
                                    valueItem = new ValueWrapper.DateValueWrapper(String.valueOf(dataJson.get(idKey)));
                                } else {
                                    showToast("数据格式不对");
                                }
                            } else if ("enum".equals(dataType)) {
                                valueItem = new ValueWrapper.EnumValueWrapper(getInt(String.valueOf(dataJson.get(idKey))));
                            } else {
                                showToast("数据格式不支持");
                            }
                            if (valueItem != null) {
                                dataMap.put(idKey, valueItem);
                            }
                        }
                    }

                    report(property.getIdentifier(), new ValueWrapper.StructValueWrapper(dataMap));
                } catch (Exception e) {
                    showToast("数据格式不正确");
                }
                return;
            }
            showToast("该类型Demo暂不支持，用户可参照其他类型代码示例开发支持。");
        } catch (Exception e) {
            showToast("数据格式不对");
            e.printStackTrace();
        }
    }

    /**
     * 获取设备服务,
     *
     * @return
     */
    public List<Service> GetService() {
        return LinkKit.getInstance().getDeviceThing().getServices();
    }

    /**
     * 监听服务
     */
    public void MonitorService()
    {
        List<Service> services= LinkKit.getInstance().getDeviceThing().getServices();
        for (Service item:services)
        {
            LinkKit.getInstance().getDeviceThing().setServiceHandler(item.getIdentifier(),itResRequestHandler);
        }
    }

    /**
     * 获取设备事件
     *
     * @return
     */
    public List<Event> GetEvents() {
        return LinkKit.getInstance().getDeviceThing().getEvents();
    }

    /**
     * 上报事件通知
     * @param event
     * @param val
     */
    public void UploadEvents(Event event, String val) {
        if (event == null) {
            showToast("事件不能为空");
            return;
        }

        HashMap<String, ValueWrapper> hashMap = new HashMap<>();
        try {
            String mapEventData = val;
            JSONObject object = JSONObject.parseObject(mapEventData);
            if (object == null){
                showToast("参数不能为空");
                return;
            }
            if (event.getOutputData() != null) {
                for (int i = 0; i < event.getOutputData().size(); i++) {
                    Arg arg = event.getOutputData().get(i);
                    if (arg == null || arg.getDataType() == null || arg.getIdentifier() == null){
                        continue;
                    }
                    String idnValue = String.valueOf(object.get(arg.getIdentifier()));
                    if (idnValue == null || object.get(arg.getIdentifier()) == null){
                        continue;
                    }
                    if (TmpConstant.TYPE_VALUE_INTEGER.equals(arg.getDataType().getType())) {
                        int parseData = getInt(idnValue);
                        if (parseData != DEF_VALUE) {
                            hashMap.put(arg.getIdentifier(), new ValueWrapper.IntValueWrapper(parseData));
                        } else {
                            showToast("数据格式不对");
                            break;
                        }
                        continue;
                    }
                    if (TmpConstant.TYPE_VALUE_FLOAT.equals(arg.getDataType().getType())) {
                        Double parseData = getDouble(idnValue);
                        if (parseData != null) {
                            hashMap.put(arg.getIdentifier(), new ValueWrapper.DoubleValueWrapper(parseData));
                        } else {
                            showToast("数据格式不对");
                            break;
                        }
                        continue;
                    }
                    if (TmpConstant.TYPE_VALUE_DOUBLE.equals(arg.getDataType().getType())) {
                        Double parseData = getDouble(idnValue);
                        if (parseData != null) {
                            hashMap.put(arg.getIdentifier(), new ValueWrapper.DoubleValueWrapper(parseData));
                        } else {
                            showToast("数据格式不对");
                            break;
                        }
                        continue;
                    }
                    if (TmpConstant.TYPE_VALUE_BOOLEAN.equals(arg.getDataType().getType())) {
                        int parseData = getInt(idnValue);
                        if (parseData == 0 || parseData == 1) {
                            hashMap.put(arg.getIdentifier(), new ValueWrapper.BooleanValueWrapper(parseData));
                        } else {
                            showToast("数据格式不对");
                            break;
                        }
                        continue;
                    }
                    if (TmpConstant.TYPE_VALUE_TEXT.equals(arg.getDataType().getType())) {
                        hashMap.put(arg.getIdentifier(), new ValueWrapper.StringValueWrapper(idnValue));
                        continue;
                    }
                    if (TmpConstant.TYPE_VALUE_DATE.equals(arg.getDataType().getType())) {
                        hashMap.put(arg.getIdentifier(), new ValueWrapper.DateValueWrapper(idnValue));
                        continue;
                    }
                    if(TmpConstant.TYPE_VALUE_ENUM.equalsIgnoreCase(arg.getDataType().getType())){
                        hashMap.put(arg.getIdentifier(),new ValueWrapper.EnumValueWrapper(getInt(idnValue)));
                        continue;
                    }
                    if(TmpConstant.TYPE_VALUE_ARRAY.equalsIgnoreCase(arg.getDataType().getType())){
                        ValueWrapper.ArrayValueWrapper arrayValueWrapper = GsonUtils.fromJson(idnValue,new TypeToken<ValueWrapper>(){}.getType());
                        hashMap.put(arg.getIdentifier(),arrayValueWrapper);
                        continue;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("数据格式错误");
            return;
        }
        try {
            OutputParams params = new OutputParams(hashMap);
            if (!isSubDev) {
                LinkKit.getInstance().getDeviceThing().thingEventPost(event.getIdentifier(), params, resourceListener);
            } else {
//                IThing thing = LinkKit.getInstance().getGateway().getSubDeviceThing(mBaseInfo).first;
//                if (thing == null){
//                    showToast("子设备当前状态不支持");
//                    return;
//                }
//                thing.thingEventPost(event.getIdentifier(), params, resourceListener);
            }
        } catch (Exception e) {
            e.printStackTrace();
            showToast("上报失败 " + e);
        }
    }
    //endregion

    //region 私有

    /**
     * 初始化建联
     * 如果初始化建联失败，需要用户重试去完成初始化，并确保初始化成功。如应用启动的时候无网络，导致失败，可以在网络可以的时候再次执行初始化，成功之后不需要再次执行。
     * 初始化成功之后，如果因为网络原因连接断开了，用户不需要执行初始化建联操作，SDK会处理建联。
     * <p>
     * onError 初始化失败
     * onInitDone 初始化成功
     * <p>
     * SDK 支持以userName+password+clientId 的方式登录（不推荐，建议使用三元组建联）
     * 设置如下参数，InitManager.init的时候 deviceSecret, productSecret 可以不填
     * MqttConfigure.mqttUserName = username;
     * MqttConfigure.mqttPassWord = password;
     * MqttConfigure.mqttClientId = clientId;
     */
    private void connect(Context context) {
        AppLog.d(TAG, "connect() called");
        InitManager.init(context, productKey, deviceName, deviceSecret, productSecret, mqttHost, new IDemoCallback() {
            @Override
            public void onError(AError aError) {
                AppLog.d(TAG, "onError() called with: aError = [" + InitManager.getAErrorString(aError) + "]");
                // 初始化失败，初始化失败之后需要用户负责重新初始化
                // 如一开始网络不通导致初始化失败，后续网络恢复之后需要重新初始化
                if (aError != null) {
                                    AppLog.d(TAG, "初始化IOT失败，错误信息：" + aError.getCode() + "-" + aError.getSubCode() + ", " + aError.getMsg());
                   // ToastUtils.error("初始化IOT失败，错误信息：" + aError.getCode() + "-" + aError.getSubCode() + ", " + aError.getMsg());
                } else {
                                    AppLog.d(TAG, "初始化IOT失败");
                    //ToastUtils.error("初始化IOT失败");
                }
            }

            @Override
            public void onInitDone(Object data) {
                AppLog.d(TAG, "初始化IOT成功: data = [" + data + "]");
                isInitDone = true;

                MonitorService();
            }
        });
    }

    /**
     * 注意：该场景只适合于设备未激活的场景
     * 验证一型一密 需要以下步骤：
     * 1.云端创建产品，开启产品的动态注册功能；
     * 2.创建一个设备，在文件中(raw/deviceinfo)填写改设备信息 productKey，deviceName， productSecret;
     * 3.通过这三个信息可以去云端动态拿到deviceSecret，并建立长连接；
     *
     * @return
     */
    public String getFromRaw() {
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            inputReader = new InputStreamReader(MainApplication.getContext().getResources().openRawResource(R.raw.deviceinfo));
            bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufReader != null) {
                    bufReader.close();
                }
                if (inputReader != null) {
                    inputReader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 解析数据
     *
     * @param testData
     */
    private void getDeviceInfoFrom(String testData) {
        AppLog.d(TAG, "getDeviceInfoFrom() called with: testData = [" + testData + "]");
        try {
            if (testData == null) {
                AppLog.e(TAG, "getDeviceInfoFrom: data empty.");
                userDevInfoError = true;
                return;
            }
            Gson mGson = new Gson();
            DeviceInfoData deviceInfoData = mGson.fromJson(testData, DeviceInfoData.class);
            if (deviceInfoData == null) {
                AppLog.e(TAG, "getDeviceInfoFrom: file format error.");
                userDevInfoError = true;
                return;
            }
            AppLog.d(TAG, "getDeviceInfoFrom deviceInfoData=" + deviceInfoData);
            if (checkValid(deviceInfoData)) {
                mDeviceInfoData = new DeviceInfoData();
                mDeviceInfoData.productKey = deviceInfoData.productKey;
                mDeviceInfoData.productSecret = deviceInfoData.productSecret;
                mDeviceInfoData.deviceName = deviceInfoData.deviceName;
                mDeviceInfoData.deviceSecret = deviceInfoData.deviceSecret;
                mDeviceInfoData.username = deviceInfoData.username;
                mDeviceInfoData.password = deviceInfoData.password;
                mDeviceInfoData.clientId = deviceInfoData.clientId;
                mDeviceInfoData.deviceToken = deviceInfoData.deviceToken;
                mDeviceInfoData.registerType = deviceInfoData.registerType;
                mDeviceInfoData.mqttHost = deviceInfoData.mqttHost;
                mDeviceInfoData.instanceId = deviceInfoData.instanceId;

                userDevInfoError = false;

                mDeviceInfoData.subDevice = new ArrayList<>();
                if (deviceInfoData.subDevice == null) {
                    AppLog.d(TAG, "getDeviceInfoFrom: subDevice empty..");
                    return;
                }
                for (int i = 0; i < deviceInfoData.subDevice.size(); i++) {
                    if (checkValid(deviceInfoData.subDevice.get(i))) {
                        mDeviceInfoData.subDevice.add(deviceInfoData.subDevice.get(i));
                    } else {
                        AppLog.d(TAG, "getDeviceInfoFrom: subDevice info invalid. discard.");
                    }
                }

                productKey = mDeviceInfoData.productKey;
                deviceName = mDeviceInfoData.deviceName;
                deviceSecret = mDeviceInfoData.deviceSecret;
                productSecret = mDeviceInfoData.productSecret;
                password = mDeviceInfoData.password;
                username = mDeviceInfoData.username;
                clientId = mDeviceInfoData.clientId;
                deviceToken = mDeviceInfoData.deviceToken;
                registerType = mDeviceInfoData.registerType;
                mqttHost = mDeviceInfoData.mqttHost;
                instanceId = mDeviceInfoData.instanceId;

                AppLog.d(TAG, "getDeviceInfoFrom: final data=" + mDeviceInfoData);
            } else {
                AppLog.e(TAG, "res/raw/deviceinfo error.");
                userDevInfoError = true;
            }

        } catch (Exception e) {
            AppLog.e(TAG, "getDeviceInfoFrom: e", e);
            userDevInfoError = true;
        }

    }

    private boolean checkValid(BaseInfo baseInfo) {
        if (baseInfo == null) {
            return false;
        }
        if (TextUtils.isEmpty(baseInfo.productKey) || TextUtils.isEmpty(baseInfo.deviceName)) {
            return false;
        }
        if (baseInfo instanceof DeviceInfoData) {
            if (TextUtils.isEmpty(((DeviceInfo) baseInfo).productSecret) && TextUtils.isEmpty(((DeviceInfo) baseInfo).deviceSecret) && TextUtils.isEmpty(((DeviceInfoData) baseInfo).password)) {
                return false;
            }
        }
        return true;
    }

    private static void showToast(String message)
    {
        ToastUtils.info(message);
    }

    private boolean isValidDouble(String value) {
        if (TextUtils.isEmpty(value)) {
            return false;
        }
        try {
            if (pattern != null && pattern.matcher(value) != null) {
                if (pattern.matcher(value).matches()) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private Double getDouble(String value) {
        if (isValidDouble(value)) {
            return Double.parseDouble(value);
        }
        return null;
    }

    private boolean isValidInt(String value) {
        return !TextUtils.isEmpty(value);
    }

    private int getInt(String value) {
        if (isValidInt(value)) {
            try {
                return Integer.parseInt(value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return DEF_VALUE;
    }

    private void report(String identifier, ValueWrapper valueWrapper) {
        reportData.clear();
        Map<String, ValueWrapper> reportData  = new HashMap<>();
        /**
         * 物模型默认的模块中,属性的identifer是不用加前缀的. 比如名为lightSwitch的属性, identifer就是lightSwitch
         * 如果是用户自定义的模块,属性的identifer前要加"模块名:"这样的前缀. 比如myBlock模块中的lightSwitch属性,
         * identifer就要写成"myBlock:lightSwitch"
         */
        reportData.put(identifier, valueWrapper);
        if (!isSubDev) {
            try {
                LinkKit.getInstance().getDeviceThing().thingPropertyPost(reportData, resourceListener);
            } catch (Exception e) {
                e.printStackTrace();
                showToast("上报失败 " + e);
            }
        } else {
            try {
//                IThing thing = LinkKit.getInstance().getGateway().getSubDeviceThing(mBaseInfo).first;
//                if (thing == null){
//                    showToast("子设备当前状态不支持");
//                    return;
//                }
//                thing.thingPropertyPost(reportData, resourceListener);
            } catch (Exception e) {
                e.printStackTrace();
                showToast("上报失败 " + e);
            }
        }
    }

    /**
     * 上报返回数据
     */
    private static IPublishResourceListener resourceListener = new IPublishResourceListener() {
        @Override
        public void onSuccess(String alinkId, Object o) {
            AppLog.d(TAG, "onSuccess() called with: alinkId = [" + alinkId + "], o = [" + o + "]");
            showToast("设备状态上报上行成功（code=200），用户可以根据云端返回的data判断是否有不符合的属性上报");
        }

        @Override
        public void onError(String alinkId, AError aError) {
            AppLog.d(TAG, "onError() called with: alinkId = [" + alinkId + "], aError = [" + aError + "]");
            showToast("设备上报状态失败");
        }
    };

    /**
     * 接收到服务
     */
    private static ITResRequestHandler itResRequestHandler=new ITResRequestHandler() {
        @Override
        public void onProcess(String identify, Object result, ITResResponseCallback itResResponseCallback) {
            Log.d(TAG, "onProcess() called with: s = [" + identify + "], o = [" + result + "], itResResponseCallback = [" + itResResponseCallback + "]");
            showToast("收到异步服务调用 " + identify);
            if (SERVICE_SET.equals(identify)) {
                // TODO  用户按照真实设备的接口调用  设置设备的属性
                // 设置完真实设备属性之后，上报设置完成的属性值
                // 用户根据实际情况判断属性是否设置成功 这里测试直接返回成功
                boolean isSetPropertySuccess = true;
                if (isSetPropertySuccess){
                    if (result instanceof InputParams) {
                        Map<String, ValueWrapper> data = (Map<String, ValueWrapper>) ((InputParams) result).getData();
//                        data.get()

                        // 响应云端 接收数据成功
                        itResResponseCallback.onComplete(identify, null, null);
                    } else {
                        itResResponseCallback.onComplete(identify, null, null);
                    }
                    //updatePropertyValue((Property) mPropertySpinner.getSelectedItem());
                } else {
                    AError error = new AError();
                    error.setCode(100);
                    error.setMsg("setPropertyFailed.");
                    itResResponseCallback.onComplete(identify, new ErrorInfo(error), null);
                }

            } else if (SERVICE_GET.equals(identify)){
                //  初始化的时候将默认值初始化传进来，物模型内部会直接返回云端缓存的值

            }else
            {
                OutputParams outputParams = new OutputParams();
//                    outputParams.put("op", new ValueWrapper.IntValueWrapper(20));
                itResResponseCallback.onComplete(identify,null, outputParams);
            }
        }

        @Override
        public void onSuccess(Object o, OutputParams outputParams) {
            showToast("注册服务成功");
        }

        @Override
        public void onFail(Object o, ErrorInfo errorInfo) {
            showToast("注册服务失败");
        }
    };
    //endregion
}