<?php

namespace App\Http\Controllers\Admin;

use App\Models\Device;
use App\Models\DeviceName;
use App\Models\InnerDeviceNamesModel;
use App\Models\Order;
use App\Models\OrderDevice;
use App\Models\OrderOverviewModel;
use App\Models\Project;
use App\Models\Spec;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class OrderOverviewController extends BaseController
{
    protected $model;

    protected $department;

    protected $model_name = '账单明细列表';

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

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

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

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

    public function index()
    {
        $project_ids = Project::getNotOneProjectOptions();
        $status = [
            [
                'id' => 1,
                'name' => '未确认'
            ],
            [
                'id' => 2,
                'name' => '已确认'
            ]
        ];
        $date = OrderOverviewModel::pluck('date','id')->toArray();
        $date = array_unique($date);
        $dates = [];
        foreach ($date as $key =>$value)
        {
            $name = date('Y-m',strtotime($value));
            array_push($dates,$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','project_ids','status','dates'));
    }
    public function orderDetails(Request $request)
    {
        $device_id = Device::get(['id','name'])->toArray();
        list($model, $model_name, $pre_uri) = array($this->model, $this->model_name, $this->pre_uri);
        return view($this->view_path . 'order-details', compact('model', 'model_name','pre_uri','device_id'));
    }

    public function get(Request $request)
    {
        if($request->input('type') == 'details') {
            $before_time = strtotime($request->input('date'));
            $before_times = date('Y-m-d H:i:s',$before_time);
            $now = strtotime('+1 month',$before_time);
            $now = date('Y-m-d H:i:s',$now);
            $order_arr = Order::where('project_id',$request->input('project_id'))
                ->where('status',3)
                ->where('type',1)
                ->whereBetween('updated_at',[$before_times,$now])
                ->pluck('id')->toArray();
            $items = $this->order_device->where('project_id',$request->input('project_id'))->whereIn('order_id',$order_arr);
        }else{
            $items = $this->model->where('id', '>', 0)->orderBy('id','desc');
        }
        if ($request->input('project_ids'))
        {
            $items->whereHas('projects',function ($query){
                    $query->where('id','=',request('project_ids'));
                });
        }
        if ($request->input('status'))
        {
            if ($request->input('status') == 1)
            {
                $items->where('status',0);
            }else if ($request->input('status') == 2)
                {
                    $items->where('status',1);
                }
        }
        if ($request->input('order_sn'))
        {
            $items->where('order_sn','like','%'.request('order_sn').'%');
        }
        if ($request->input('dates'))
        {
            $dates = $request->input('dates').'-01 00:00:00';
            $items->where('date',$dates);
        }
        if ($request->input('device_id'))
        {
            $items->where('device_id',request('device_id'));
        }

            $items = $items->paginate(15);
        if ($request->input('type') == 'details')
        {
            foreach ($items as $item) {
                $device = $item->device ? $item->device->name : '';
                $device_name = $item->device_name ? $item->device_name->name : '';
                $spec_name =   $item->spec ? $item->spec->name : '';
                $item->name = $device.'-'.$device_name.'-'.$spec_name;
                $user_id = Order::where('id',$item->order_id)->value('user_id');
                $item->user_name = User::where('id',$user_id)->value('name');
                $item->price = ($item->price*$item->quantity)/100;
            }

        }else
        {
            foreach ($items as $item) {
                $item->dates = date('Y-m',strtotime($item->date));
                $item->project_name = $item->projects ? $item->projects->name : '';
                $item->total_price = $item->total_price/100;
                $item->status = $item->status?'已确认':'未确认';
                $item->confirmation_user_id = $item->user ? $item->user->name : '';
                $item->phone = $item->user ? $item->user->phone : '';
            }
        }


        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' => '找不到要删除的数据']);
        DeviceName::where('device_id', $item->id)->delete();
        Spec::where('device_id', $item->id)->delete();
        $res = $item->delete();
        if (!$res) return response()->json(['status' => 'fail', 'info' => '删除失败']);
        return response()->json(['status' => 'success', 'info' => '操作成功']);
    }

}
