# -*- coding: utf-8 -*-
"""
    demeter web page
    name:device.py 设备相关页面
    author:rabin
"""
from .__load__ import *

class gateway_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			name = u'网关'
			,path = 'gateway'
			,width = '600'
			,height = '500'
			#,add = False
			#,edit = False
			,search = (('label-1','cdate-time-start','cdate-time-end','farm_id-select-','name-input-mlike'), (u'日期范围',u'开始时间',u'截止时间',u'选择农场',u'网关名称'))
			,thead = (u'所属农场',u'网关名称', u'网关ID', u'所属产品', u'关联服务', u'网关连接状态', u'更新时间')
			,tbody = ('farm','name', 'hardware_id', 'product', 'server', 'status', 'cdate')
			,state = False
		)
		self.data['common']['search_farm_id-select-'] = Demeter.config['setting']['farmList']
		self.list('device_gateway', order='hardware_id asc')
		if self.data['list']:
			for key, value in enumerate(self.data['list']):
				farm = self.service('common').one('farm', id=value['farm_id'])
				self.data['list'][key]['farm'] = farm['name']
				device = self.service('common').list('device_info', search={'hardware_id':value['hardware_id']})
				self.data['list'][key]['status'] = '断开'
				self.data['list'][key]['product'] = '无'
				self.data['list'][key]['server'] = '无'

				if value['product_id']:
					product = self.service('common').one('setting_product', id=value['product_id'])
					self.data['list'][key]['product'] = product['name']
				if value['server_id']:
					server = self.service('common').one('setting_server', id=value['server_id'])
					self.data['list'][key]['server'] = server['name']
				if device:
					for v in device:
						if v['value']:
							v['value'] = float(v['value'])
							if v['hardware_type'] == 5 and v['value'] == 1:
								self.data['list'][key]['status'] = '连接'
							elif v['hardware_type'] == 4 and v['value']:
								self.data['list'][key]['power_status'] = '连接'
								self.data['list'][key]['power_num'] = v['value']
		self.show('list')

class gateway_update_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		id = self.input('id')
		if id:
			#hardware_id = 'hardware_id-show-required'
			hardware_id = 'hardware_id-input-required'
		else:
			hardware_id = 'hardware_id-input-required'
		self.set(
			path = 'gateway'
			,label = (u'所属农场', u'网关名称', u'网关ID', u'所属产品', u'关联服务', u'设备分布图纸')
			,update = ('farm_id-select-required', 'name-input-required',hardware_id,'product_id-select-','server_id-select-', 'pic-pic-')
			,update_product_id = self.service('common').list('setting_product')
			,update_server_id = self.service('common').list('setting_server')
			,update_farm_id = self.service('common').list('farm', search={'eros_status':2})
		)
		self.one('device_gateway')
		self.show('update')
	@Web.auth
	@Web.setting
	def post(self):
		id = self.update('device_gateway')
		self.device(id)

	@Web.auth
	@Web.setting
	def delete(self):
		self.drop('device_gateway')

	@Web.auth
	@Web.setting
	def device(self, id):
		info = self.service('common').one('device_gateway', id=id)
		self.service('device').addDeviceByGateway(info)
		
