<?php

namespace app\admin\controller;

use app\BaseController;
use app\admin\model\User as UserModel;
use Exception;

class User extends BaseController
{

    /**
     * @api {get} /user/list 用户列表
     */
    function list()
    {
        try {
            $params = $this->request->param();
            $page = $params['page'] ?? 1;
            $limit = $params['limit'] ?? 15;
            $user_id = $params['user_id'] ?? '';
            $name = $params['name'] ?? '';
            $role = $params['role'] ?? 0;
            
            $query = new UserModel();
            if ($role == 0) {
                $query = $query->where('role', 0);
            } else {
                $query = $query->where('role', 3);
            }
            if (!empty($user_id)) {
                $query = $query->where('user_id', $user_id);
            }
            if (!empty($name)) {
                $query = $query->where(function ($query) use ($name) {
                    $query->where('account', 'like', "%{$name}%")
                        ->whereOr('phone', 'like', "%{$name}%")
                        ->whereOr('realname', 'like', "%{$name}%");
                });
            }

            $count = $query->count();
            $list = $query->order('last_login_time','desc')
                        ->limit($limit)
                        ->page($page)
                        ->select();
            foreach($list as &$item) {
                $item['last_login_time'] = date('Y-m-d H:i:s', $item['last_login_time']);
                $item['offline_time'] = $item['offline_time'] ? date('Y-m-d H:i:s', $item['offline_time']) : '';
            }
        } catch (Exception $e) {
            return $this->error($e->getMessage());
        }
        return $this->success(['count' => $count, 'list' => $list]);
    }

    //设置用户状态
    public function setStatus()
    {
        
        $user_id = (int)$this->request->param('user_id');
        $user = UserModel::where('user_id', $user_id)->find();
        if (!$user) {
            return $this->error('用户不存在');
        }
        $user->status = $user->status == 0 ? 1 : 0;
        $user->save();
        return $this->success($user);
    }

}