#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
	demeter web
	name:login.py 登录相关接口
	author:rabin
"""
from __load__ import *

class login_path(Load):
	"""
	@api {get} /login 登录绑定
	@apiVersion 1.0.0
	@apiName Login
	@apiGroup Common

	@apiParam {String} code 微信小程序的code
	@apiParam {String} mobile 手机号
	@apiParam {String} password 密码

	@apiSuccess {String}   uid  用户id（加密之后的）

	@apiErrorExample 操作成功
	{"status": 1, "msg": "yes", "code": 0, "data": {"uid": "111"}]}}
	@apiErrorExample 操作失败
	{"status": 2, "msg": "\u64cd\u4f5c\u5931\u8d25", "code": 0, "data": {}}
	"""
	@Web.setting
	def get(self):
		mobile = self.input('mobile')
		password = self.input('password')
		nickname = self.input('nickname')
		if mobile and password:
			user = self.service('common').one('farm_user', mobile=mobile)
			if user:
				temp = user['password'].split('_')
				if Demeter.md5(password, temp[1]) == user['password']:
					if not nickname:
						nickname = user['username']
					state = self.bind(user['id'], nickname)
					if state == False:
						self.out('手机号或密码错误，登录失败')
					elif state and state['status'] == False:
						self.out('您的微信账号已经被封禁，请联系管理员')
					else:
						#self.set_secure_cookie('user', str(user['id']))
						#self.redirect('/')
						if state['status']:
							state['status'] = 1
						else:
							state['status'] = 2
						self.out('yes', {'uid':user['id'], 'wid':state['id'], 'status': state['status']})
					return
		else:
			self.out('手机号或密码错误，登录失败')
			return

	def bind(self, uid, nickname):
		code = self.input('code')
		if not code:
			self.out('no')
			return
		url = Demeter.config['weixinApp']['login']
		url = url + '?appid=' + Demeter.config['weixinApp']['appid']
		url = url + '&secret=' + Demeter.config['weixinApp']['secret']
		url = url + '&js_code=' + code
		url = url + '&grant_type=authorization_code'
		data = Demeter.curl(url)
		data = json.loads(data)
		if 'errcode' in data:
			return False
		update = {}
		update['openid'] = data['openid']
		update['session_key'] = data['session_key']
		self.service('common').update('farm_user', uid, update)
		wechat = self.service('common').one('farm_user_wechat', uid=uid, openid=update['openid'])
		if not wechat:
			update = {}
			update['nickname'] = nickname
			update['openid'] = data['openid']
			update['session_key'] = data['session_key']
			update['uid'] = uid
			self.service('common').update('farm_user_wechat', False, update)
			wechat = self.service('common').one('farm_user_wechat', uid=uid, openid=data['openid'])
		return wechat

class check_path(Load):
	@Web.setting
	def get(self):
		wid = self.input('wid')
		uid = self.input('uid')
		if wid and uid:
			wechat = self.service('common').one('farm_user_wechat', wid=wid)
			if wechat:
				if wechat['status']:
					wechat['status'] = 1
				else:
					wechat['status'] = 2
				self.out('yes', {'uid':uid, 'wid':wid, 'status': wechat['status']})
			else:
				self.out('yes', {'uid':uid, 'wid':wid, 'status': 3})