<?php
/**
 * Created by PhpStorm.
 * User: wesley
 * Date: 2018/12/12
 * Time: 上午9:48
 */

namespace App\Http\Controllers\Admin\Company;

use App\Http\Controllers\Admin\Controller;
use App\Models\CompanyInfoModel;
use App\Models\UserCompanyCollectionModel;
use App\Repositories\Company\InfoRepository;
use Illuminate\Http\Request;

class CollectionController extends Controller
{

    private $repository;

    public function __construct(InfoRepository $repository)
    {
        if (!$this->repository) $this->repository = $repository;
    }

    /***
     * 创建公海
     * @param Request $request
     * @return int
     */
    public function create(Request $request)
    {
        $user_id = \Auth::guard('admin')->user()->id;
        $filter_fields = $request->except('_token');

        $isCreated = UserCompanyCollectionModel::where('user_id',$user_id)->first();
        if($isCreated){

            $isCreated->filter_fields = json_encode($filter_fields);
            $isCreated->save();
        }else{
            $data['user_id'] = $user_id;
            $data['filter_fields'] = json_encode($filter_fields);
            $data['name'] = '我的公海';
            UserCompanyCollectionModel::create($data);
        }
        return 200;
    }

    /***
     * 公海列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
     * @throws \Throwable
     */
    public function index(Request $request)
    {

        $user_id = \Auth::guard('admin')->user()->id;
        $collection = UserCompanyCollectionModel::where('user_id', $user_id)->first();

        if (count($collection)) {
            $search = (array)json_decode($collection->filter_fields);
            $order = array();
            if (isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
                $order[$request['sort_field']] = $request['sort_field_by'];
            } else {
                $order['id'] = 'DESC';
            }

            if ($request->ajax()) {
                $keywords = $request->all();
                $search = array_merge(array_filter($keywords), array_filter($search));

                $list = $this->repository->searchCompany($search, $order, 20);

                $view = view('admin.company.collection.data', compact('list'))->render();
                return response()->json(['html' => $view]);
            }

            $list = $this->repository->searchCompany($search, $order, 20);
            $fields = (new CompanyInfoModel())->filterFields;

            return view('admin.company.collection.index', compact('list', 'fields'));
        } else {
            return '您暂未创建过公海！';
        }

    }
}