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

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')
		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']:
					state = self.bind(user['id'])
					if state == False:
						self.out('手机号或密码错误,登录失败')
					else:
						#self.set_secure_cookie('user', str(user['id']))
						#self.redirect('/')
						self.out('yes', {'uid':user['id']})
					return
		else:
			self.out('手机号或密码错误,登录失败')
			return
	@Web.setting
	def bind(self, uid):
		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.body)
		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)
		return True