<?php

namespace common\models;

use yii\db\ActiveRecord;

/**
 * This is the model class for table "sh_user".
 *
 * @property integer $uid
 * @property string $openid
 * @property string $phone
 * @property integer $fx_uid
 * @property integer $status
 * @property string $nickname
 * @property string $headimgurl
 * @property integer $sex
 * @property string $country
 * @property string $province
 * @property string $city
 * @property string $reg_time
 */
class ShUser extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sh_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['status'], 'integer'],
            [['reg_time', 'last_login'], 'safe'],
            [['phone'], 'string', 'max' => 20],
            [['phone'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'uid' => 'Uid',
            'phone' => 'Phone',
            'status' => 'Status',
            'reg_time' => 'Reg Time',
            'last_login' => 'Last Login',
        ];
    }

    /**
     * Des:根据手机号获取用户ID 没有则注册一个
     * Name: getUidByPhone
     * @param $phone
     * @return int|mixed
     * @author 倪宗锋
     */
    public function getUidByPhone($phone)
    {
        $info = $this->getUserInfoByPhone($phone);
        if (empty($info['uid'])) {
            $this->addUser(['phone' => $phone]);
            $info = $this->getUserInfoByPhone($phone);
        }
        if (empty($info['uid'])) {
            return 0;
        }
        return $info['uid'];
    }

    /**
     * Des:根据手机号获取用户的信息
     * Name: getUserInfoByPhone
     * @param $phone
     * @return array
     * @author 倪宗锋
     */
    public function getUserInfoByPhone($phone)
    {
        $info = self::find()
            ->where(['=', 'phone', $phone])
            ->asArray()
            ->one();
        if (empty($info['uid'])) {
            return [];
        }
        return $info;
    }

    /**
     * Des: 添加用户
     * Name: addUser
     * @param $param
     * @return bool
     * @author 倪宗锋
     */
    public function addUser($param)
    {
        $this->setAttributes($param);
        $return = $this->insert(true);
        return $return;

    }


}