class info_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			name = u'设备'
			,path = 'info'
			,width = '600'
			,height = '400'
			,button = ({'name':'添加摄像机','link':'/device/camera_update'},{'name':'添加摄像头','link':'/device/camera_pic_update'})
			,add = False
			#,edit = False
			,search = (('farm_id-select--gateway_id', 'hardware_type-select-','type_id-select-','name-input-mlike', 'status-hidden-'), (u'选择农场',u'硬件类型',u'设备类型',u'设备名称', '设备状态'))
			,thead = (u'所属农场',u'设备名称', u'设备id', u'当前值', u'设备类型', u'网关',u'硬件类型')
			,tbody = ('farm','name', 'hardware_id', 'value', 'type', 'gateway', 'hardware_type')
			,state = True
		)
		self.data['common']['search_farm_id-select--gateway_id'] = Demeter.config['setting']['farmList']
		self.data['common']['search_type_id-select-'] = self.service('common').list('setting_device_type')
		self.data['common']['search_gateway_id-select---farm_id'] = self.service('common').list('device_gateway', order='hardware_id asc')
		self.data['common']['search_hardware_type-select-'] = self.service('common').list('hardware_type')
		"""
		if self.data['common']['search_hardware_type-select-']:
			del self.data['common']['search_hardware_type-select-'][0]
		"""
		status = self.input('search_status-hidden-', False)
		if status:
			self.data['search']['status'] = False

		#inorder asc, type_id asc,
		self.list('device_info', order='inorder asc, type_id asc, udate asc,hardware_id asc,cdate desc')
		if self.data['list']:
			for key, value in enumerate(self.data['list']):
				farm = self.service('common').one('farm', id=value['farm_id'])
				self.data['list'][key]['farm'] = farm['name']
				self.data['list'][key]['type'] = '无'
				if value['type_id']:
					type_info = self.service('common').one('setting_device_type', id=value['type_id'])
					if type_info:
						self.data['list'][key]['type'] = type_info['name']
				info = self.service('common').one('device_gateway', id=value['gateway_id'])
				self.data['list'][key]['gateway'] = info['name']
				if value['status']:
					self.data['list'][key]['status'] = '已连接'
				else:
					self.data['list'][key]['status'] = '已断开'

				if not value['value']:
					value['value'] = ''
					self.data['list'][key]['value'] = '无'
				elif value['hardware_type'] == 2 or value['hardware_type'] == 4:
					if value['type_id'] and type_info:
						value['value'] = value['value'] + ' ' + type_info['unit']
					self.data['list'][key]['value'] = '<a href="/device/stat?id='+value['id']+'&search_date-select-=1&method=list">'+value['value'] + '</a><br />更新时间：' + Demeter.date(value['cdate']) + '<br /><a href="/device/stat?id='+value['id']+'&search_date-select-=1&method=avg">[平均值统计]</a> <a href="/device/stat?id='+value['id']+'&search_date-select-=1&method=maxmin">[高低值统计]</a>'
				elif value['hardware_type'] == 6:
					self.data['list'][key]['value'] = '<a href="/device/pic?id='+value['id']+'"><img src="'+value['value']+'" width="200px"/></a><br />更新时间：' + Demeter.date(value['cdate'])
				elif value['hardware_type'] == 3:
					if value['status']:
						status = ''
					else:
						status = 'disabled'
					url = '/device/info'
					import math
					value['value'] = math.ceil(float(value['value']))
					if value['value'] == 1:
						value['value'] = '开'
					else:
						value['value'] = '关'

					'''
					if value['value'] == 1:
						#disabled
						self.data['list'][key]['value'] = '<input type="checkbox" name="switch" lay-filter="switch" lay-skin="switch" checked '+status+' value="1" data-value="0" data-id="'+value['id']+'" data-url="'+url+'">'
					else:
						self.data['list'][key]['value'] = '<input type="checkbox" lay-filter="switch" name="switch" lay-skin="switch" '+status+' value="0" data-value="1" data-id="'+value['id']+'" data-url="'+url+'">'
					'''
					self.data['list'][key]['value'] = value['value']
				elif value['hardware_type'] == 5:
					if value['value'] == '1':
						self.data['list'][key]['value'] = '已连接'
					else:
						self.data['list'][key]['value'] = '已断开'

				hardware_type = self.service('common').one('hardware_type', id=value['hardware_type'])
				self.data['list'][key]['hardware_type'] = hardware_type['name']


		self.show('list')

	@Web.auth
	@Web.setting
	def post(self):
		id = self.input('id')
		value = self.input('value')
		if id:
			Demeter.service('device').switch(id, value)
			self.out('yes', {'state':id})
		else:
			self.out('no')

