<?php

namespace App\Http\Controllers\Mobile\Active;

use App\Http\Controllers\Mobile\MobileBaseController;
use App\Services\Common\CategoryService;
use App\Services\Common\HotWordService;
use App\Services\Common\SearchService;
use App\Services\Company\JobsService;
use App\Services\Content\AdService;
use Illuminate\Http\Request;

class FudaController extends MobileBaseController
{
    protected $categoryService;
    protected $adService;
    protected $hotWordService;
    protected $jobsService;
    protected $searchService;

    /**
     * JobsController constructor.
     * @param $JobsService
     */
    public function __construct(CategoryService $categoryService, AdService $adService, HotWordService $hotWordService, JobsService $jobsService, SearchService $searchService)
    {
        $this->categoryService = $categoryService;
        $this->adService       = $adService;
        $this->hotWordService  = $hotWordService;
        $this->jobsService     = $jobsService;
        $this->searchService   = $searchService;
    }

    public function index(Request $request)
    {
        if ($request->input('range-lng') != '' && $request->input('range-lat') != '') {
            $request->session()->put('range-lng', $request->input('range-lng'));
            $request->session()->put('range-lat', $request->input('range-lat'));
            $request->session()->put('range-laction', 1);
        };
        //查询条件
        $citycategory = $request->input('citycategory');
        $search_type  = $request->input('search_type', 'jobs');

        //职位搜索
        $job_category = $this->categoryService->getJobsCategoryInfo();      //获取职位分类信息
        $filter_where = [
            'AIX_wage'        => 100,
            'AIX_jobtag'      => 100,
            'AIX_trade'       => 100,
            'AIX_scale'       => 100,
            'AIX_jobs_nature' => 100,
            'AIX_education'   => 100,
            'AIX_experience'  => 100,
        ];
        $categories   = $this->categoryService->getCategories($filter_where);     //过滤条件信息

        //广告位
        $ad_where         = [
            'theme' => 'default',
            'org'   => 'Home',
            'alias' => 'AIX_jobs_list_right',
            'num'   => '1',
        ];
        $ad_infos         = $this->adService->getAds($ad_where);
        $hotWords         = $this->hotWordService->getHotWords(['type' => 1], 'list_order desc,w_hot desc', '21');    //热门关键词
        $job_hotwords     = array_slice($hotWords->toArray(), 0, 10);
        $company_hotwords = $this->hotWordService->getHotWords(['type' => 2], 'list_order desc,w_hot desc', '10');

        $param_array = ['citycategory', 'wage', 'jobtag', 'trade', 'scale', 'nature', 'education', 'experience', 'settr', 'jobcategory', 'key', 'sort', 'search_cont', 'license', 'deliver', 'search_type', 'lng', 'lat', 'range', 'wa', 'range-lng', 'range-lat', 'keyword'];
        $params      = [];
        if ($request->all()) {
            foreach ($request->all() as $k => $v) {
                if (in_array($k, $param_array) && $v) {
                    $params[$k] = $v;
                }
            }
        }
        $map_data = [];
        if (array_has($params, 'lng') && array_has($params, 'lat') && (array_has($params, 'range') || array_has($params, 'wa'))) {
            if (array_has($params, 'range')) {
                $map_data = ['lng' => $params['lng'], 'lat' => $params['lat'], 'range' => $params['range']];
            } elseif (array_has($params, 'wa')) {
                $map_data = ['lng' => $params['lng'], 'lat' => $params['lat'], 'range' => round($params['wa'] / 1000, 2)];
            } else {
                $map_data = ['lng' => $params['lng'], 'lat' => $params['lat'], 'range' => config('aix.system.map.map.map_range')];
            }
        } elseif (array_has($params, 'range') && !array_has($params, 'citycategory') && session("range-laction")) {
            $map_data = ['lng' => session("range-lng"), 'lat' => session("range-lat"), 'range' => $params['range']];
        }
        $show_range = false;
        if ($map_data) {
            $show_range = true;
        }
        $hidden_all_result = 0;
        $show_login_notice = 0;
        $list_limit        = '';
        $order_by          = ['stime' => 'desc', 'refresh_time' => 'desc'];
        $search_key        = '';

        if ($params) {
            $search_key = array_has($params, 'key') ? $params['key'] : '';
            if (array_has($params, 'sort')) {
                if ($params['sort'] == 'rtime') {
                    $order_by = 'refresh_time';
                } else {
                    $order_by = $params['sort'];
                }
            } else {
                $order_by = ['stime' => 'desc', 'refresh_time' => 'desc'];
            }
        }

        $citys         = $this->categoryService->getCitys($citycategory);   //获取地标地段
        $district_info = $this->categoryService->getDefaultDistrictInfo(); //获取默认地区信息
        $where         = $this->setWhere($params, $citys, $job_category);   //组合where条件
        $size          = 20;
        $list          = $this->searchService->search('Job', $where, $order_by, $search_key, $size);

        if ($list->total() > 0) {
            $list_items = $this->jobsService->dealjobFilelds($list->items(), $map_data);
        } else {
            $list_items = [];
        }

        $mobile_dropload = false;
        if ($list->total() > $size) {
            $mobile_dropload = true;
        }

        if ($request->ajax()) {
            if ($list->lastPage() < $list->currentPage()) {
                return response()->json(['status' => 0]);
            }
            return response()->json(['status' => 1, 'data' => view('mobile.app.content.jobs.ajax_job_list', ['params' => $params, 'list_items' => $list_items])->render()]);
        }

        $return_data = [
            'search_type'       => $search_type,
            'city'              => $citys,
            'categories'        => $categories,
            'params'            => $params,
            'district_info'     => $district_info,
            'job_category'      => $job_category,
            'ad_info'           => $ad_infos,
            'hotWords'          => $hotWords,
            'job_hotwords'      => $job_hotwords,
            'company_hotwords'  => $company_hotwords,
            'list'              => $list,
            'list_items'        => $list_items,
            'show_login_notice' => $show_login_notice,
            'hidden_all_result' => $hidden_all_result,
            'limit'             => $list_limit,
            'mobile_dropload'   => $mobile_dropload,
            'show_range'        => $show_range,
            'current_url'       => \Illuminate\Support\Facades\Request::getRequestUri(),
            'wap_title'         => '福州大学招聘会',
        ];
        return view('mobile.app.active.fuda', $return_data);
    }

