<?php
namespace App\Models;
class WxUser extends BaseModel {
	const CREATED_AT = 'createTime';
	protected $table = "user";
	const UPDATED_AT = 'updateTime';
	public $timestamps = true;
	protected $primaryKey = "id";

	/**
	 * 检测UID是否在表中
	 *
	 * @param [type] $uid
	 * @return void
	 */
	function checkUser($uid) {
		$data = $this->where('uid', $uid)->first();
		if (!$data) {
			return 0;
		}
		return $data->id;
	}

	function getUser($user_id) {
		$data = $this->where('id', $user_id)->first();
		if (!$data) {
			return -1;
		}
		return $data;
	}

	function addUser($uid, $user) {
		if (empty($uid) || empty($user)) {
			return -1;
		}
		if (!$user = $this->checkUser($uid)) {
			$this->userName = $user;
			$this->uid = $uid;
			$this->point = 0;
			$this->totalPoint = 0;
			$this->save();
			return $this->id;
		}
		return $user;

	}
	function queryPoint($user_id) {
		$user = $this->getUser($user_id);
		if ($user->id < 0) {
			return -3200;
		}
		return array('totalPoint' => $user['point']);
	}
	function upPoint($user_id, $point) {
		$user = $this->getUser($user_id);
		if ($user->id < 0) {
			return -3200;
		}

		$model = $this->find($user_id);
		$model->point = $user->point + $point;
		$model->totalPoint = $user->totalPoint + $point;
		$model->save();
		return array('totalPoint' => $model->point, 'point' => $point);
	}

	function downPoint($user_id, $point) {
		$user = $this->getUser($user_id);
		if ($user->id < 0) {
			return -3200;
		}

		if ($user->point < $point) {
			return -3203;
		}
		$add_point = $point;
		$model = $this->find($user_id);
		$model->point = $user->point - $point;
		$model->save();
		return array('totalPoint' => $model->point, 'point' => $point);
	}
}
