/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.third.iotdevice.service.impl;

import com.alibaba.fastjson.JSON;
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.AepProductManagementClient;
import com.ctg.ag.sdk.biz.aep_device_management.*;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.constant.AepConstant;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.entity.IotDevice;
import org.springblade.third.iotdevice.entity.IotAepProduct;
import org.springblade.third.iotdevice.service.IIotAepProductService;
import org.springblade.third.iotdevice.service.IIotDeviceBasicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 *  服务实现类
 *
 * @author BladeX
 * @since 2021-07-13
 */
@Service
@Slf4j
public class IotAepDeviceServiceImpl implements IIotDeviceBasicService {

	@Autowired
	private IIotAepProductService iotAepProductService;

	@Override
	public R<JSONObject> registerDevice(IotDevice iotDevice) {
		IotAepProduct iotAepProduct = iotAepProductService.getByProductId(iotDevice.getProductId());
		Assert.hasText(iotDevice.getProductId(), "产品不存在");

		AepDeviceManagementClient client = AepDeviceManagementClient.newClient().appKey(AepConstant.APPKEY).appSecret(AepConstant.APPSECRET).build();
		CreateDeviceRequest request = new CreateDeviceRequest();
		request.setParamMasterKey(iotAepProduct.getMasterKey());

		//请求body
		JSONObject other = new JSONObject();
		other.put("autoObserver", 0);
		JSONObject data = new JSONObject();
		data.put("other", other);
		data.put("deviceName", iotDevice.getDeviceName());
		data.put("imei", iotDevice.getImei());
		data.put("operator", iotDevice.getCreateUser());
		data.put("productId", iotAepProduct.getProductId());
		request.setBody(JsonUtil.toJsonAsBytes(data));

		JSONObject responseResult = null;
		try {
			CreateDeviceResponse createDeviceResponse = client.CreateDevice(request);
			log.info("================【AEP注册设备响应结果】======================");
			log.info(createDeviceResponse.toString());
			responseResult = JSON.parseObject(createDeviceResponse.toString().split("body=")[1]);
			client.shutdown();
			Integer code = responseResult.getInteger("code");
			if(code == 0){
				return R.data(responseResult.getJSONObject("result"), responseResult.getString("msg"));
			}else{
				return R.fail(responseResult.getString("msg"));
			}
		} catch (Exception e) {
			client.shutdown();
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	@Override
	public R deleteDevice(IotDevice iotDevice) {
		IotAepProduct iotAepProduct = iotAepProductService.getByProductId(iotDevice.getProductId());
		Assert.hasText(iotDevice.getProductId(), "产品不存在");

		AepDeviceManagementClient client = AepDeviceManagementClient.newClient().appKey(AepConstant.APPKEY).appSecret(AepConstant.APPSECRET).build();

		DeleteDeviceRequest request = new DeleteDeviceRequest();
		request.setParamMasterKey(iotAepProduct.getMasterKey());
		request.setParamProductId(iotAepProduct.getProductId());
		request.setParamDeviceIds(iotDevice.getDeviceId());

		JSONObject responseResult = null;
		try {
			DeleteDeviceResponse deleteDeviceResponse = client.DeleteDevice(request);
			log.info("================【AEP删除设备响应结果】======================");
			log.info(deleteDeviceResponse.toString());
			responseResult = JSON.parseObject(deleteDeviceResponse.toString().split("body=")[1]);
			client.shutdown();
			Integer code = responseResult.getInteger("code");
			if(code == 0){
				return R.success(responseResult.getString("msg"));
			}else{
				return R.fail(responseResult.getString("msg"));
			}
		} catch (Exception e) {
			client.shutdown();
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	@Override
	public R queryDevice(IotDevice iotDevice) {
		IotAepProduct iotAepProduct = iotAepProductService.getByProductId(iotDevice.getProductId());
		Assert.hasText(iotDevice.getProductId(), "产品不存在");

		AepDeviceManagementClient client = AepDeviceManagementClient.newClient().appKey(AepConstant.APPKEY).appSecret(AepConstant.APPSECRET).build();

		QueryDeviceRequest request = new QueryDeviceRequest();
 		request.setParamMasterKey(iotAepProduct.getMasterKey());
 		request.setParamDeviceId(iotDevice.getDeviceId());
 		request.setParamProductId(iotAepProduct.getProductId());

		JSONObject responseResult = null;
		try {
			QueryDeviceResponse queryDeviceResponse = client.QueryDevice(request);
			log.info("================【AEP查询设备响应结果】======================");
			log.info(queryDeviceResponse.toString());
			responseResult = JSON.parseObject(queryDeviceResponse.toString().split("body=")[1]);
			client.shutdown();
			Integer code = responseResult.getInteger("code");
			if(code == 0){
				return R.data(responseResult.getJSONObject("result"), responseResult.getString("msg"));
			}else{
				return R.fail(responseResult.getString("msg"));
			}
		} catch (Exception e) {
			client.shutdown();
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

	@Override
	public R queryDeviceList(IotDevice iotDevice) {
		return null;
	}

	@Override
	public R updateDevice(IotDevice iotDevice) {
		IotAepProduct iotAepProduct = iotAepProductService.getByProductId(iotDevice.getProductId());
		Assert.hasText(iotDevice.getProductId(), "产品不存在");

		AepDeviceManagementClient client = AepDeviceManagementClient.newClient().appKey(AepConstant.APPKEY).appSecret(AepConstant.APPSECRET).build();

		UpdateDeviceRequest request = new UpdateDeviceRequest();
 		request.setParamMasterKey(iotAepProduct.getMasterKey());
 		request.setParamDeviceId(iotDevice.getDeviceId());
 		JSONObject data = new JSONObject();
 		JSONObject other = new JSONObject();
 		other.put("autoObserver", 0);
 		data.put("deviceName", iotDevice.getDeviceName());
 		data.put("productId", iotAepProduct.getProductId());
 		data.put("operator", iotDevice.getUpdateUser() != null? iotDevice.getUpdateUser().toString() : "admin");
		data.put("other", other);
 		request.setBody(JsonUtil.toJsonAsBytes(data));

		JSONObject responseResult = null;
		try {
			UpdateDeviceResponse updateDeviceResponse = client.UpdateDevice(request);
			log.info("================【AEP更新设备响应结果】======================");
			log.info(updateDeviceResponse.toString());
			responseResult = JSON.parseObject(updateDeviceResponse.toString().split("body=")[1]);
			client.shutdown();
			Integer code = responseResult.getInteger("code");
 			if(code != null && code == 0){
				return R.success(responseResult.getString("msg"));
			}else{
				return R.fail(responseResult.getString("msg"));
			}
		} catch (Exception e) {
			client.shutdown();
			e.printStackTrace();
			return R.fail(e.getMessage());
		}
	}

}
