<?php

namespace app\models\user;

use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;

class BindUser extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'bind_user';

    use ModelTrait;

    /**
     * 创建用户信息记录
     */
    public static function addBindUser($openid, $nickname, $sex, $language, $city, $province, $country, $headimgurl, $type, $status, $mer_id = '')
    {
        $add_time = time();
        return self::create(compact('openid', 'nickname', 'sex', 'language', 'city', 'province', 'country', 'headimgurl', 'type', 'status', 'add_time', 'mer_id'));
    }

    /**
     * 更新用户信息记录
     */
    public static function editBindUser($openid, $nickname, $sex, $language, $city, $province, $country, $headimgurl)
    {
        return self::update(['openid' => $openid, 'nickname' => $nickname, 'sex' => $sex, 'language' => $language, 'city' => $city, 'province' => $province, 'country' => $country, 'headimgurl' => $headimgurl]);
    }

    /**
     * 绑定推送用户列表
     */
    public static function systemPage($where)
    {
        $model = self::setWhere($where);
        $count = $model->count();
        $list = $model->page((int)$where['page'], (int)$where['limit'])
            ->select();
        return compact('count', 'list');
    }

    /**
     * 设置 where 条件
     * @param $where
     * @param null $model
     * @return mixed
     */
    public static function setWhere($where, $model = null)
    {
        $model = $model === null ? new self() : $model;
        if (isset($where['mer_id']) && $where['mer_id'] != '') $model = $model->where('mer_id', $where['mer_id']);
        if (isset($where['nickname']) && $where['nickname'] != '') $model = $model->where('nickname', 'LIKE', "%$where[nickname]%");
        return $model->order('id desc')->where('is_del', 0);
    }
}