<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\Device;
use App\Models\DeviceName;
use App\Models\InnerDevice;
use App\Models\Notification;
use App\Models\Option;
use App\Models\Order;
use App\Models\OrderDevice;
use App\Models\OrderOverviewModel;
use App\Models\Project;
use App\Models\ProjectRole;
use App\Models\ProjectUser;
use App\Models\RentType;
use App\Models\Spec;
use App\Models\WorkPoint;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\DocBlock;

class OrderController extends BaseController
{
    protected $model;

    public function __construct()
    {
        $this->model = new Order();
    }

    public function create(Request $request)
    {
        $project = Project::find($request->input('project_id'));
        if(!$project) return $this->error(['msg' => '找不到项目']);
        $user = Auth::guard('mini')->user();
        $project_role = ProjectRole::getCreateRole('rent', $request->input('is_draft'));
        $option = Option::get('orders', 'status', 'checking');

        $order = Order::create([
            'work_point_id' => $request->input('work_point_id'),
            'remark' => $request->input('remark'),
            'is_draft' => $request->input('is_draft'),
            'status' => $option,
            'order_number' => $this->model->createOrderNumber(),
            'project_id' => $project->id,
            'user_id' => $user->id,
            'project_role_id' => $project_role ? $project_role['id'] : '',
            'level' => $project_role ? $project_role['level'] : '',
            'type' => 1
        ]);
        if(!$order) return $this->error(['msg' => '订单创建失败']);
        Notification::send($order->id);
        $order->updateOrderDevices($request->input('devices'));

        return $this->success();
    }

    public function getNameSpecRent($data)
    {
        $device = Device::find($data['type_id']);

        $rent_type = RentType::firstOrCreate([
            'name' => $data['rent']
        ]);
        if(!$device) return [
            'device_id' => '',
            'device_name_id' => '',
            'spec_id' => '',
            'rent_type_id' => $rent_type->id
        ];
        $device_name = DeviceName::firstOrCreate([
            'device_id' => $device->id,
            'name' => $data['name']
        ]);
        $spec = Spec::firstOrCreate([
            'device_id' => $device->id,
            'device_name_id' => $device_name->id,
            'name' => $data['spec']
        ]);
        return [
            'device_id' => $device->id,
            'device_name_id' => $device_name->id,
            'spec_id' => $spec->id,
            'rent_type_id' => $rent_type->id
        ];
    }

    public function createInner(Request $request)
    {
        $project = Project::find($request->input('project_id'));
        if(!$project) return $this->error(['msg' => '找不到项目']);
        $devices = $request->input('devices');
        $using_id = Option::get('inner_devices', 'status', 'using');
        $free_id = Option::get('inner_devices', 'status', 'free');

        // 续租时不检查设备使用状态
        if(!$request->input('type') || $request->input('type') != 're-rent') {
            foreach($devices as $device) {
                $device = InnerDevice::find($device['id']);
                if($device->status != $free_id) {
                    $status = Option::find($device->status);
                    $msg = $device['name'] . ($status ? $status['name'] : '使用中') . '，不能使用';
                    return $this->error(['msg' => $msg]);
                }
            }
        }

        $user = Auth::guard('mini')->user();
        $project_role = ProjectRole::getCreateRole('apply', $request->input('is_draft'));
        $option = Option::get('orders', 'status', 'checking');

        $order = Order::create([
            'remark' => $request->input('remark'),
            'is_draft' => $request->input('is_draft'),
            'status' => $option,
            'order_number' => $this->model->createOrderNumber(),
            'project_id' => $project->id,
            'user_id' => $user->id,
            'project_role_id' => $project_role ? $project_role['id'] : '',
            'level' => $project_role ? $project_role['level'] : '',
            'type' => 2,
            'is_change' => 2
        ]);
        if(!$order) return $this->error(['msg' => '订单创建失败']);
        foreach($devices as $device) {
            OrderDevice::create([
                'name' => $device['name'],
                'order_id' => $order->id,
                'project_id' => $order->project_id,
                'user_id' => $order->user_id,
                'inner_device_id' => $device['id'],
                'start_date' => $device['start_date'],
                'end_date' => $device['end_date']
            ]);
            if($device['id']) {
                InnerDevice::find($device['id'])->update([
                    'project_id' => $order['project_id'],
                    'status' => $using_id,
                    'start_date' => $device['start_date'],
                    'end_date' => $device['end_date'],
                ]);
            }
        }

        Notification::send($order->id);
        return $this->success();
    }

