/*
 *      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.device.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springblade.common.constant.CommonConstant;
import org.springblade.community.entity.Residential;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.device.entity.IotDevice;
import org.springblade.device.vo.IotDeviceVO;
import org.springblade.device.mapper.IotDeviceMapper;
import org.springblade.device.service.IIotDeviceService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.system.entity.DictBiz;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.third.iotdevice.feign.IAepDeviceManageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 智能设备 服务实现类
 *
 * @author BladeX
 * @since 2021-04-19
 */
@Service
public class IotDeviceServiceImpl extends BaseServiceImpl<IotDeviceMapper, IotDevice> implements IIotDeviceService {

	@Autowired
	private IResidentialClient residentialClient;
	@Autowired
	private IAepDeviceManageClient aepDeviceManageClient;

	@Override
	public IPage<IotDeviceVO> selectIotDevicePage(IPage<IotDeviceVO> page, IotDeviceVO iotDevice) {
		return page.setRecords(baseMapper.selectIotDevicePage(page, iotDevice));
	}

	@Override
	public IotDevice getByDeviceId(String deviceId) {
		return this.getBaseMapper().selectOne(new QueryWrapper<>(new IotDevice()).lambda().eq(IotDevice::getDeviceId,deviceId));
	}

	@Override
	public R registerDevice(IotDevice iotDevice) {
		Long residentialId = iotDevice.getResidentialId();
		Residential residential = residentialClient.getById(residentialId);
		Assert.notNull(residential, "安装区域不存在");
		Assert.notBlank(iotDevice.getProductId(), "产品ID必传");
		iotDevice.setTenantId(residential.getTenantId());
		iotDevice.setAgencyId(residential.getAgencyId());
		if (iotDevice.getId() != null) {//更新
			return this.updateDevice(iotDevice);
		} else {//新增设备
			switch (iotDevice.getPlatform()) {
				case "AEP":
					BladeUser user = AuthUtil.getUser();
					iotDevice.setCreateUser(user.getUserId());
					R<JSONObject> registerR = aepDeviceManageClient.registerDevice(iotDevice);
					if (registerR.isSuccess()) {
						JSONObject data = registerR.getData();
						iotDevice.setDeviceId(data.getString("deviceId"));
						iotDevice.setDeviceStatus(0);
						return R.status(this.save(iotDevice));
					} else {
						return R.fail(registerR.getMsg());
					}
				default:
					return R.fail("对接平台不存在，请重新选择");
			}
		}
	}

	@Override
	public R updateDevice(IotDevice iotDevice) {
		Assert.notBlank(iotDevice.getDeviceId(), "设备ID必传");
		Assert.notBlank(iotDevice.getProductId(), "产品ID必传");
		boolean update = this.updateById(iotDevice);
		if(update){
			return aepDeviceManageClient.updateDevice(iotDevice);
		}else{
			return R.status(false);
		}
	}

	@Override
	public R deleteDevice(IotDevice iotDevice) {
		if(CommonConstant.THIRDPLATFORM.AEP.getValue().equals(iotDevice.getPlatform())){
			Assert.notBlank(iotDevice.getDeviceId(), "设备ID必传");
			Assert.notBlank(iotDevice.getProductId(), "产品ID必传");
			return aepDeviceManageClient.deleteDevice(iotDevice);
		}else{
			return R.status(true);
		}
	}

	@Override
	public R queryDevice(IotDevice iotDevice) {
		Assert.notBlank(iotDevice.getDeviceId(), "设备ID必传");
		Assert.notBlank(iotDevice.getProductId(), "产品ID必传");
		R<JSONObject> queryR= this.aepDeviceManageClient.queryDevice(iotDevice);
		if(queryR.isSuccess()){
			JSONObject data = queryR.getData();
			Integer deviceStatus = data.getInteger("deviceStatus");
			Integer deviceNetStatus = data.getInteger("netStatus");
			Long activeTime = data.getLong("activeTime");
			Long deviceOnlineAt = data.getLong("onlineAt");
			Long deviceOfflineAt = data.getLong("offlineAt");
			iotDevice.setDeviceStatus(deviceStatus);
			iotDevice.setDeviceNetStatus(deviceNetStatus);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(activeTime != null){
				String activeTimeStr = sdf.format(new Date(activeTime));
				iotDevice.setActiveTime(activeTimeStr);
			}
			if(deviceOnlineAt != null){
				String deviceOnlineAtStr = sdf.format(new Date(deviceOnlineAt));
				iotDevice.setLastOnlineAt(deviceOnlineAtStr);
			}
			if(deviceOfflineAt != null){
				String deviceOfflineAtStr = sdf.format(new Date(deviceOfflineAt));
				iotDevice.setLastOfflineAt(deviceOfflineAtStr);
			}
			return R.status(this.updateById(iotDevice));
		}else{
			return R.fail(queryR.getMsg());
		}
	}


}
