<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\controller\Base;
use plugin\admin\app\controller\Crud;
use plugin\admin\app\model\User as UserModel;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Throwable;

/**
 * OpenIM管理 
 */
class OpenimController  extends Crud
{
    
    /**
     * @var UserModel
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    function __construct()
    {
        $this->model = new UserModel();
        $groupList = [
            ['value'=>0,'label'=>"普通用户"],
            ['value'=>1,'label'=>"内部用户"],
            ['value'=>2,'label'=>"联盟商"],
        ];
        $roleList = \app\model\UserRole::order('id','desc')->column('name as label,id as value');
        $this->assign('groupList',$groupList);
        $this->assignconfig('groupList',$groupList);
        $this->assign('roleList',$roleList);
        $this->assignconfig('roleList',$roleList);
    }
    public function team(Request $request): Response
    {
        return view();
    }
    // public function select(Request $request): Response
    // {
    //     $this->model = $this->model->with(['referrer','role']);
    //     return parent::select($request);
    // }
    /**
     * 浏览
     * @return Response
     * @throws Throwable
     */
    public function index(Request $request): Response
    {
        return view('user/index');
    }
    public function select(Request $request): Response{
        $res = $request->IM->user->getUsers(1,20);
        //cp($request->IM->user->getAllUsersUid());
        if($res['errCode']!==0){
            return $this->fail($res['errDlt']);
        }
        return json([
            'code'  =>  0,
            "msg"   => "ok",
            'count'  =>  $res['data']['total'],
            'data'  =>$res['data']['users'],
        ]);
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('user/update',[
            'row'   => UserModel::findOrEmpty(0)
        ]);
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException|Throwable
     */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            [$id, $data] = $this->updateInput($request);
            $this->doUpdate($id, $data);
            $ret =  $this->success('操作成功');
            return $ret;
        }
        $ids = Request()->get('ids');
        $user = $this->model->where('id',$ids)->find();
        return view('user/update',[
            'row'   => $user
        ]);
    }
}