    public function getYears()
    {
        $date_arr = OrderOverviewModel::pluck('date')->toArray();
        $result = array_unique($date_arr);
        $years = [];
        foreach ($result as $value)
        {
            $year = date('Y',strtotime($value));
            array_push($years,$year);
        }
        $years = array_unique($years);
        return $this->success(['msg' => '获取年份成功', 'data' => $years]);
    }
    public function getOrderview(Request $request)
    {
        if ($request->input('year'))
        {
            $year = $request->input('year');
        }else
        {
            return $this->error(['msg' => '筛选年份缺失']);
        }
        if ($request->input('status'))
        {
            $status = $request->input('status');
        }else{
            $status = 2;
        }
        if ($request->input('project_id'))
        {
            $project_id = $request->input('project_id');
        } else
        {
            return $this->error(['msg' => '项目id缺失']);
        }
        //获取当前项目的当前年的所有月份的数据总览
        if ($status == 2)
        {
            $items = OrderOverviewModel::whereYear('date',$year)->where('project_id',$project_id)->get()->toArray();
            foreach ($items as &$item)
            {
                $dates = date('Y-m-d H:i:s',strtotime($item['date']));
                $item['dates'] = $dates;
                $item['date'] = date('Y年m月',strtotime($item['date']));
                $item['total_price'] = $item['total_price']/100;
                $item['status'] = $item['status'] ? '已确认':'未确认';
                $item['confirmation_user_id'] = User::where('id',$item['confirmation_user_id'])->value('name');
                $item['project_id'] = Project::where('id',$item['project_id'])->value('name');
                $item['confirmation_time'] = $item['confirmation_time'] ? date('Y-m-d',strtotime($item['confirmation_time'])): '暂无';
            }
        }else
        {
            $items = OrderOverviewModel::whereYear('date',$year)->where('project_id',$project_id)->where('status',$status)->get()->toArray();
            foreach ($items as &$item)
            {
                $dates = date('Y-m-d H:i:s',strtotime($item['date']));
                $item['dates'] = $dates;
                $item['date'] = date('Y年m月',strtotime($item['date']));
                $item['total_price'] = $item['total_price']/100;
                $item['status'] = $item['status'] ? '已确认':'未确认';
                $item['confirmation_user_id'] = User::where('id',$item['confirmation_user_id'])->value('name');
                $item['project_id'] = Project::where('id',$item['project_id'])->value('name');
                $item['confirmation_time'] = $item['confirmation_time'] ?date('Y-m-d',$item['confirmation_time']): '暂无';
            }
        }
        return $this->success(['msg' => '获取订单数据总览成功', 'data' => $items]);

    }
    public function getOrderDetails(Request $request)
    {
        if ($request->input('user_id'))
        {
            $user = $request->input('user_id');
        }else
        {
            return $this->error(['msg' => '登录的用户id缺失']);
        }
        if ($request->input('order_sn'))
        {
            $order_sn = $request->input('order_sn');
        }else
        {
            return $this->error(['msg' => '订单号缺失']);
        }
        if ($request->input('dates'))
        {
            $dates = $request->input('dates');
        }else
        {
            return $this->error(['msg' => '订单时间缺失']);
        }
        if ($request->input('project_id'))
        {
            $project_id = $request->input('project_id');
        }else
        {
            return $this->error(['msg' => '项目id缺失']);
        }
        $project_manager_id = Project::where('id',$project_id)->value('user_id');
        if ($project_manager_id == $user)
        {
            $is_manager = true;
        }else
        {
            $is_manager = false;

        }
        //获取到订单总览数据
        $order_view = OrderOverviewModel::where('order_sn',$order_sn)->first();
        $order_view->date = date('Y年m月',strtotime($order_view->date));
        $order_view->total_price = $order_view->total_price/100;
        $order_view->project_id = Project::where('id',$order_view->project_id)->value('name');
        $order_view->confirmation_time = $order_view->confirmation_time ? date('Y-m-d',strtotime($order_view->confirmation_time)): '暂无';
        $order_view->status = $order_view->status ? '已确认':'未确认';
        $before_time = strtotime($dates);
        //获取订单详情
        $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',$project_id)
            ->where('status',3)
            ->where('type',1)
            ->whereBetween('updated_at',[$before_times,$now])
            ->pluck('id')->toArray();
        $items = OrderDevice::where('project_id',$request->input('project_id'))->whereIn('order_id',$order_arr)->get()->toArray();
        $data = [];
        foreach ($items as $key=>$item) {
            $device = Device::where('id',$item['device_id'])->value('name');
            $device_name = DeviceName::where('id',$item['device_name_id'])->value('name');
            $spec_name =   Spec::where('id',$item['spec_id'])->value('name');
            $data[$key][] = $device.'-'.$device_name.'-'.$spec_name;
            $user_id = Order::where('id',$item['order_id'])->value('user_id');
            $data[$key][] = User::where('id',$user_id)->value('name');
            $data[$key][] = ($item['price']*$item['quantity'])/100;
        }
        return $this->success(['msg' => '获取账单详情成功', 'data' => $data,'order_view' => $order_view,'is_manager'=>$is_manager]);
    }
    public function updateOrderviewStatus (Request $request)
    {
        if ($request->input('order_sn'))
        {
            $order_sn = $request->input('order_sn');
        }else
        {
            return $this->error(['msg' => '订单号缺失']);
        }
        if ($request->input('time'))
        {
            $time = $request->input('time');
        }else
        {
            return $this->error(['msg' => '确认时间缺失']);
        }
        OrderOverviewModel::where('order_sn',$order_sn)->update(['status'=> 1,'confirmation_time'=>$time]);
        return $this->success(['msg' => '更新订单状态成功']);
    }

