<?php

namespace app\admin\controller\user;

use Exception;
use ba\Random;
use think\facade\Db;
use app\common\controller\Backend;
use app\admin\model\User as UserModel;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class Identity extends Backend
{
    protected $model = null;
    
    protected $withJoinTable = ['group'];
    
    // 排除字段
    protected $preExcludeFields = ['lastlogintime', 'loginfailure', 'password', 'salt', 'money', 'score'];
    
    protected $quickSearchField = ['username', 'nickname', 'id'];
    
    public function initialize()
    {
        parent::initialize();
        $this->model = new UserModel();
    }
    
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        // if ($this->request->param('select')) {
        //     $this->select();
        // }
        
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withoutField('password,salt')
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where(['real_name_status' => [0, 2]])
            ->order($order)
            ->paginate($limit);
        
        // var_dump($res);
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
    
    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }
        
        // 重构：不需要修改密码，所以不需要这个字段
        // $row->password = '';
        
        if ($this->request->isPost()) {
            $password = $this->request->post('password', '');
            if ($password) {
                $this->model->resetPassword($id, $password);
            }
            parent::edit();
        }
        
        unset($row->salt);
        $row->password = '';
        $this->success('', [
            'row' => $row
        ]);
    }
    
    /**
     * 重写select
     */
    // public function select()
    // {
    //     $this->request->filter(['strip_tags', 'trim']);
    //
    //     list($where, $alias, $limit, $order) = $this->queryBuilder();
    //     $res = $this->model
    //         ->withJoin($this->withJoinTable, $this->withJoinType)
    //         ->alias($alias)
    //         // ->where($where)
    //         ->where(['real_name_status' => 1])
    //         ->order($order)
    //         ->paginate($limit);
    //     // var_dump($res);die;
    //     foreach ($res as $re) {
    //         $re->nickname_text = $re->username . '(ID:' . $re->id . ')';
    //     }
    //
    //     $this->success('', [
    //         'list'   => $res->items(),
    //         'total'  => $res->total(),
    //         'remark' => get_route_remark(),
    //     ]);
    // }
}