<?php

namespace App\Http\Controllers\Admin;

use App\Model\Adminuser;
use App\Model\Department;
use App\Model\Job;
use App\Model\Tablelist;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Admin\CommonController;
use Session;

class DepartmentController extends CommonController
{

    public function index()
    {

        $data = Department::orderby('id', 'asc')->paginate(20);

        return view('admin.department.index', compact('data'));

    }

    public function edit($dep_id)
    {

        if (!$data = Department::find($dep_id)) return back()->withErrors('未找到数据');

        return view('admin.department.edit', compact('data'));
    }

    public function create()
    {

        return view('admin.department.create');

    }

    public function update($dep_id)
    {

        if (!Department::where('id', $dep_id)->update(Input::except('_token', '_method'))) return back()->withErrors('机构信息更新失败，请稍后重试!');

        return redirect('/department');

    }

    public function destroy($dep_id)
    {

        if (!Department::where('id', $dep_id)->delete()) return ['status' => 0, 'msg' => '删除失败，请刷新重试！'];

        return ['status' => 1, 'msg' => '删除成功！'];

    }

    public function store()
    {

        $input = Input::except('_token');

        $input['display'] = '1';

        $validator = Validator::make($input, [
            'department_description' => 'max:200',
            'department_name' => 'required|max:100',
        ], [
            'department_name.required' => '名称不能为空！',
            'department_description.max' => '描述不能超过100字！',
            'department_name.max' => '名称请保持在50字内！',
        ]);

        if ($validator->fails()) return back()->withErrors($validator);

        if (!Department::create($input)) return back()->withErrors('新建失败，请稍后重试！');

        return redirect('/department');

    }


    public function ting($dep_id)
    {

        if (!Department::where('id', $dep_id)->update(['display' => 0])) return ['status' => '1', 'msg' => '隐藏失败！'];

        return ['status' => '0','msg' => '隐藏成功！'];

    }

    public function start($dep_id)
    {

        if (!Department::where('id', $dep_id)->update(['display' => 1])) return ['status' => '0', 'msg' => '显示失败！'];

        return ['status' => '1','msg' => '显示成功！'];

    }

}