    public function setWhere($params, $citys, $job_category)
    {
        $where = [];

        //审核状态过滤
        $where[] = ['audit', '=', 1];
        $where[] = ['valid', '=', 1];
        $where[] = ['display', '=', 1];
        $where[] = ['created_at', '>=', '2024-04-06 00:00:00'];

        if ($params) {
            foreach ($params as $k => $v) {
                if ($k == 'citycategory') {
                    //地标地段
                    $where[] = ['district', '=', $citys['select']['id']];
                } elseif ($k == 'jobcategory') {
                    //职位分类
                    if ($job_category && $v && array_get($job_category['spell'], $v)) {
                        if ($job_category && $v && array_get($job_category['spell'], $v)) {
                            $where[] = ['intention_jobs_id', '=', $job_category['spell'][$v]['id']];
                        }
                    }
                } elseif ($k == 'jobtag') {
                    //职位亮点
                    $where[] = ['tag', '=', $v];
                } elseif ($k == 'search_cont') {
                    if ($v == 'setmeal') {
                        //名企招聘
                        $where[] = ['setmeal_id', '>', 1];
                    }
                } elseif ($k == 'license') {
                    //营业执照
                    $where[] = ['company.certificate_img_audit', '=', 1];
                } elseif ($k == 'settr') {
                    //更新时间
                    $update_time = date('Y-m-d H:i:s', strtotime(date('Y-m-d', strtotime('-' . $v . ' day'))));
                    $where[]     = ['updated_at', '>=', $update_time];
                } elseif ($k == 'deliver') {
                    $where['apply'] = $v;
                } elseif ($k == 'wa') {
                    $where[] = ['range', '=', round($params['wa'] / 1000, 2)];
                    if (!(array_has($params, 'lng') && array_has($params, 'lat'))) {
                        $where[] = ['lng', '=', subsite_config('aix.system.map.map.map_x')];
                        $where[] = ['lat', '=', subsite_config('aix.system.map.map.map_y')];
                    }
                } elseif ($k == 'wage') {
                    //获取薪资最大值和最小值
                    $filter_where = ['AIX_wage' => 100];
                    $categories   = $this->categoryService->getCategories($filter_where);
                    if ($categories) {
                        $wage = $categories['AIX_wage'][$params['wage']]['origin_demand'];
                        if ($wage) {
                            $wage = format_wage($wage);
                        }
                        $wage_arr = explode_wage($wage);
                        $where[]  = $wage_arr[0];
                        $where[]  = $wage_arr[1];
                    }
                } elseif ($k == 'range') {
                    if (!array_has($params, 'citycategory')) {
                        if (!(array_has($params, 'lng') && array_has($params, 'lat'))) {
                            if (session('range-laction')) {
                                $where[] = ['range', '=', $params['range']];
                                $where[] = ['lng', '=', session('range-lng')];
                                $where[] = ['lat', '=', session('range-lat')];
                            }
                        }
                    }

                } elseif ($k == 'keyword') {
                    $where[] = ['jobs_name', 'like', "*{$params['keyword']}*"];
                } elseif ($k != 'sort' && $k != 'key' && $k != 'search_type' && $k != 'm_zoom' && $k != 'range-lng' && $k != 'range-lat') {
                    $where[] = [$k, '=', $v];
                }
            }
        }

        return $where;
    }

}