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

namespace App\Http\Controllers\Api\Business;

use App\Http\Controllers\Controller;
use App\Repositories\Business\SpotRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class SpotController extends Controller
{


    protected $spot;


    public function __construct(SpotRepository $spot)
    {
        $this->spot = $spot;
    }


    public function profile(Request $request)
    {
        Log::info("[mySpotList]params" . json_encode($request->all()));
        $spot_obj = $this->spot->getToShowSpotObj($request->get('user'));
        $response['data'] = $this->_formatSpotProfile($spot_obj);
        return $this->responseSuccess($response);


    }


    public function mySpotList(Request $request)
    {
        Log::info("[mySpotList]params" . json_encode($request->all()));
        $spots_obj = $this->spot->getMylist($request->get('user'));
        $spot_id = $this->spot->getSelectedSpot($request->get('user'));
        $response = $this->_formatMySpotList($spots_obj, $spot_id);
        return $this->responseSuccess($response);
    }


    public function changeSpotSelected(Request $request)
    {
        $spot_id = $request->get('spot_id');
        //验证指定景点权限
        $this->spot->spotPermission($request->get('user'), $spot_id);
        $this->spot->setSpotSelected($request->get('user'), $spot_id);
        return $this->responseSuccess();
    }


    private function _formatSpotProfile($spot_obj)
    {
        $data = [
            'business_time' => $spot_obj->time . '-' . $spot_obj->overtime,
            'address' => $spot_obj->address,
            'spot_name' => $spot_obj->spotname,
        ];
        return $data;
    }

    private function _formatMySpotList($spots_obj, $selected_spot_id)
    {
        $data = [];

        if ($selected_spot_id) {
            foreach ($spots_obj as $k => $spot_obj) {
                if ($spot_obj->id == $selected_spot_id) {
                    $data['spots'][$k]['selected'] = 1;
                }
                $data['spots'][$k]['spot_id'] = $spot_obj->id;
                $data['spots'][$k]['spot_name'] = $spot_obj->spotname;
            }
        } else {
            foreach ($spots_obj as $k => $spot_obj) {
                if ($k == 0) {
                    $data['spots'][$k]['selected'] = 1;
                }
                $data['spots'][$k]['spot_id'] = $spot_obj->id;
                $data['spots'][$k]['spot_name'] = $spot_obj->spotname;
            }

        }
        return $data;
    }

}