package com.mvc.iot.aep;

import com.alibaba.fastjson.JSONObject;
import com.ctg.ag.sdk.biz.AepDeviceCommandClient;
import com.ctg.ag.sdk.biz.AepDeviceManagementClient;
import com.ctg.ag.sdk.biz.AepNbDeviceManagementClient;
import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CancelCommandResponse;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandRequest;
import com.ctg.ag.sdk.biz.aep_device_command.CreateCommandResponse;
import com.ctg.ag.sdk.biz.aep_nb_device_management.DeleteDeviceByImeiRequest;
import com.ctg.ag.sdk.biz.aep_nb_device_management.DeleteDeviceByImeiResponse;
import com.mvc.iot.aep.config.AepConfig;
import com.mvc.iot.aep.model.AepCommandBodyModel;
import com.mvc.iot.aep.model.AepDeviceApiModel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import com.ctg.ag.sdk.biz.aep_device_management.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 电信AEP平台API处理
 * 基于SDK
 */
@Component
public class AepApiHelper {
    @Resource
    private AepConfig aepConfig;

    public static final String RESPONSE_MSG_SUCC = "ok";//响应结果成功的返回值

    /**
     * 新增设备
     *
     * @param model
     * @return
     * @throws Exception
     */
    public CreateDeviceResponse createDevice(AepDeviceApiModel model) throws Exception {
        AepDeviceManagementClient client = AepDeviceManagementClient.newClient()
                .appKey(aepConfig.getAppKey()).appSecret(aepConfig.getAppSecret())
                .build();

        CreateDeviceRequest request = new CreateDeviceRequest();
        // set your request params here
        request.setParamMasterKey(aepConfig.getMasterKey());    // single value
        String body = JSONObject.toJSONString(model);
        request.setBody(body.getBytes());    //具体格式见前面请求body说明
        CreateDeviceResponse response = client.CreateDevice(request);
        System.out.println(response);
        client.shutdown();
        return response;
        //返回结果示例
        /*BaseApiResponse: statusCode=200 , contentType=application/json;charset=utf-8 , message=OK , headers={Transfer-Encoding=chunked, x-ag-timestamp=1728866208066, x-ag-route-cost=184, Server=elb, Connection=keep-alive, x-ag-proxied=true, x-ag-proxy-cost=94, Date=Mon, 14 Oct 2024 00:36:48 GMT, via=Telecom API Gateway, access-control-expose-headers=x-ag-request-id, x-ag-timestamp, x-ag-proxy-cost, cache-control, Transfer-Encoding, Date, Keep-Alive, Connection, user-agent, server, via, access-control-allow-origin, x-ag-proxied, x-ag-route-cost, content-type, access-control-expose-headers, access-control-allow-origin=*, x-ag-request-id=1047964000--1939778838, cache-control=no-cache, no-store, Content-Type=application/json;charset=utf-8, user-agent=Telecom API Gateway} ,
        body=
        {
            "code": 0,
                "msg": "ok",
                "result": {
                    "deviceSn": null,
                    "deviceId": "c78d9c03e45e4357816295a11f73a01d",
                    "deviceName": "0000001849",
                    "tenantId": "2000523344",
                    "productId": 17154609,
                    "imei": "864606065659897",
                    "token": null
        }*/
    }

    /**
     * 删除设备
     *
     * @param imei
     * @throws Exception
     */
    public DeleteDeviceByImeiResponse deleteDevice(String imei) throws Exception {
        List<String> imeiList = new java.util.ArrayList<>();
        imeiList.add(imei);
        return deleteDevice(imeiList);
    }

    /**
     * 删除设备
     *
     * @param imeiList
     * @throws Exception
     */
    public DeleteDeviceByImeiResponse deleteDevice(List<String> imeiList) throws Exception {
        Map<String, Object> bodyMap = new HashMap<>();

        bodyMap.put("imeiList", imeiList);
        bodyMap.put("productId", aepConfig.getProductId());

        AepNbDeviceManagementClient client = AepNbDeviceManagementClient.newClient()
                .appKey(aepConfig.getAppKey()).appSecret(aepConfig.getAppSecret()).build();

        DeleteDeviceByImeiRequest request = new DeleteDeviceByImeiRequest();
        // set your request params here
        request.setParamMasterKey(aepConfig.getMasterKey());    // single value
        String body = JSONObject.toJSONString(bodyMap);
        request.setBody(body.getBytes());    //具体格式见前面请求body说明
        DeleteDeviceByImeiResponse response = client.DeleteDeviceByImei(request);
        System.out.println(response);
        client.shutdown();
        return response;
        //返回结果示例
        //全部成功:body={"code":0,"msg":"ok","result":null}
        //单个失败:body={"code":1127,"msg":"删除失败的设备","result":[{"imei":"864606065659897","reason":"此设备不存在"}]}
        //部分失败:body={"code":1127,"msg":"删除失败的设备","result":[{"imei":"864606065659898","reason":"此设备不存在"}]}
        //重复执行body={"code":2010115,"msg":"IMEI号864606065648668已被您注册","result":null}
    }

    public CreateCommandResponse createCommand(AepCommandBodyModel body) throws Exception {
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(aepConfig.getAppKey()).appSecret(aepConfig.getAppSecret()).build();

        CreateCommandRequest request = new CreateCommandRequest();
        // set your request params here
        request.setParamMasterKey(aepConfig.getMasterKey());    // single value
        String json = JSONObject.toJSONString(body);
        request.setBody(json.getBytes());    //具体格式见前面请求body说明
        CreateCommandResponse response = client.CreateCommand(request);
        System.out.println(response);
        /*body返回示例
        {
          "code": 0,
          "msg": "ok",
          "result": {
            "commandId": "1",
            "command": "7E7E0000000000162020E08013020002241014000111BD0800D10801D5080105AB98",
            "commandStatus": "指令已保存",
            "productId": 17154609,
            "deviceId": "31e663633bbf47ccb953a2b355a66a49",
            "imei": "861999061568318",
            "createBy": "GZ",
            "createTime": 1728885786619,
            "ttl": 7200
          }
        }
         */
        // more requests

        client.shutdown();
        return response;
    }

    /**
     * 取消命令
     *
     * @param commandId
     * @param deviceId
     * @throws Exception
     */
    public CancelCommandResponse cancleCommand(String commandId, String deviceId) throws Exception {
        AepDeviceCommandClient client = AepDeviceCommandClient.newClient()
                .appKey(aepConfig.getAppKey()).appSecret(aepConfig.getAppSecret()).build();

        Map<String, Object> body = new HashMap<>();
        body.put("commandId", commandId);
        body.put("deviceId", deviceId);
        body.put("productId", aepConfig.getProductId());

        CancelCommandRequest request = new CancelCommandRequest ();
        // set your request params here
        request.setParamMasterKey(aepConfig.getMasterKey());    // single value
        String json = JSONObject.toJSONString(body);
        request.setBody(json.getBytes());    //具体格式见前面请求body说明
        CancelCommandResponse response = client.CancelCommand(request);
        System.out.println(response);
        //body={"code":0,"msg":"指令取消成功","result":null}
        // more requests

        client.shutdown();
        return response;
    }
}
