<?php
/**
 * Created by PhpStorm.
 * User: machengjun
 * Date: 2018/3/22
 * Time: 下午5:59
 */

namespace App\Repositories\Business;

use App\Exceptions\Api\ApiException;
use App\Modules\Enums\ErrorCode;
use App\Modules\Enums\RepairStatus;
use App\Modules\Models\RepairImages\RepairImages;
use App\Modules\Models\Repairs\Repairs;
use App\Modules\Repositories\BaseRepository;
use Illuminate\Support\Facades\DB;


/**
 * Class EloquentHistoryRepository.
 */
class RepairRepository extends BaseRepository
{

    /**
     * @param $input
     * @return mixed
     */
    public function create($input)
    {
        $repair = $this->createRepairStub($input);

        if ($repair != null) {
            DB::transaction(function () use ($repair, $input) {
                $repair->save();

                $pics = isset($input['pics']) ? $input['pics'] : array();
                if (count($pics) > 0) {
                    $pics_array = array();

                    foreach ($pics as $pic) {
                        if (!empty($pic)) {
                            array_push($pics_array, $this->createRepairImage($pic));
                        }
                    }

                    if (count($pics_array) > 0) {
                        $repair->images()->saveMany($pics_array);
                    }
                }
            });
        }

        return $repair;
    }

    /**
     * @param $pic
     * @return FeedbackImage
     */
    private function createRepairImage($pic)
    {
        $repairImage = new RepairImages();
        $repairImage->url = $pic;

        return $repairImage;
    }

    /**
     * @param $input
     * @return Feedback
     */
    private function createRepairStub($input)
    {
        $repairs = new Repairs();
        $repairs->system_users_id = $input['system_users_id'];
        $repairs->remark = $input['remark'];
        $repairs->tel = isset($input['tel']) ? $input['tel'] : "";
        $repairs->status = RepairStatus::UNPROCESSED;
        $repairs->spot_id = $input['spot_id'];
        $repairs->machine_id = $input['machine_id'];
        return $repairs;
    }


}