<?php
namespace app\admin\controller;

use app\admin\validate\AdminValidate as Validate;
use think\Exception;
use think\facade\Session;
use think\Request;
use app\admin\model\AdminModel as Model;

/**
 * 管理员管理控制器
 * 管理员的增删改查
 * 初始化密码等操作
 * Class Admin
 * @package app\admin\controller
 */
class Admin extends Base
{
    public function index(Model $model)
    {
        $data = $model->select();
        $this->assign('data',$data);
        return $this->fetch('index');
    }

    public function create()
    {
    	return $this->fetch('add');
    }

    public function store(Request $request, Validate $validate, Model $model)
    {
        $data = $request->post();

        if(!$validate->scene('create')->check($data)){
            return jsonErr($validate->getError());
        }

        $model->name = $data['name'];
        $model->password = decrypt($data['password']);

        if($model->save()){
            return jsonSuc('添加数据成功');
        } else {
            return jsonErr('添加数据失败');
        }
    }

    public function delete(Request $request,Model $model)
    {
        $id = $request->post('id') + 0;

        if(is_int($id)){

            $admin = $model->find($id);
            $resNum = $admin->delete();

            if($resNum){
                return jsonSuc('已删除');
            } else {
                return jsonErr('删除失败，请重试');
            }
        } else {
            throw new Exception('错误的变量参数',1);
        }
    }

    public function edit($id = 0, Model $model){
        $id = $id + 0;
        if($id > 0){
            $admin = $model->field('id,name')->find($id);
            $this->assign('data',$admin);
            return $this->fetch('edit');
        }
        throw new Exception('id参数不正确', 1);
    }

    public function update(Request $request, Validate $validate, Model $model)
    {
        $data = $request->post();

        if(!$validate->scene('update')->check($data)){
            return jsonErr($validate->getError());
        }

        $model = $model->find($data['id']);
        $model->password = $model->setPass($data['password']);

        if($model->save()){
            return jsonSuc('更新数据成功');
        } else {
            return jsonErr('更新数据失败');
        }
    }


}
