<?php

namespace app\admin\controller;

use app\common\model\Admin as AmdinModel;
use app\admin\controller\AuthBase;

class Admin extends AuthBase
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $keyword = trim(input('get.word'));

        $map = array();
        if ($keyword) {
            $map['name'] = ['like', "%".$keyword."%"];
        }
        $admins = AmdinModel::where($map)
            ->order('id', 'desc')->paginate(20, false, [
                'query' => [
                    'k' => $keyword
                ]
            ]);

        $this->assign('admins', $admins);
        return $this->fetch();
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $admin = AmdinModel::get(trim($id));
        if ($admin) {
            $data['user'] = $admin;
            return json_encode(['error'=>0, 'msg'=>'获取成功', 'data'=>$data]);
        } else {
            return json_encode(['error'=>1, 'msg'=>'获取失败']);
        }
    }

    /**
     * 更新
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function update($id)
    {
        if (request()->isPost()) {
            $admin = AmdinModel::get(trim($id));
            if ($admin) {
                $name = input("post.name");
                $password = input("post.password");
                $update = false;
                if ($name != $admin->name) {
                    $admin->name = $name;
                    $update = true;
                }
                if ($password && md5($password)!=$admin->password) {
                    $admin->password = md5($password);
                    $update = true;
                }
                if ($update && $admin->save()) {
                    // 更改当前管理员的session名称
                    if (session("uid")==$admin->id) {
                        session('username', $admin->name);
                    }
                    return json_encode(['error'=>0, 'msg'=>'更新成功']);
                }else{
                    return json_encode(['error'=>1, 'msg'=>'没有任何修改']);
                }
            }else{
                return json_encode(['error'=>1, 'msg'=>'未找到对象']);
            }
        }else{
            return json_encode(['error'=>1, 'msg'=>'请求方法错误']);
        }
    }
    
    
}
