<?php

namespace App\Http\Controllers;

use App\Authority;
use App\Sign;
use App\UserWorkgroup;
use App\Warehouse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class UserWorkgroupController extends Controller
{
    public function index()
    {
        if(!Gate::allows('工作组-查询')){ return redirect(url('/'));  }
        $UserWorkgroups=UserWorkgroup::with(['wareHouse','signs'])->orderBy('id',"DESC")->paginate(50);
        return view('maintenance.userWorkgroup.index',['userWorkgroups'=>$UserWorkgroups]);
    }

    public function create()
    {
        if(!Gate::allows('工作组-录入')){ return redirect(url('/'));  }
        $warehouses=Warehouse::select('id','name')->get();
        return view('maintenance.userWorkgroup.create',['warehouses'=>$warehouses]);
    }


    public function store(Request $request)
    {
        if(!Gate::allows('工作组-录入')){ return redirect(url('/'));  }
        $id=false;
        $this->validatorUserWorkgroup($request,$id)->validate();
        $UserWorkgroup=new UserWorkgroup($request->input());
        $warehouseId=$request->input('warehouse_id');
        $UserWorkgroup['warehouse_id']=$warehouseId;
        $UserWorkgroup->save();
        $remark=$request->input('remark');
        $sign=new Sign([
            'signable_type'=>'user_workgroups',
            'signable_id'=>$UserWorkgroup['id'],
            'field'=>'is_need_remark',
            'mark'=>$remark,
        ]);
        $sign->save();
        $this->storeAuthority($UserWorkgroup['name'],$UserWorkgroup->id);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        return redirect('maintenance/userWorkgroup')->with('successTip','新工作组“'.$request->input('name').'”添加成功');
    }

    private function storeAuthority($name,$id){
        Authority::create([
            "name"=>$name,
            "alias_name"=>$name,
            "type"=>"工作组",
            "relevance"=>$id,
        ]);
    }

    public function edit($id)
    {
        if(!Gate::allows('工作组-编辑')){ return redirect(url('/'));  }
        $userWorkgroup=UserWorkgroup::with('signs')->find($id);
        if (!$userWorkgroup)return view('exception.404',['error'=>'工作组不存在！']);
        $warehouses=Warehouse::select('id','name')->get();
        return view('maintenance.userWorkgroup.edit',['userWorkgroup'=>$userWorkgroup,'warehouses'=>$warehouses]);
    }

    public function update(Request $request, $id)
    {
        if(!Gate::allows('工作组-编辑')){ return redirect(url('/'));  }
        $this->validatorUserWorkgroup($request,$id)->validate();
        $data=$request->input();
        $userWorkgroup=UserWorkgroup::with('signs')->find($id);
        $sign=$userWorkgroup->signs;
        $mark=$request->input('remark');
        if ($sign){
            $sign->mark=$mark;
            $sign->update();
            app('LogService')->log(__METHOD__,'工作组是否需要录入备注'.__FUNCTION__,json_encode($sign),Auth::user()['id']);
        }
        if(!$sign){
            $newSign=new Sign([
                'signable_type'=>'user_workgroups',
                'signable_id'=>$id,
                'field'=>'is_need_remark',
                'mark'=>$mark,
            ]);
            $newSign->save();
            app('LogService')->log(__METHOD__,'工作组是否需要录入备注'.__FUNCTION__,json_encode($sign),Auth::user()['id']);
        }
        $userWorkgroup['warehouse_id']= $data['warehouse_id'];
        if ($data['name']!=$userWorkgroup->name){
            $authority=Authority::where("name",$userWorkgroup->name)->first();
            if ($authority){
                $authority->name=$data['name'];
                $authority->alias_name=$data['name'];
                $authority->update();
            }
            if (!$authority){
                $this->storeAuthority($data['name'],$id);
            }
            $userWorkgroup->fill($data);
            $userWorkgroup->update();
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        }else{
            $userWorkgroup->update();
            app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($request->toArray()),Auth::user()['id']);
        }
        return redirect('maintenance/userWorkgroup')->with('successTip','工作组“'.$request->input('name').'”修改成功');
    }

    public function destroy($id)
    {
        if(!Gate::allows('工作组-删除')){ return redirect(url('/'));  }
        $UserWorkgroup=UserWorkgroup::with('signs')->find($id);
        app('LogService')->log(__METHOD__,__FUNCTION__,json_encode($UserWorkgroup),Auth::user()['id']);
        $result=$UserWorkgroup->delete();
        return ['success'=>$result];
    }

    public function validatorUserWorkgroup(Request $request,$id){
        if ($id){$name=$id;}
        $validator=Validator::make($request->input(),[
            'name'=>['required','max:10',isset($name)?"unique:user_workgroups,name,$name":'unique:user_workgroups,name'],
            'warehouse_id'=>['required'],
            'remark'=>['required'],
        ],[
            'required'=>':attribute 为必填项',
            'max'=>':attribute 过长',
            'unique'=>':attribute 已存在',
        ],[
            'name'=>'工作组名称',
            'warehouse_id'=>'仓库名称',
            'remark'=>'是否录入备注',
        ]);
        return $validator;
    }
}