    public function update(Request $request)
    {
        $order = $this->model->find($request->input('id'));
        if(!$order) return $this->error(['msg' => '找不到订单']);
        $user = Auth::guard('mini')->user();
        $project_role = ProjectRole::getCreateRole('rent', $request->input('is_draft'));
        $option = Option::get('orders', 'status', 'checking');
        $res = $order->update([
            'work_point_id' => $request->input('work_point_id'),
            'remark' => $request->input('remark'),
            'is_draft' => $request->input('is_draft'),
            'status' => $option,
            'order_number' => $this->model->createOrderNumber(),
            'user_id' => $user->id,
            'project_role_id' => $project_role ? $project_role['id'] : '',
            'level' => $project_role ? $project_role['level'] : ''
        ]);
        if(!$res) return $this->error(['msg' => '订单修改失败']);
        $order->updateOrderDevices($request->input('devices'));
        return $this->success();
    }

    public function updateInner(Request $request)
    {
        $order = $this->model->find($request->input('id'));
        if(!$order) return $this->error(['msg' => '找不到订单']);
        $user = Auth::guard('mini')->user();
        $project_role = ProjectRole::getCreateRole('apply', $request->input('is_draft'));
        $type = $request->input('type');
        $option = Option::get('orders', 'status', 'checking');
        if($type == 'back') {
            $option = Option::get('orders', 'status', 'back');
        }

        $res = $order->update([
            'work_point_id' => $request->input('work_point_id'),
            'remark' => $request->input('remark'),
            'is_draft' => $request->input('is_draft'),
            'status' => $option,
            'user_id' => $user->id,
            'project_role_id' => $project_role ? $project_role['id'] : '',
            'level' => $project_role ? $project_role['level'] : '',
        ]);
        if(!$res) return $this->error(['msg' => '订单修改失败']);
        $devices = $request->input('devices');
        if($type == 'back') {
            foreach($devices as $device) {
                if($device['id']) {
                    InnerDevice::find($device['id'])->update([
                        'project_id' => '',
                        'start_date' => '',
                        'end_date' => '',
                        'work_point_id' => '',
                        'status' => Option::get('inner_devices', 'status', 'free')
                    ]);
                }
            }
        } else {
            $order->updateOrderDevices($devices);
        }

        return $this->success();
    }

