<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\model\AdminUser as AdminModel;
use think\facade\Db;

/**
 * 文档控制器
 * @package app\apicom\home
 */
class AdminUser extends AdminBase
{
    /*
     * 获取管理员列表
     */
    public function getList()
    {
        $name   = input('name', '');
        $mobile = input('mobile', '');
        $offset = input('pageSize',20, ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $order  = 'id desc';
        $where  = [];
        if(!empty($name))  $where[] = ['username','=', $name];
        if(!empty($mobile))$where[] = ['mobile','=', $mobile];
        $res = AdminModel::getList($where,$order,$offset);
        if($res){
            return ajaxmsg('操作成功',200, $res); 
        }else {
            return ajaxmsg('操作失败',0);
        }
    }
    /*
     * 启用/禁用 状态
     */
    public function doDisable()
    {
        $id     = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $status = input('status','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
		$res = AdminModel::where('id', $id)->save(['status'=> $status]);
        if ($res) {
            return ajaxmsg('操作成功',200);
        } else {
            return ajaxmsg('操作失败',0);
        }
    }
    /*
     * 删除管理员
     */
    public function delAdmin()
    {
        $id    = input('id','', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $count = AdminModel::count();
        //print_r($count);exit;
        if($count == 1) return ajaxmsg('最后一个不能删除',0);
		Db::startTrans();
		$res = AdminModel::where('id', $id)->delete();
        if ($res) {
            Db::commit();
            return ajaxmsg('操作成功',200);
        } else {
            Db::rollback();
            return ajaxmsg('操作失败',0);
        }
    }
    /* 
     * 修改/新增 管理员
     */
    public function editAdmin()
    {
        $data = input();
        if (isset($data['id']) && !empty($data['id'])) {
            // 验证数据
            $result = $this->validate($data, 'AdminUser.edit');
		    if ($result !== true) return ajaxmsg($result,0);
            if (!empty($data['password'])) $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
            $res = AdminModel::strict(false)->where(['id'=>$data['id']])->save($data);
    		if ($res) {
                return ajaxmsg('操作成功',200);
            } else {
                return ajaxmsg('操作失败',0);
            }
        } else {
            // 验证数据
            $result = $this->validate($data, 'AdminUser.create');
		    if ($result !== true) return ajaxmsg($result,0);
		    //print_r($data);exit;
            if (AdminModel::saveData($data)) return ajaxmsg('操作成功',200);
            return ajaxmsg('操作失败',0);
        }
		
    }
}