#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    demeter web page
    name:origin.py
    author:rabin
"""
from __load__ import *
#import qrcode
from datetime import *
import os
import short_url
import uuid
import random

class Code(object):
	@staticmethod
	def get(self, value):
		cdate = Demeter.date(value['cdate'], '%Y%m%d%H%M%S')
		#number = Demeter.compressUuid(value['id']).upper()
		min = 1000
		max = 9999
		number = 'XN' + str(value['farm_id'] + 10000) + '-' + str(value['cdate']) + str(random.randint(min, max))

		info = self.service('common').one('origin_batch', number=number)

		if info and info['id'] != value['id']:
			return Code.get(self, value)

		#url = Demeter.config['front']['qrcode'] + self.data['setting']['web'] + 'origin/view?qrcode=' + self.data['list'][key]['number']
		update = {}
		update['number'] = number
		state = self.service('common').update('origin_batch', value['id'], update)
		return number

class index_path(Load):
	@Web.auth
	def get(self):
		mobile = Demeter.checkMobile(self.request)
		if mobile:
			self.redirect('/device')
			return

		self.data['list'] = self.service('common').list('origin_batch', search={'farm_id':self.data['setting']['farm']})
		if self.data['list']:
			for key, value in enumerate(self.data['list']):
				self.data['list'][key]['cdates'] = Demeter.date(value['cdate'], '%Y%m%d')
				self.data['list'][key]['zzdates'] = Demeter.date(value['zzdate'], '%Y-%m-%d')
				self.data['list'][key]['csdates'] = Demeter.date(value['csdate'], '%Y-%m-%d')
				product = self.service('common').one('farm_product', id=value['product_id'])
				if product:
					self.data['list'][key]['product'] = product['name']
				else:
					self.data['list'][key]['product'] = ''

				if not value['number']:
					self.data['list'][key]['number'] = Code.get(self, value)
					value['number'] = self.data['list'][key]['number']
				self.data['list'][key]['url'] = '/origin/view?id=' + value['id']
		self.view("origin/index.html")


class view_path(Load):
	@Web.auth
	def get(self):
		id = self.input('id')
		self.data['info'] = self.service('common').one('origin_batch', id=id)
		self.data['url'] = self.data['setting']['web'] + 'origin?id=' + id + '&code=' + self.data['info']['number']
		self.data['qrcode'] = Demeter.config['front']['qrcode'] + self.data['url']
		self.view("origin/view.html")

class update_path(Load):
	@Web.auth
	def get(self):
		id = self.input('id')
		copy_id = self.input('copy_id')
		if copy_id:
			id = copy_id
		self.data['product'] = self.service('common').list('farm_product', search={'status':True,'farm_id':self.data['setting']['farm']})
		self.data['land'] = self.service('common').list('farm_work_land', search={'farm_id':self.data['setting']['farm']})
		self.data['gateway'] = self.service('common').list('device_gateway', search={'farm_id':self.data['setting']['farm']})
		self.data['device'] = Device.getByGateway(self, search={'hardware_type' : 2,'farm_id':self.data['setting']['farm']})
		self.data['camera'] = self.service('common').list('device_info', search={'hardware_type': 6,'farm_id':self.data['setting']['farm']})
		self.data['info'] = {}
		self.data['growth'] = []
		if id:
			self.data['growth'] = self.service('common').list('origin_growth', search={'batch_id': id})
			if self.data['growth']:
				for key, value in enumerate(self.data['growth']):
					self.data['growth'][key]['date'] = Demeter.date(value['date'], '%Y-%m-%d')
			self.data['info'] = self.service('common').one('origin_batch', id=id)
			if self.data['info']:
				self.data['info']['zzdate'] = Demeter.date(self.data['info']['zzdate'], '%Y-%m-%d')
				self.data['info']['csdate'] = Demeter.date(self.data['info']['csdate'], '%Y-%m-%d')
				if copy_id:
					self.data['info']['id'] = None
		self.view("origin/update.html")

	@Web.auth
	def post(self):
		id = self.input('id')
		update = {}
		update['devices'] = self.inputs('update_devices')
		update['amount'] = self.input('update_amount')
		update['product_id'] = self.input('update_product_id')
		update['device_camera_id'] = self.input('update_device_camera_id')
		update['land_id'] = self.input('update_land_id')
		update['name'] = self.input('update_name')
		update['zzdate'] = self.input('update_zzdate')
		update['csdate'] = self.input('update_csdate')
		growth = {}
		growth['name'] = self.inputs('update_growth_name')
		growth['date'] = self.inputs('update_growth_date')
		growth['pic'] = self.inputs('update_growth_pic')
		growth['id'] = self.inputs('update_growth_id')

		if not update['name']:
			self.out(u'请输入批次名称')
			return
		if not update['product_id']:
			self.out(u'请选择产品')
			return
		if not update['land_id']:
			self.out(u'请选择地块')
			return
		if not update['devices']:
			self.out(u'请选择设备')
			return
		if not update['device_camera_id']:
			self.out(u'请选择摄像头')
			return
		if not update['zzdate'] or not update['csdate']:
			self.out(u'请选择生长周期')
			return
		if not growth['name'] or not growth['date'] or not growth['pic']:
			self.out(u'请添加生长阶段')
			return
		if not update['amount']:
			self.out(u'请输入本批产量')
			return
			
		update['devices'] = str(update['devices'])
		state = self.service('common').update('origin_batch', id, update)
		if state:
			model = Demeter.model('origin_growth')
			model.batch_id = state
			model.delete()
			for key,value in enumerate(growth['name']):
				if value and growth['date'][key]:
					gid = growth['id'][key]
					gupdate = {}
					gupdate['name'] = value
					gupdate['date'] = growth['date'][key]
					gupdate['pic'] = growth['pic'][key]
					gupdate['batch_id'] = state
					self.service('common').update('origin_growth', gid, gupdate)
		self.out('yes', {'state':state})

	@Web.auth
	def delete(self):
		id = self.input('id')
		if not id:
			self.out('no')
			return
		state = self.input('state', False)
		state = self.service('common').delete('origin_batch', id, state)
		self.out('yes', {'state':state})

class printer_path(Load):
	@Web.auth
	def get(self):
		id = self.input('id')
		table_id = self.input('table_id');
		self.data['info'] = {}
		self.data['printer'] = self.service('common').list('device_printer', search={'farm_id':self.data['setting']['farm']})
		self.data['table_id'] = table_id
		if id:
			self.data['info'] = self.service('common').one('device_printer_log', id=id)
		self.view("origin/printer.html")

	@Web.auth
	def post(self):
		id = self.input('id')
		update = {}
		update['printer_id'] = self.input('update_printer_id')
		update['num'] = self.input('update_num')

		if not update['printer_id']:
			self.out(u'请选择打印机')
			return
		if not update['num']:
			self.out(u'请输入张数')
			return
		update['uid'] = self.data['setting']['userInfo']['id']
		update['table_name'] = 'origin_batch'
		update['table_id'] = self.input('update_table_id')
		if not update['table_id']:
			self.out(u'错误的来源')
			return
		info = self.service('common').one(update['table_name'], id=update['table_id'])
		update['content'] = '打印' + info['name'] + '溯源码：' + str(update['num']) + '张'
		state = self.service('common').update('device_printer_log', id, update)
		self.out('已发送至打印机队列')