    //订单列表
    public function get(Request $request)
    {
        $user = Auth::guard('mini')->user();
        $project_role = $user->getTopRole();
        if($project_role) {
            $project_role->rights = $project_role->getRights();
        }
        //判断是否有租赁查看权限
        if($project_role->rights['rentView'] == true){
            $items = $this->model->join('users', 'orders.user_id', '=', 'users.id')->where('status','!=',4)->select('orders.*', 'users.id as user_id', 'users.name');
        } else {
            $items = $this->model->join('users', 'orders.user_id', '=', 'users.id')->select('orders.*', 'users.id as user_id', 'users.name');
        }

        //取对应项目的工点
        $level = $user->getLevel($request->input('project_id'));

        $search_items = [
            ['project_id', $request->input('project_id')],
            ['level', '>=', $level]
        ];
        $is_draft = $request->input('is_draft');

        $project_user = ProjectUser::where([
            ['user_id', $user->id],
            ['project_id', $request->input('project_id')]
        ])->first();

        if($project_user) {
            $project_role = ProjectRole::find($project_user->project_role_id);
            if($project_role) {
                $rights = $project_role->getRights();
                if(isset($rights) && $rights['rentView']) {
                    unset($search_items[1]);
                }
            }
        }

        if($is_draft) {
            $search_items['is_draft'] = $is_draft;
            if($is_draft == 1) {
                $search_items['user_id'] = $user->id;
            }
        }
        $statu = $request->input('status');
        if($request->input('status')) {
//            if($statu == 'reject'){
//                unset($search_items[1]);
//                $search_items[] = ['last_project_role_id',$level];
//            }
            $status = Option::get('orders', 'status', $request->input('status'));
            if($status) {
                array_push($search_items, ['status', '=', $status]);
            };
        }
        $equal_items = ['work_point_id', 'type'];
        foreach ($equal_items as $item) {
            if($request->input($item)) {
                array_push($search_items, [$item, '=', $request->input($item)]);
            }
        }
        $items = $items->where($search_items);
        if($request->input('keyword')) {
            $keyword = '%' . $request->input('keyword') . '%';
            $items = $items->where(function ($query) use($keyword) {
                $query->where('order_number', 'like', $keyword)->orWhere('users.name', 'like', $keyword);
            });
        }
        $items = $items->orderBy('updated_at', 'desc');
        $items = $items->paginate();
        foreach($items as $item) {
            $item->formatOrder($item);
        }
        return $this->success(['data' => $items->items()]);
    }


    public function formatOrder($item)
    {
        $option = Option::find($item->status);
        $item->status = $item->getStatusName();
        $item->status_key = $option ? $option['key'] : '';
        $item->color = $option ? $option['color'] : '';
        $item->date_time = substr($item->created_at, 0, 16);
    }

    public function detail(Request $request)
    {
        $order = $this->model->with('project', 'workPoint', 'user', 'innerDevices', 'order_devices')->find($request->input('id'));
        if(!$order) return $this->error(['msg' => '找不到订单']);
        $this->formatOrder($order);
        foreach($order['innerDevices'] as $device) {
            $device->device = Device::find($device->device_id);
            $device->device_name = DeviceName::find($device->device_name_id);
            $device->status = Option::find($device->status);
            $device->spec = Spec::find($device->spec);
            $device->work_point = $order['workPoint'];
            $device->init_start_date = $device->start_date;
            $device->init_end_date = $device->end_date;
        }
        foreach($order['order_devices'] as $order_device) {
            $order_device->device_type = Device::find($order_device->device_id);
            $order_device->device_name = DeviceName::find($order_device->device_name_id);
            $order_device->spec = Spec::find($order_device->spec_id);
            $order_device->rent_type = RentType::find($order_device->rent_type_id);
        }
        return $this->success(['data' => $order]);
    }

    public function getRole(Request $request)
    {
        $user = Auth::guard('mini')->user();
        $project_user = ProjectUser::where([
            ['project_id', '=', $request->input('id')],
            ['user_id', '=', $user->id]
        ])->first();
        $project_role = null;
        if($project_user) {
            $project_role = ProjectRole::find($project_user->project_role_id);
            if($project_role) {
                $project_role->rights = $project_role->getRights();
            }
        }
        return $this->success(['data' => $project_role]);
    }

