<?php

namespace app\index\controller;

use app\index\controller\Base;
use app\index\model\UserModel;

class User extends Base{

    //用户列表
    public function UserList()
    {
        $param = input('param.');

        $limit = isset($param['pageSize']) ? $param['pageSize'] : 10;
        $param['pageNumber'] = isset($param['pageNumber']) ? $param['pageNumber'] : 1;
        $offset = ($param['pageNumber'] - 1) * $limit;

        $where = [];
        if (!empty($param['searchText'])) {
            $where['username'] = ['like', '%' . $param['searchText'] . '%'];
        }
        $user = new UserModel();
        $selectResult = $user->getUsersByWhere($where, $offset, $limit);

        $status = ['1' => '启用' , '2' => '禁用'];

        // 拼装参数
        foreach($selectResult as $key=>$vo){
            $selectResult[$key]['status_text'] = $status[$vo['status']];
            if($vo['last_login_time'] == null){
                $selectResult[$key]['last_login_time'] = '';
            }
            if($vo['update_timestamp'] == null){
                $selectResult[$key]['update_timestamp'] = '';
            }
        }

        $return['total'] = $user->getAllUsers($where);  //总数据
        $return['rows'] = $selectResult;
        json_success($return);
    }

    // 添加用户
    public function UserAdd()
    {
        $param = input('param.');
        $valid = $this->validate($param,'UserValidate');
        if($valid!== true){
            return json(json_error_exception('1007',$valid));
        }
        $param['password'] = md5($param['password']);
        $user = new UserModel();
        $flag = $user->insertUser($param);
        if($flag['code'] != 1){
            return json(json_error_exception('1006',$flag['msg']));
        }
        json_success([]);
    }

    // 删除用户
    public function UserDel()
    {
        $id = input('param.id');
        if($id == session('id')){
            json_error(1006,'不可删除当前登录用户');
        }
        $UserModel = new UserModel();
        $flag = $UserModel->delUser($id);
        if($flag['code'] != 1){
            return json(json_error_exception('1006',$flag['msg']));
        }
        json_success([]);
    }

    public function EditPwd(){
        $param = input('param.');
        $valid = $this->validate($param,'PwdValidate');
        if($valid!== true){
            return json(json_error_exception('1007',$valid));
        }
        $userid = session('id');
        $user = UserModel::find($userid);
        $password = md5($param['password']);
        if($user['password'] == $password){
            json_success([]);
        }else{
            $model = new UserModel();
            $ret = $model->save(['password' => $password] , ['id' => $userid]);
            if($ret == false){
                return json(json_error_exception('1006'));
            }else{
                json_success([]);
            }
        }
    }
}