<?php

namespace App\Http\Controllers\Admin;

use App\Imports\WorkPointImport;
use App\Models\Option;
use App\Models\Project;
use App\Models\ProjectRole;
use App\Models\WorkPoint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;


class WorkPointController extends BaseController
{
    protected $model;

    protected $department;

    protected $model_name = '工点管理';

    protected $pre_uri = '/admin/WorkPoint/';

    protected $view_path = 'admin.work-points.';

    protected $redirect_index = '/admin/WorkPoint/index';

    public function __construct()
    {
        parent::__construct();
        $this->model = new WorkPoint();
    }

    public function index()
    {
        $project_id = Project::getOptions();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'index', compact('model', 'model_name','pre_uri','project_id'));
    }

    public function innerDevices()
    {
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'inner-devices', compact('model', 'model_name','pre_uri'));
    }

    public function get(Request $request)
    {
        $items = $this->model->orderBy('id', 'desc')->orderBy('created_at', 'desc');

        $tmp_items = collect(['name']);
        foreach($tmp_items as $tmp_item) {
            if($request->has($tmp_item) && !empty($request->input($tmp_item))) {
                $items = $items->where($tmp_item, 'like', '%' . $request->input($tmp_item) . '%');
            }
        }

        $select_items = collect([]);
        foreach($select_items as $select_item) {
            if($request->has($select_item) && !empty($request->input($select_item))) {
                $items = $items->where($select_item, '=', $request->input($select_item));
            }
        }
        if ($request->input('project_id'))
        {
            $items->whereHas('project',function ($query){
               $query->where('id','=',request('project_id'));
            });
        }
        $items = $items->paginate();

        foreach ($items as $item) {
            $item->status_label = $item->getNameOrLabel('status', 'label');
            $item->project_name = $item->project ? $item->project->name : '';
        }

        return response()->json(['code' => 0, 'message' => '', 'count' => $items->total(), 'data' => $items->items()]);
    }

    public function create()
    {
        $status_options = $this->model->getStatusOptions();
        $projects = Project::getOptions();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri', 'status_options', 'projects'));
    }

    public function store(Request $request)
    {
        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
        $validator = $this->model->getValidator($request, 'store');
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $data = $request->input('data');
        if (empty($data['status']))
        {
            return back()->withErrors(['sg_error_info' => '状态值为空']);
        }
        $res = $this->model->create($data);
        if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
        return redirect($this->pre_uri . 'create')->with(['sg_success_info' => '创建成功']);
    }
    public function edit(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        $status_options = $this->model->getStatusOptions();
        $projects = Project::getOptions();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'edit', compact('model', 'model_name', 'pre_uri', 'item', 'status_options', 'projects'));
    }

    public function update(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        if(empty($request->input('data')) || !is_array($request->input('data'))) return back()->withErrors(['sg_error_info' => '数据错误']);
        $validator = $this->model->getValidator($request, 'update');
        if($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        $data = $request->input('data');
        $res = $this->model->where('id', $request->input('id'))->update($data);
        if(!$res) return back()->withErrors(['sg_error_info' => '数据库保存失败！']);
        return back()->with(['sg_success_info' => '编辑成功']);
    }

    public function delete(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return response()->json(['status' => 'fail', 'info' => '找不到要删除的数据']);
        $res = $item->delete();
        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

    public function change(Request $request)
    {
        $this->model->where('id', $request->input('id'))->update(['status' => $request->input('status')]);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }
    public function exportTemplate(Request $request)
    {
        return response()->download(public_path() . '/工点导入模板.xlsx', '工点导入模板.xlsx', [
            'Content-Type: application/vnd.ms-excel'
        ]);
    }
    public function import(Request $request)
    {
        if(!$request->hasFile('file')) {
            return response()->json(['status' => 'error', 'info' => '参数错误']);
        }
        $file = $request->file('file');
        try {
            Excel::import(new WorkPointImport(), $file);
        } catch (ImportError $e) {
            return response()->json(['status' => 'error', 'info' => $e->getMessage()]);
        }
        return response()->json(['status' => 'success', 'info' => '上传成功']);
    }
}
