<?php
namespace Api\Model;

use Think\Model;

header("Content-Type:text/html;CharSet=UTF-8");
class UsersModel extends Model
{
    /**
     * 更新 用户记录
     */
    public function updateUserInfo()
    {
        file_put_contents("./Logs/updateUserInfo.log", date("Y-m-d H:i:s ") . "\r\n" . serialize($_GET) . "\r\n\r\n", FILE_APPEND);
        $openid = $_GET['openid'];
        $time = $_SERVER['REQUEST_TIME'];
        $userInfo = json_decode($_GET['userInfo']);
        $data['nickname'] = $userInfo->nickName;
        $data['gender'] = $userInfo->gender;
        $data['language'] = $userInfo->language;
        $data['city'] = $userInfo->city;
        $data['province'] = $userInfo->province;
        $data['country'] = $userInfo->country;
        $data['avatarurl'] = $userInfo->avatarUrl;
        $row = $this->where("`openid` = '$openid'")->find();
        if ($row) {
            $result = $this->where("`openid`='{$openid}'")->save($data);
        } else {
            $data['openid'] = $openid;
            $data['create_time'] = $time;
            $insert_id = $this->add($data);
        }
        $info = $this->where("`openid`='{$openid}'")->find();
        return $info;
    }

    /**
     * 更改用户地区
     */
    public function updateRegion()
    {
        $data = array(
            "province_id" => $_GET['province_id'],
            "city_id" => $_GET['city_id'],
            "county_id" => $_GET['county_id'],
            "village_id" => $_GET['village_id'],
            "live_place" => $_GET['live_place']
        );
        return $this->where("`openid`='{$_GET['openid']}'")->save($data);
    }

    /**
     * 通过openid获取用户信息
     * @param  string $openid 用户标识
     * @return mix
     */
    public function findByOpenid($openid)
    {
        if ($openid) {
            return $this->where("`openid` = '$openid'")->find();
        } else {
            return false;
        }
    }

    /**
     * 增加可用佣金
     * @param  string $openid 用户标识
     * @param  float  $money  佣金
     * @return boolean
     */
    public function makeFund($openid, $money)
    {
        if ($openid) {
            if ($money || $money == 0) {
                $this->where("`openid` = '$openid'")->lock()->setInc("fund_enable", $money);
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
}