<?php

namespace App\Http\Controllers\Mobile\Health;

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\CompanyService;
use App\Services\Company\JobsService;
use App\Services\Company\PersonalJobsApplyService;
use App\Services\Content\AdService;
use App\Services\Content\FeedbackService;
use App\Services\Content\ReportService;
use App\Services\Content\TaskService;
use App\Services\Person\PersonFavoriteService;
use App\Services\Person\ResumeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class RecruitController extends MobileBaseController
{
    protected $jobsService;
    protected $resumeService;
    protected $categoryService;
    protected $feedbackService;
    protected $reportService;
    protected $taskService;
    protected $personalJobsApplyService;
    protected $companyService;
    protected $personFavoriteService;
    protected $adService;
    protected $searchService;
    protected $hotWordService;

    /**
     * JobsController constructor.
     * @param $JobsService
     * @param $resumeService
     * @param $categoryService
     * @param $feedbackService
     * @param $reportService
     * @param $taskService
     * @param $personalJobsApplyService
     * @param $companyService
     * @param $personFavoriteService
     * @param $adService
     * @param $searchService
     * @param $hotWordService
     */
    public function __construct(JobsService $jobsService, ResumeService $resumeService, CategoryService $categoryService, FeedbackService $feedbackService, ReportService $reportService, TaskService $taskService, PersonalJobsApplyService $personalJobsApplyService, CompanyService $companyService, PersonFavoriteService $personFavoriteService, AdService $adService, SearchService $searchService, HotWordService $hotWordService)
    {
        $this->jobsService              = $jobsService;
        $this->resumeService            = $resumeService;
        $this->categoryService          = $categoryService;
        $this->feedbackService          = $feedbackService;
        $this->reportService            = $reportService;
        $this->taskService              = $taskService;
        $this->personalJobsApplyService = $personalJobsApplyService;
        $this->companyService           = $companyService;
        $this->personFavoriteService    = $personFavoriteService;
        $this->adService                = $adService;
        $this->searchService            = $searchService;
        $this->hotWordService           = $hotWordService;
    }

    public function index()
    {
        return view('mobile.app.health.recruit.index');
    }

    public function list(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');
        if ($search_type == 'company') {
            return redirect(route('jobs.companyList', ['list_type' => 'AIX_companylist']));
        } else {
            session(['hotword_show_type' => 1]);
            //职位搜索
            $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);     //过滤条件信息
            //广告位
            $subsite_id       = Cache::has('subsite_id') ? Cache::get('subsite_id') : 0;
            $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', 'keyword', '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'];
            $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        = '';
            $where             = [];

            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'];
                }
            }
            $is_subsite = 0;
            $subsites   = Cache::get('subsites_list');
            if ($subsites) {
                if (!array_has($params, 'citycategory')) {
                    if (get_subsite_id() > 0) {
                        $citycategory = $subsites[get_subsite_id()]['district'];
                    }
                }
                $is_subsite = 1;
            }
            $citys = $this->categoryService->getCitys($citycategory);   //获取地标地段

            $district_info = $this->categoryService->getDefaultDistrictInfo(); //获取默认地区信息

            $where = $this->setWhere($params, $citys, $job_category);   //组合where条件

            if (config('aix.companyset.search_com.search_basic.jobs_search_login') == 1 && !auth('web-company')->check() && !auth('web-member')->check()) {
                $need_login_params = $param_array;
                if ($is_subsite == 1) {
                    unset($need_login_params[array_search('citycategory', $need_login_params)]);
                };
                foreach ($params as $k => $v) {
                    if (in_array($k, $need_login_params) && $v) {
                        $hidden_all_result = 1;
                        $where[]           = ['id', '=', 0]; //设置该条件使查询结果为空
                        break;
                    }
                }
                $show_login_notice = 1;
                $list_limit        = config('aix.companyset.search_com.search_basic.jobs_search_num_login');
            }

            $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(),
            ];
            return view('mobile.app.health.recruit.list', $return_data);
        }
    }

    public function will()
    {
        return view('mobile.app.health.recruit.will');
    }

    public function quanji()
    {
        return view('mobile.app.health.recruit.quanji');
    }

    public function show()
    {
        return view('mobile.app.health.recruit.show');
    }

    public function apply()
    {
        $district = $this->categoryService->getDefaultDistrict();
        return view('mobile.app.health.recruit.apply', [
            'defaultCity' => $district->defaultCity,
        ]);
    }

    public function setWhere($params, $citys, $job_category)
    {
        $where = [];
        //审核状态过滤
        if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
            $where[] = ['audit', '=', 1];
        } else {
            $where[] = ['audit', '<>', 3];
        }

        $where[] = ['valid', '=', 1];
        $where[] = ['display', '=', 1];
        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', $v];
                } elseif ($k != 'sort' && $k != 'key' && $k != 'search_type' && $k != 'm_zoom' && $k != 'range-lng' && $k != 'range-lat') {
                    $where[] = [$k, '=', $v];
                }
            }
        }
        return $where;
    }
}