<?php
namespace app\user\controller;

use app\admin\controller\Base;
use app\admin\model\DepartmentModel;
use app\admin\model\RoleModel;
use app\admin\model\StaffModel;
use app\admin\model\StaffRoleModel;
use app\admin\validate\StaffValidate;
use think\Request;


/**
 * 员工控制器
 * 负责员工的增删改查
 * 员工密码的初始化
 * Class Staff
 * @package app\admin\controller
 */
class Staff extends Base
{
    public function index()
    {
        $data = StaffModel::select();
        $this->assign('data',$data);
        return $this->fetch('index');
    }

    public function create()
    {
        $model =  new DepartmentModel;
        $data = $model->getDepartmentTree();
        $this->assign('data',$data);
        return $this->fetch('add');
    }

    public function edit($id){
        $staff = StaffModel::find($id);
    }

    public function store(Request $request){

        $validate = new StaffValidate;

        if(!$validate->check($request->post())){
            return json([
                'status' => 0,
                'message' => $validate->getError()
            ]);
        }

        $staff = new StaffModel;
        $staff->name = $request->post('name');
        $staff->email = $request->post('email');
        $staff->d_id = $request->post('d_id');
        $staff->tel = $request->post('tel') + 0;
        $staff->identity = $request->post('identity');
        $staff->status = $request->post('status');

        if($staff->save()){
            return json([
                'status' => 1,
                'message' => '添加员工成功'
            ]);
        } else {
            return json([
                'status' => 1,
                'message' => '添加员工失败'
            ]);
        }
    }

    public function delete(Request $request){
        $id =  $request->post('id');

        if(is_int($id + 0) && ($id + 0) > 0) {
            $staff =StaffModel::get($id);

            if(!$staff){
                return json([
                    'status'=>0,
                    'message'=>'删除失败，用户不存在'
                ]);
            }

            //如果删除成功
            if($staff->delete()){
                //删除权限
                return $this->role_del($staff);
            } else {
                return json([
                    'status' => 0,
                    'message' => '删除失败,请重试'
                ]);
            }
        } else {
            return json([
                'status' => 0,
                'message' => '参数错误'
            ]);
        }
    }

    //配置员工所属角色匹配角色所属权限
    public function role(){
        $data = StaffModel::with('roles')->select();
        $this->assign('data',$data);
        $this->assign('empty','<span class="layui-bg-orange">[没有权限]</span>');
        return $this->fetch('role');
    }

    public function role_edit($id){
        $data = StaffModel::with('roles')->field('id,name')->find($id)->toArray();
        $roles = RoleModel::field('id,title')->select()->toArray();

        //筛选匹配的键
        foreach ($roles as $key => $role){
            foreach ($data['roles'] as  $drole){
                if($drole['id'] == $role['id']){
                    $roles[$key]['checked'] = true;
                }
            }
            if(!isset($roles[$key]['checked'])){
                $roles[$key]['checked'] = false;
            }
        }
        $this->assign('roles',$roles);
        $this->assign('data',$data);
        return  $this->fetch('role_edit');
    }

    /**
     * 添加用户权限
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     *
     */
    public function role_update(Request $request){

        $id = $request->post('id');
        $roles = $request->post('role');

        if(!$id){
            return json([
                'status' => 0,
                'message' => '参数有错误刷新之后添加'
            ]);
        }

        $staffRole = StaffRoleModel::where(['staff_id'=>$id])->find();

        //如果没有记录，则更新
        if($staffRole) {
            //先清除所有权限
            StaffRoleModel::where(['staff_id' => $id])->delete();
        }

        //生成权限数据
        $staffRoleList = [];
        foreach ($roles as $key => $role){
            $staffRoleList[$key]['staff_id'] = $id;
            $staffRoleList[$key]['role_id'] = $role;
        }

        //批量插入权限
        if((new StaffRoleModel)->saveAll($staffRoleList)){
            return json([
                'status'=>1,
                'message' => '添加权限成功'
            ]);
        } else {
            return json([
                'status' =>0,
                'message' => '添加权限失败'
            ]);
        }
    }


    public function role_del($staff=''){

        if(!empty($staff)){
            $id = $staff->id;
        } else {
            $id =  Request::post('id');
        }

        if(is_int($id + 0) && ($id + 0) > 0){
            if(StaffRoleModel::where(['staff_id' => $id])->delete()){
                return json([
                    'status' => 1,
                    'message' => '删除权限成功'
                ]);
            } else {
                return json([
                    'status' => 0,
                    'message' => '删除失败，用户没有设置权限'
                ]);
            }
        } else {
            return json([
                'status' => 0,
                'message' => '参数错误'
            ]);
        }
    }
}