#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter service
    name:record.py 用于记录设备过来的数据
    author:rabin
"""
from demeter.core import *
import json
class Record(object):

	def topic(self, key):
		array = key.split('/')
		slen = len(array)
		if len >= 4:
			return {'method':array[0], 'type':array[1], 'parent':array[2], 'child':array[3]}
		else:
			return {'method':array[0], 'type':array[1], 'parent':array[2], 'child':array[2]}

	def push(self, key, value):
		config = self.topic(key)
		method = 'record_' + config['method']
		cls = Demeter.getClass(method, 'service.')
		state = False
		if config['method'] != 'pic':
			if '{' in value:
				value = Demeter.isJson(value)
				if value:
					state = True
					for k,v in value.items():
						config['child'] = k
						cls().handle(self, config, v)
		if state == False:
			cls().handle(self, config, value)

	def save(self, config, value, name='', device_type=None):
		model = Demeter.model('device_gateway')
		model.hardware_id = config['parent']
		gateway = model.select(type='fetchone')
		if gateway:
			#更新网关状态
			self.gateway(config['parent'], gateway['farm_id'], gateway['id'])
			model_type = Demeter.model('hardware_type')
			model_type.key = config['method']
			hard = model_type.select(type='fetchone')
			model = Demeter.model('device_info')
			model.hardware_id = config['child']
			model.hardware_type = hard['id']
			device = model.select(type='fetchone')
			if device:
				model.id = device['id']
				if config['method'] == 'control' and (value == '0' or value == 0):
					model.update(status=True, cdate='time')
					return
				#update
				id = device['id']
				if config['method'] == 'sensor' or config['method'] == 'power':
					value = Demeter.exp(device['exp'], value)
				model.update(value=value,status=True,cdate='time')
				# 上下限判断
				# 条件判断
				if device['type_id'] > 0 and (hard['id'] == 2 or hard['id'] == 4):
					value = float(value)
					content = ''
					if device['max']:
						if value > device['max']:
							if device['cxtype'] == 1:
								if device['cxnum']:
									device['cxnum'] = device['cxnum'] + 1
								else:
									device['cxnum'] = 1
								if device['cxnum'] > 3:
									device['cxnum'] = 0
									content = '从' + Demeter.date(device['cxdate']) + '到' + Demeter.date(Demeter.time()) + '，' + gateway['name'] + '，'+device['name']+'超过'+str(device['max'])+device_type['unit']+'，当前值'+str(value)+device_type['unit']+'，请及时控制'+device_type['name']+'进行处理。'
									self.msg(id, content, gateway['farm_id'], 2)
							else:
								device['cxtype'] = 1
								device['cxnum'] = 1
							model.id = device['id']
							if device['cxnum'] == 1:
								model.update(farm_id=gateway['farm_id'], cxnum=device['cxnum'],cxtype=device['cxtype'], cxdate='time')
							else:
								model.update(farm_id=gateway['farm_id'], cxnum=device['cxnum'],cxtype=device['cxtype'])

					if device['min']:
						if value < device['min']:
							if device['cxtype'] == 2:
								if device['cxnum']:
									device['cxnum'] = device['cxnum'] + 1
								else:
									device['cxnum'] = 1
								if device['cxnum'] > 3:
									device['cxnum'] = 0
									content = '从' + Demeter.date(device['cxdate']) + '到' + Demeter.date(Demeter.time()) + '，' + gateway['name'] + '，'+device['name']+'少于'+str(device['min'])+device_type['unit']+'，当前值'+str(value)+device_type['unit']+'，请及时控制'+device_type['name']+'进行处理。'
									self.msg(id, content, gateway['farm_id'], 2)
							else:
								device['cxtype'] = 2
								device['cxnum'] = 1
							model.id = device['id']
							if device['cxnum'] == 1:
								model.update(farm_id=gateway['farm_id'], cxnum=device['cxnum'],cxtype=device['cxtype'], cxdate='time')
							else:
								model.update(farm_id=gateway['farm_id'], cxnum=device['cxnum'],cxtype=device['cxtype'])
					"""
					content = ''
					condition_model = Demeter.model('device_set_condition')
					condition_model.device_id = id
					condition_model.status = True
					condition = condition_model.select()
					if condition:
						
						for cv in condition:
							state = False
							text = ''
							cv['value'] = float(cv['value'])
							if cv['condition'] == 1 and value > cv['value']:
								state = True
								text = '超过'
							elif cv['condition'] == 2 and value < cv['value']:
								state = True
								text = '少于'
							elif value == cv['value']:
								state = True
								text = '等于'
							if state:
								if cv['notice'] == True:
									content = gateway['name'] + '，'+device['name']+text+str(cv['value'])+device_type['unit']+'，当前值'+str(value)+device_type['unit']+'，请及时控制'+device_type['name']+'进行处理。'
									self.msg(id, content, gateway['farm_id'], 2)
								if cv['oper'] == 2:
									cv['oper'] = 1
									Demeter.service('device').switchMul(cv)
								elif cv['oper'] == 3:
									cv['oper'] = 0
									Demeter.service('device').switchMul(cv)
					"""
						
			else:
				#insert
				model.hardware_id = config['child']
				model.farm_id = gateway['farm_id']
				model.name = name
				model.hardware_type = hard['id']
				model.gateway_id = gateway['id']
				if device_type:
					model.type_id = device_type['id']
				else:
					model.type_id = 0
				model.value = value
				model.status = True
				id = model.insert()
				self.hardware(id, config['child'], gateway['farm_id'],gateway['id'], hard['id'])

			if config['method'] == 'pic':
				model_pic = Demeter.model('device_pic')
				model_pic.farm_id = gateway['farm_id']
				model_pic.gateway_id = gateway['id']
				model_pic.device_id = id
				model_pic.pic = value
				model_pic.insert()
			else:
				data = {}
				data['type'] = config['type']
				data['gateway'] = config['parent']
				data['device'] = config['child']
				data['hard'] = config['method']
				data['farm'] = gateway['farm_id']
				data['source'] = value
				data['value'] = value
				data['time'] = Demeter.time()
				Demeter.model('data', 'tsdb').insert(data)

	def msg(self, device_id, content, farm_id, type_id):
		model = Demeter.model('msg')

		# 2018-05-23更新 增加三个小时之内只能报一次错误
		model.farm_id = farm_id
		#model.content = content
		model.device_id = device_id
		model.type_id = type_id
		info = model.select(type='fetchone')
		state = False
		if info:
			if Demeter.time() - info['cdate'] > 3600*3:
				state = True

		if state == True:
			model.farm_id = farm_id
			model.content = content
			model.device_id = device_id
			model.type_id = type_id
			info = model.select(type='fetchone')
			if not info:
				model.farm_id = farm_id
				model.content = content
				model.device_id = device_id
				model.type_id = type_id
				model.insert()
			else:
				model.id = info['id']
				model.update(content=content, cdate='time')

	def gateway(self, gateway, farm, id):
		# 更新网关状态
		hardware_type = 5
		model = Demeter.model('device_info')
		model.hardware_id = gateway
		model.hardware_type = hardware_type
		device = model.select(type='fetchone')
		if device:
			model.id = device['id']
			model.update(value='1',status=True,cdate='time')
		else:
			model.hardware_id = gateway
			model.farm_id = farm
			model.name = '网关状态'
			model.status = True
			model.hardware_type = hardware_type
			model.gateway_id = id
			model.type_id = 0
			model.value = '1'
			model.insert()
			self.hardware(id, gateway, farm, id, 1)

	def hardware(self, id, hardware_id, farm, gateway, hard):
		# 记录硬件设备
		if hardware_id and id > 0:
			model = Demeter.model('hardware')
			model.hardware_id = hardware_id
			info = model.select(type='fetchone')
			if not info:
				model.farm_id = farm
				model.hardware_id = hardware_id
				model.gateway_id = gateway
				model.device_id = id
				model.hardware_type = hard
				model.insert()