<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ImportError;
use App\Imports\InnerDeviceImport;
use App\Models\Device;
use App\Models\DeviceName;
use App\Models\InnerDevice;
use App\Models\Option;
use App\Models\Project;
use App\Models\WorkPoint;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use phpDocumentor\Reflection\DocBlock;

class InnerDeviceController extends BaseController
{
    protected $model;
    
    protected $device;

    protected $device_name;

    protected $department;

    protected $model_name = '设备';

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

    protected $view_path = 'admin.inner-devices.';

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

    public function __construct()
    {
        parent::__construct();
        $this->model = new InnerDevice();
        $this->device = new Device();
        $this->device_name = new DeviceName();
    }

    public function index()
    {
        $options = $this->device_name->getNameSpecOptions();
        $statuses = Option::get('inner_devices', 'status');
        $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', 'options', 'statuses','project_id'));
    }

    public function get(Request $request)
    {
        $items = $this->model->where('id', '>', 0)->with(['device', 'spec', 'device_name','inner_device_names'])->orderBy('id','asc');

        $tmp_items = collect(['number']);
        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) . '%');
            }
        }

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

        $select_items = collect(['device_id', 'device_name_id', 'spec_id', 'status', 'work_point_id','project_id']);
        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));
            }
        }
        //排序
        $items = $items->orderBy('updated_at', 'desc')->paginate();
//        dd($items);
        foreach ($items as $item) {
            $item->device_type = $item->device ? $item->device->name : '';
            $item->device_name_name = $item->inner_device_names ? $item->inner_device_names->name : '';
            $item->spec_name = $item->spec_name ? $item->spec_name : '';
            $item->status = $item->getStatusLabel();
            $item->work_point_name = $item->workPoint ? $item->workPoint->name : '';
            $item->project_name = $item->project ? $item->project->name : '';
        }


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

    public function create()
    {
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        $options = $this->device_name->getNameSpecOptions();
        $status_options = Option::get('inner_devices', 'status');
//        $project_work_point_options = (new Project())->getTwoLevelOptions();
        $project_options = Project::getNotOneProjectOptions();

        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri', 'options', 'status_options', 'project_options'));
    }

    public function transObject($items)
    {
        return json_decode(json_encode($items));
    }

    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');
        $data = array_merge($data, $request->only(['device_id', 'device_name_id', 'spec_name', 'project_id', 'work_point_id']));
        $res = $this->model->create($data);
        if(empty($res)) return back()->withErrors(['sg_error_info' => '保存失败']);
        return redirect($this->pre_uri . 'index')->with(['sg_success_info' => '创建成功']);
    }

    public function exportTemplate(Request $request)
    {
        return response()->download(public_path() . '/内部设备导入模板.xlsx', '内部设备导入模板.xlsx', [
            'Content-Type: application/vnd.ms-excel'
        ]);
    }

    public function edit(Request $request)
    {
        if(empty($request->input('id')) || empty($item = $this->model->find($request->input('id')))) return back()->withErrors(['sg_error_info' => '找不到要编辑的数据']);
        $options = $this->device_name->getNameSpecOptions();
        $status_options = Option::get('inner_devices', 'status');
//        $project_work_point_options = (new Project())->getTwoLevelOptions();
        $project_options = Project::getNotOneProjectOptions();
        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', 'options', 'status_options', 'project_options'));
    }

    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');
        $data = array_merge($data, $request->only(['device_id', 'device_name_id', 'spec_name', 'project_id', 'work_point_id']));
        $res = $this->model->where('id', $request->input('id'))->update($data);
        if(!$res) return back()->withErrors(['sg_error_info' => '数据库保存失败！']);
        return redirect($this->pre_uri . 'index')->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 import(Request $request)
    {
        if(!$request->hasFile('file')) {
            return response()->json(['status' => 'error', 'info' => '参数错误']);
        }
        $file = $request->file('file');
        try {
            Excel::import(new InnerDeviceImport(), $file);
        } catch (ImportError $e) {
            return response()->json(['status' => 'error', 'info' => $e->getMessage()]);
        }
        return response()->json(['status' => 'success', 'info' => '上传成功']);
    }
}
