<?php

namespace App\Http\Controllers\Api\mini;

use App\Models\InnerDevice;
use App\Models\Option;
use App\Models\Part;
use App\Models\Project;
use App\Models\RentType;
use App\Models\RepairDevice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RepairDeviceController extends BaseController
{
    protected $model;

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

    public function create(Request $request)
    {
        $project = Project::find($request->input('project_id'));
        if(!$project) return $this->error(['msg' => '找不到项目']);
//        $user = Auth::guard('mini')->user();

        $data = $request->only(['project_id', 'work_point_id', 'inner_device_id', 'reason', 'day', 'remark', 'money']);
        $user = Auth::guard('mini')->user();
        $data['user_id'] = $user ? $user->id : '';
        $data['money'] = $this->transMoney($request->input('money'));

        $repair = $this->model->create($data);
        $repair_status = Option::get('inner_devices', 'status', 'repair');
        InnerDevice::where('id', $data['inner_device_id'])->update([
            'status' => $repair_status
        ]);
        if(!$repair) return $this->error(['msg' => '订单失败']);
        $parts = $request->input('parts');
        if($parts) {
            foreach($parts as $item) {
                $price = $this->transMoney($item['price']);
                $item['price'] = $price;
                Part::create(array_merge($item, [
                    'repair_device_id' => $repair->id
                ]));
            }
        }

        return $this->success();
    }

    public function get(Request $request)
    {
        $items = $this->model->where('inner_device_id', $request->input('id'))->with('parts', 'project', 'user')->get();
        foreach($items as $item) {
            $item->date = substr($item->created_at, 0 ,10);
        }
        return $this->success(['data' => $items]);
    }
}
