<?php

namespace App\Http\Controllers\Admin;

use App\Models\Device;
use App\Models\DeviceName;
use App\Models\InnerDevice;
use App\Models\InnerDeviceNamesModel;
use App\Models\OrderDevice;
use App\Models\Project;
use App\Models\Spec;
use App\Models\WorkPoint;
use Illuminate\Http\Request;

class OrderDeviceController extends BaseController
{
    protected $model;

    protected $department;

    protected $model_name = '调用记录';

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

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

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

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

    public function index(Request $request)
    {
        $inner_device = InnerDevice::find($request->input('inner_device_id'));
        $inner_device->device_name_name = $inner_device->device_name ? $inner_device->device_name->name : '';
        $inner_device->spec_name = $inner_device->spec ? $inner_device->spec->name : '';
        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', 'inner_device'));
    }

    public function rentList()
    {
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        $options = ( new Device())->getDeviceOptions();
        $project_work_point_options = (new Project())->getTwoLevelOptions();
        return view($this->view_path . 'rent-list', compact('model', 'model_name','pre_uri','options','project_work_point_options'));
    }

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

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

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

        if($request->input('type') == 'rent') {
            $items = $items->whereNull('inner_device_id');

            if($request->input('work_point_id')){
                $items->whereHas('order',function ($query){
                    $query->where('work_point_id','=',request('work_point_id'));
                });
            }

        } else if($request->input('type') == 'apply') {
            $items = $items->whereNotNull('inner_device_id');
        }

        $items = $items->with('order');
        $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(['inner_device_id','device_id','device_name_id','spec_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));
            }
        }


        if ($request->input('order_id'))
        {
            $items->where('order_id','like','%'.$request->input('order_id').'%');
        }
        if ($request->input('number'))
        {
            $items->whereHas('inner_device',function ($query){
                $query->where('number','like','%'.request('number').'%');
            });
        }
        if ($request->input('spec_name'))
        {
            $items->whereHas('inner_device',function ($query){
                $query->where('spec_name','like','%'.request('spec_name').'%');
            });
        }
        if ($request->input('project_id'))
        {
            $items->whereHas('project',function ($query){
               $query->where('id','=',request('project_id'));
            });
        }
        if ($request->input('inner_device_name'))
        {
            $items->whereHas('inner_device',function ($query){
                $query->whereHas('device_name',function ($query){
                    $query->where('id','=',request('inner_device_name'));
                });
            });
        }

        $items = $items->paginate();

        if($request->input('type') == 'apply') {
            foreach ($items as $item) {
                $item->number = $item->inner_device ? $item->inner_device->number : '';
                $item->device_name_name = $item->inner_device ? ($item->inner_device->device_name ? $item->inner_device->device_name->name : '') : '';
                $item->spec_name = $item->inner_device ? ($item->inner_device->spec_name ? $item->inner_device->spec_name : '') : '';
                $item->project_name = $item->project ? $item->project->name : '';
                $item->work_point_name = $item->inner_device ? ($item->inner_device->workPoint ? $item->inner_device->workPoint->name : '') : '';
                $item->status_label = $item->inner_device ? $item->inner_device->getStatusLabel() : '';
            }
        } else {
            foreach ($items as $item) {
                $item->user_name = $item->user ? $item->user->name : '';
                $item->project_name = $item->project ? $item->project->name : '';
                $item->work_point_name = $item->order ? ($item->order->workPoint ? $item->order->workPoint->name : '') : '';
                $item->money = ($item->price * $item->quantity) / 100;
                $item->device_type_name = $item->device ? $item->device->name : '';
                $item->device_name_name = $item->device_name ? $item->device_name->name : '';
                $item->spec_name = $item->spec ? $item->spec->name : '';
                $item->rent_type_name = $item->rent_type ? $item->rent_type->name : '';
                $item->price = $item->price / 100;
            }
        }

        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);
        return view($this->view_path . 'create', compact('model', 'model_name','pre_uri'));
    }

    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');
        $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' => '找不到要编辑的数据']);
        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'));
    }

    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' => '操作成功']);
    }
}