    public function check(Request $request)
    {
        $user = Auth::guard('mini')->user();
        $order = $this->model->find($request->input('id'));
        if(!$order) return $this->error(['msg' => '找不到订单']);
        $project_user = ProjectUser::where([
            ['project_id', '=', $order->project_id],
            ['user_id', '=', $user->id]
        ])->first();
        if(!$project_user) return $this->error(['msg' => '找不到用户']);
        $project_role = ProjectRole::find($project_user->project_role_id);
        if(!$project_role) return $this->error(['msg' => '找不到角色']);
        $status = Option::get('orders', 'status', $request->input('type'));
        $next_project_role = null;
        $is_inner = $order->type == 2;
        $new_order = null;
        // 工区负责人确认通过
        if($request->input('type') == 'pass') {
            $status = Option::get('orders', 'status', 'pass');
            $next_project_role = $project_role;
        } else if($request->input('type') == 're-submit') {
            $status = Option::get('orders', 'status', 'checking');
            $next_project_role = $project_role->getNext(null, $is_inner);
            $order->updateOrderDevices($request->input('devices'));
        } else if($request->input('type') == 'reject') {
            $next_project_role = ProjectRole::getFirstRole($order);
            $next_project_role['level'] =$project_role->level;
        } else if($request->input('type') == 'back') {
            $new_order = $order->backInnerDevices($request->input('devices'));
            // 没有返回新订单，是全部归还
            if(!$new_order) {
                $status = Option::get('orders', 'status', 'pass');
                // 全部归还，下一角色改为最高角色
                $next_project_role = ProjectRole::getLastRole($order);
                OrderDevice::where('order_id', $order->id)->update(['end_date' => Carbon::now()->toDateString()]);
            } else {
                // 部分归还，状态保持，下一角色保持，上一角色保持
                $status = $order->status;
                $next_project_role = ProjectRole::find($order->project_role_id);
                $project_role = ProjectRole::find($order->last_project_role_id);
            }
        } else {
            // 审核
            $next_project_role = $project_role->getNext(null, $is_inner);
        }
        $is_change = $request->input('is_change');

        $level = $next_project_role ? $next_project_role['level'] : '';
        if($request->input('type') == 'pass') {
            $last_role = ProjectRole::getLastRole($order);
            $level = $last_role ? $last_role['level'] : '';
        }

        $res = $order->update([
            'status' => $status,
            'last_project_role_id' => $project_role->id,
            'project_role_id' => $next_project_role ? $next_project_role['id'] : '',
            'level' => $level,
            'is_change' => $is_change,
            'remark' => $request->input('remark')
        ]);

        if($request->input('type') == 'back') {
            if($new_order) {
                // 部分归还
                Notification::send($new_order->id);
            } else {
                // 全部归还
                Notification::send($order->id);
            }
        } else {
            Notification::send($order->id);
        }

        if($res) return $this->success();
        return $this->error(['msg' => '操作失败']);
    }

    public function change(Request $request)
    {
        $order_device = OrderDevice::find($request->input('id'));
        if(!$order_device) return $this->error(['msg' => '找不到设备']);
        $order_device->update([
            'quantity' => $request->input('quantity')
        ]);
        $order = $this->model->find($order_device['order_id']);
        if(!$order) return $this->error(['msg' => '找不到订单']);
        $order->updateMoney();
        return $this->success();
    }

    public function delete(Request $request)
    {
        if($request->input('id')) {
            $id = $request->input('id');
            $this->model->where('id', $id)->delete();
            $inner_device_ids = OrderDevice::where('order_id', $id)->pluck('inner_device_id');
            if($inner_device_ids) {
                $free_id = Option::get('inner_devices', 'status', 'free');
                InnerDevice::where('id', $inner_device_ids)->update([
                    'status' => $free_id,
                    'start_date' => null,
                    'end_date' => null,
                    'work_point_id' => ''
                ]);
            }
            Notification::where('order_id', $id)->delete();
            OrderDevice::where('order_id', $id)->delete();
        }
        return $this->success();
    }
}