class info_update_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.one('device_info')
		if self.data['info']['hardware_type'] == 7:
			self.set(
				path = 'camera'
				#,label = (u'摄像机名称', u'摄像机id', u'所属农场', u'选择网关', u'选择硬件类型', u'摄像机地址')
				#,update = ('name-input-required','hardware_id-show-','farm_id-select-required','gateway_id-select-required','hardware_type-select-required','value-text-required')
				,label = (u'摄像机名称', u'摄像机id', u'所属农场', u'选择网关', u'摄像机地址', u'排序')
				,update = ('name-input-required','hardware_id-show-','farm_id-select-required-gateway_id','gateway_id-select-required--farm_id','value-text-required','inorder-input-')
				,update_farm_id = self.service('common').list('farm', search={'eros_status':2})
				,update_gateway_id = self.service('common').list('device_gateway', order='hardware_id asc')
				#,update_hardware_type = self.service('common').list('hardware_type')
			)
		elif self.data['info']['hardware_type'] == 6:
			self.set(
				path = 'camera_pic'
				,label = (u'摄像头名称', u'摄像头id', u'所属农场', u'选择网关', u'摄像头地址', u'排序')
				,update = ('name-input-required','hardware_id-show-','farm_id-select-required-gateway_id','gateway_id-select-required--farm_id','value-text-required','inorder-input-')
				,update_farm_id = self.service('common').list('farm', search={'eros_status':2})
				,update_gateway_id = self.service('common').list('device_gateway', order='hardware_id asc')
			)
		elif self.data['info']['hardware_type'] in (2,4):
			self.set(
				path = 'info'
				#,label = (u'设备名称', u'设备id', u'计算公式', u'实时计算公式')
				#,update = ('name-input-required','hardware_id-show-',u'exp-text--{n}为当前数据,只处理最新数据',u'out_exp-text--处理所有数据，比较消耗服务器资源')
				,label = (u'设备名称', u'设备id', u'计算公式', u'排序')
				,update = ('name-input-required','hardware_id-show-',u'exp-input--{n}为当前数据,只处理最新数据','inorder-text-')
			)
		else:
			self.set(
				path = 'info'
				,label = (u'设备名称', u'设备id', u'排序')
				,update = ('name-input-required','hardware_id-show-','inorder-input-')
			)
		self.show('update')
	@Web.auth
	@Web.setting
	def post(self):
		self.update('device_info')
	@Web.auth
	@Web.setting
	def delete(self):
		self.drop('device_info')
		"""
		self.one('device_info')
		if self.input('state') == 'True' or (self.data['info'] and 'hardware_type' in self.data['info'] and self.data['info']['hardware_type'] == 7):
			self.drop('device_info')
		else:
			#除摄像机之外，其余设备不允许删除
			self.out('no')
		"""

class camera_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.redirect('/device/info?search_hardware_type=7')

class camera_update_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			path = 'camera'
			,label = (u'摄像机名称', u'摄像机id', u'所属农场', u'选择网关', u'摄像机地址',u'排序')
			,update = ('name-input-required','hardware_id-input-required','farm_id-select-required-gateway_id','gateway_id-select-required--farm_id','value-text-required','inorder-text-')
			,update_farm_id = self.service('common').list('farm', search={'eros_status':2})
			,update_gateway_id = self.service('common').list('device_gateway', order='hardware_id asc')
		)
		self.one('device_info')
		self.show('update')
	@Web.auth
	@Web.setting
	def post(self):
		self.data['update']['hardware_type'] = 7
		self.data['update']['type_id'] = 0
		self.update('device_info')
	@Web.auth
	@Web.setting
	def delete(self):
		self.drop('device_info')

class camera_pic_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.redirect('/device/info?search_hardware_type=6')

class camera_pic_update_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			path = 'camera_pic'
			,label = (u'摄像头名称', u'摄像头id', u'所属农场', u'选择网关', u'摄像头地址',u'排序')
			,update = ('name-input-required','hardware_id-input-required','farm_id-select-required-gateway_id','gateway_id-select-required--farm_id','value-text-required','inorder-text-')
			,update_farm_id = self.service('common').list('farm', search={'eros_status':2})
			,update_gateway_id = self.service('common').list('device_gateway', order='hardware_id asc')
		)
		self.one('device_info')
		self.show('update')
	@Web.auth
	@Web.setting
	def post(self):
		self.data['update']['hardware_type'] = 6
		self.data['update']['type_id'] = 0
		self.update('device_info')
	@Web.auth
	@Web.setting
	def delete(self):
		self.drop('device_info')

class pic_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			name = u'摄像头图片'
			,path = 'pic'
			,width = '600'
			,height = '300'
			,add = False
			,edit = False
			,search = (('label-1','sdate-time-start','sdate-time-end'), (u'日期范围',u'开始时间',u'截止时间'))
			,thead = (u'图片地址', u'更新时间')
			,tbody = ('pic', 'sdate')
			,state = False
		)

		self.list('device_pic', order='sdate desc')
		if self.data['list']:
			for key, value in enumerate(self.data['list']):
				self.data['list'][key]['pic'] = '<img src="'+value['pic']+'" width="200px" />'
		self.show('list')

