<?php
/**
 * Created by PhpStorm.
 * User: qiuzijian
 * Date: 2021-04-15
 * Time: 17:28
 */

namespace Modules\Admin\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Modules\Admin\Auxiliary\View\FromAuxiliary;
use Modules\Admin\Auxiliary\View\TableAuxiliary;
use Modules\Admin\Enum\UserEnum;
use Modules\Admin\Services\UsersService;
use Spatie\Permission\Models\Permission;
use DB;

class UsersController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        $this->menusActive[0] = 'adminUsers';
        $this->menusActive[1] = 'adminUsersList';
    }

    //用户列表
    public function userList(Request $request)
    {
        $this->menusActive[0] = 'adminUsers';
        $this->menusActive[1] = 'adminUsersList';
        $query = User::where('id', '>', 0);

        if ($request->has('name_staffNum_mobile')) {
            $query = $query->where('staff_num', 'like', '%' . $request->input('name_staffNum_mobile') . '%')
                           ->orWhere('mobile', 'like', '%' . $request->input('name_staffNum_mobile') . '%')
                           ->orWhere('name', 'like', '%' . $request->input('name_staffNum_mobile') . '%');
        }

        $users = $query->paginate(50);

        $tableObj             = new TableAuxiliary('users/list', $users);
        $tableObj->primaryKey = 'staff_num';
//        $tableObj->topActions          = ['add', 'export', 'import', 'importTemplate'];
        $tableObj->topActions          = ['add'];
        $tableObj->displayActionOthers = [
            [
                'name'   => '更改权限',
                'path'   => 'users/roles/edit',
                'class'  => 'layui-btn-warm',
                'isShow' => function ($item) {
                    return true;
                },

            ],
            [
                'name'   => '重置密码',
                'path'   => 'users/list/resetpassword',
                'class'  => 'layui-btn-warm',
                'isShow' => function ($item) {
                    return true;
                },
                'isJump' => 'confirm',
            ]
        ];

        $tableObj->search('input', 'name_staffNum_mobile', '姓名、编号或手机号');
        $tableObj->column('name', '姓名')
                 ->column('staff_num', '用户编码')
                 ->column('mobile', '手机号');


        return $this->tableList($tableObj);
    }

    //查看用户详情
    public function userDetail(Request $request)
    {
        $staff_num = $request->input('staff_num');
        if (empty($staff_num)) {
            return redirect('/users/list/view');
        }
        $user     = User::where('staff_num', $staff_num)->first();
        $tableObj = new TableAuxiliary('', $user);
        $tableObj->column("name", "姓名")
                 ->column("mobile", "手机号")
                 ->column("staff_num", "员工编码");
        $tableObj->title = '用户详情';
        return $this->tableView($tableObj);
    }

    //添加用户
    public function add(Request $request)
    {
        $fromObj = new FromAuxiliary('users/list/add');
        $fromObj->input("name", "姓名")
                ->input("mobile", "手机号")
                ->input("staff_num", "用户编码");
        $fromObj->title = '添加职员';
        return $this->from($fromObj);
    }

    //添加用户操作
    public function addPost(Request $request)
    {
        if (!$request->has('staff_num') || $request->input('staff_num') == 'admin' || empty($request->input('staff_num'))) {
            return $this->error(1, '用户编码错误');
        }
        if (!$request->has('name') || empty($request->input('name'))) {
            return $this->error(1, '姓名不能为空');
        }

        $result = UsersService::addAdminUser($request->all());

        if (!$result['status']) {
            return $this->error(1, $result['msg']);
        }

        return redirect('/admin/users/list');
    }

    //编辑用户
    public function edit(Request $request)
    {
        $staff_num = $request->input('staff_num');
        if (empty($staff_num)) {
            return redirect('/admin/users/list');
        }

        $user = User::where('staff_num', $staff_num)->first();

        $fromObj = new FromAuxiliary('users/list/edit', $user);
        $fromObj->input("name", "姓名")
                ->input("mobile", "手机号")
                ->input("staff_num", "用户编码");
        $fromObj->title      = '修改用户信息';
        $fromObj->primaryKey = 'staff_num';
        return $this->from($fromObj);
    }

    //编辑用户操作
    public function editPost(Request $request)
    {
        if (!$request->has('staff_num') || $request->input('staff_num') == 'admin' || empty($request->input('staff_num'))) {
            return $this->error(1, '用户编码错误');
        }
        if (!$request->has('name') || empty($request->input('name'))) {
            return $this->error(1, '姓名不能为空');
        }

        $result = UsersService::editAdminUser($request->all());

        if (!$result['status']) {
            return $this->error(1, $result['msg']);
        }

        return redirect('/admin/users/list');
    }

    //删除用户
    public function delPost(Request $request)
    {
        if (!$request->has('staff_num')) {
            return $this->error(1, '缺少必要参数');
        }
        if ($request->input('staff_num') == 'admin') {
            return $this->error(1, '员工编码错误');
        }
        if ($request->input('staff_num') == $request->user()['staff_num']) {
            return $this->error(1, '不能删除自己');
        }

        $result = UsersService::delAdminUser($request->all());
        if (!$result['status']) {
            return $this->error(1, $result['msg']);
        }
        return $this->success();
    }

    //重置用户密码
    public function resetPassword(Request $request)
    {
        if (!$request->has('staff_num')) {
            return $this->error(1, '缺少必要参数');
        }

        $result = UsersService::resetPassword($request->all());
        if (!$result['status']) {
            return $this->error(1, $result['msg']);
        }
        return $this->success();
    }

    //权限修改
    public function roles(Request $request)
    {
        $params = $request->all();
        if ($request->isMethod('post')) {
            $res['mine_role'] = "";
            if(isset($params['mine_id'])){
                foreach($params['mine_id'] as $k=>$v){
                    $res['mine_role'] = $res['mine_role'] . $v . ';';
                }
                $res['mine_role'] = substr($res['mine_role'], 0, strlen($res['mine_role']) - 1);
            }
            DB::table('users')->where('staff_num',$params['staff_num'])->update($res);
            $data['code'] = 0;
            return $data;
        }

        $mine_parent = DB::table('mine_list')->where('parent_id',0)->where('deleted_at',null)->get();
        $data['menusAll'] = $mine_parent;
        $data['title']    = '更改权限';
        $user = DB::table('users')->where('staff_num',$params['staff_num'])->first();
        $checkedId = explode(';',$user->mine_role);
        foreach($checkedId as $k=>$v){
            $checkedId[$k] = (int)$v;
        }
        $data['checkedId'] = $checkedId;
        $data['staff_num'] = $params['staff_num'];
        return $this->view('admin::roles', $data);
    }
}