class stat_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		method = self.input('method', 'avg')
		id = self.input('id')
		self.set(
			name = u'设备统计'
			,path = 'stat'
			,search = (('label-1','cdate-time-start','cdate-time-end', 'date-select-'), (u'日期范围',u'开始时间',u'截止时间',u'周期选择'))
		)
		data = self.service('common').one('device_info', id=id)
		typeInfo = self.service('common').one('setting_device_type', id=data['type_id'])
		farm = self.service('common').one('farm', id=data['farm_id'])
		self.data['info'] = data
		self.data['type'] = typeInfo
		self.data['farm'] = farm
		self.data['method'] = method

		model = Demeter.model('data', 'tsdb')
		self.data['common']['search_date-select-'] = model.dateConfig()
		search = {}
		if 'cdate-time-start' in self.data['search']:
			search['start'] = self.data['search']['cdate-time-start']
		if 'cdate-time-end' in self.data['search']:
			search['end'] = self.data['search']['cdate-time-end']
		if 'date-select-' in self.data['search']:
			search['group'] = self.data['search']['date-select-']
		self.data['list'] = model.getData(method, search, data)

		self.show('stat')


class printer_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			name = u'打印机'
			,path = 'printer'
			,width = '600'
			,height = '400'
			,search = (('farm_id-select-','name-input-mlike'), (u'选择农场',u'打印机名称'))
			,thead = (u'所属农场', u'打印机名称', u'打印机地址', u'更新时间')
			,tbody = ('farm','name', 'host', 'cdate')
			,state = True
		)
		self.data['common']['search_farm_id-select-'] = Demeter.config['setting']['farmList']
		self.list('device_printer')
		if self.data['list']:
			for key, value in enumerate(self.data['list']):
				farm = self.service('common').one('farm', id=value['farm_id'])
				self.data['list'][key]['farm'] = farm['name']
		self.show('list')

class printer_update_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			path = 'printer'
			,label = (u'所属农场', u'打印机名称', u'打印机地址')
			,update = ('farm_id-select-required', 'name-input-required','host-input-required')
			,update_farm_id = self.service('common').list('farm', search={'eros_status':2})
		)
		self.one('device_printer')
		self.show('update')
	@Web.auth
	@Web.setting
	def post(self):
		self.update('device_printer')
	@Web.auth
	@Web.setting
	def delete(self):
		self.drop('device_printer')


class notice_type_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			name = u'错误码设置'
			,path = '/device/notice_type'
			,width = '600'
			,height = '300'
			,search = (('name-input-mlike','key-input-mlike'), (u'错误码描述',u'错误码key'))
			,thead = (u'ID', u'错误码描述',u'错误码key', u'更新时间')
			,tbody = ('id', 'name', 'key', 'cdate')
			,state = False
		)
		self.list('notice_type')
		self.show('list')

class notice_type_update_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			path = '/device/notice_type'
			,label = (u'错误码描述', u'错误码key')
			,update = ('name-input-required', 'key-input-required')
		)
		self.one('notice_type')
		self.show('update')
	@Web.auth
	@Web.setting
	def post(self):
		self.update('notice_type')

	@Web.auth
	@Web.setting
	def delete(self):
		self.drop('notice_type')

class log_path(Load):
	@Web.auth
	@Web.setting
	def get(self):
		self.set(
			name = u'网关日志'
			,path = '/device/log'
			,width = '600'
			,height = '600'
			,add = False
			,edit = False
			,search = (('farm_id-select-','content-input-mlike'), (u'选择农场', u'内容'))
			,thead = (u'所属农场', u'所属网关', u'日志内容',u'发送时间')
			,tbody = ('farm','gateway', 'content', 'cdate')
			,state = False
		)
		self.data['common']['search_farm_id-select-'] = Demeter.config['setting']['farmList']
		self.list('log')
		if self.data['list']:
			for key, value in enumerate(self.data['list']):
				farm = self.service('common').one('farm', id=value['farm_id'])
				self.data['list'][key]['farm'] = farm['name']
				gateway = self.service('common').one('device_gateway', id=value['gateway_id'])
				self.data['list'][key]['gateway'] = gateway['name']
		self.show('list')