<?php

namespace App\Http\Controllers\Jkq\Content;

use App\Http\Controllers\Jkq\JkqBaseController;
use App\Repositories\MemberLogRepository;
use App\Services\Common\CategoryService;
use App\Services\Company\JobsService;
use App\Services\Content\FeedbackService;
use Illuminate\Http\Request;
use App\Exceptions\ResponseException;
use App\Services\Content\ReportService;
use App\Services\Content\TaskService;
use App\Services\Company\PersonalJobsApplyService;
use App\Services\Company\CompanyService;
use App\Services\Person\PersonFavoriteService;
use App\Services\Content\AdService;
use App\Services\Common\SearchService;
use App\Services\Common\HotWordService;
use App\Validators\Content\ReportValidatorRequest;
use App\Validators\Content\MsgValidatorRequest;
use Illuminate\Support\Facades\Cache;

class JobsController extends JkqBaseController
{
    protected $jobsService;
    protected $categoryService;
    protected $feedbackService;
    protected $reportService;
    protected $taskService;
    protected $personalJobsApplyService;
    protected $companyService;
    protected $personFavoriteService;
    protected $adService;
    protected $searchService;
    protected $hotWordService;
    protected $memberLogRepository;

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

    public function index(Request $request)
    {
        $citycategory = 'jjkfq';
        $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);     //过滤条件信息
            //广告位
            $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', 'apply', 'search_type', 'lng', 'lat', 'range', 'wa', 'wage_min', 'wage_max'];
            $params      = [];
            if ($request->all()) {
                foreach ($request->all() as $k => $v) {
                    if (in_array($k, $param_array) && $v) {
                        $params[$k] = $v;
                    }
                }
            }
            //处理薪资参数
            $deal_params      = $params;
            $customize_params = $params;
            $nowage_params    = $params;
            if (array_has($params, 'wage') && (array_has($params, 'wage_min') || array_has($params, 'wage_max'))) {
                unset($deal_params['wage']);
                unset($nowage_params['wage']);
            }
            if (array_has($customize_params, 'wage_min')) {
                unset($customize_params['wage_min']);
                unset($nowage_params['wage_min']);
            }
            if (array_has($customize_params, 'wage_max')) {
                unset($customize_params['wage_max']);
                unset($nowage_params['wage_max']);
            }

            $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')];
                }

            }
            $show_filter  = false;
            $filter_array = ['sort', 'search_cont', 'license', 'apply', 'search_type'];
            if ($params && (count($params) <= count($filter_array))) {
                foreach ($params as $k => $v) {
                    if (!in_array($k, $filter_array)) {
                        $show_filter = true;
                        break;
                    }
                }
            } elseif (count($params) > count($filter_array)) {
                $show_filter = 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'];
                }
            }
            $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($deal_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');
            }

            $callback = function ($query) {
                $query->with(['company.membersSetmeal']);
            };
            $list     = $this->searchService->search('Job', $where, $order_by, $search_key, '10', '', $callback);
            if ($list->total() > 0) {
                $list_items = $this->jobsService->dealjobFilelds($list->items(), $map_data);
            } else {
                $list_items = [];
            }
            $emergency_jobs = $this->searchService->searchEmergencyJobs(4);       //紧急招聘
            $recommend_jobs = $this->searchService->searchRecommendJobs(5, $this->getUser());   //推荐职位

            //设置职位默认显示方式
            if (!session('jobs_show_type')) {
                $type = config('aix.companyset.comset.show_set.jobs_list_show_type');
                session(['jobs_show_type' => $type]);
            }

            //设置薪资视图显示
            $wage_info = '';
            if (array_has($params, 'wage_min') || array_has($params, 'wage_max')) {
                $wage_min = array_has($params, 'wage_min') ? array_get($params, 'wage_min') : 0;
                $wage_max = array_has($params, 'wage_max') ? array_get($params, 'wage_max') : 0;
                if ($wage_min > 0 && $wage_max == 0) {
                    $wage_info = $wage_min . '以上/月';
                } elseif ($wage_min == 0 && $wage_max > 0) {
                    $wage_info = $wage_min . '以下/月';
                } else {
                    $wage_info = $wage_min . '-' . $wage_max . '/月';
                }
                //$wage_info = $this->jobsService->dealWage(0, $wage_min, $wage_max);
            } elseif (array_has($params, 'wage')) {
                if (array_has($categories, 'AIX_wage') && array_has($categories['AIX_wage'], $params['wage'])) {
                    $wage_info = $categories['AIX_wage'][$params['wage']]['demand'];
                }
            }

            $return_data = [
                'search_type'       => $search_type,
                'city'              => $citys,
                'categories'        => $categories,
                'params'            => $params,
                'wage_params'       => $deal_params,
                'customize_params'  => $customize_params,
                'nowage_params'     => $nowage_params,
                'wage_info'         => $wage_info,
                '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,
                'show_filter'       => $show_filter,
                'limit'             => $list_limit,
                'emergency_jobs'    => $emergency_jobs,
                'recommend_jobs'    => $recommend_jobs,
            ];
            return view('jkq.jobs.list', $return_data);
        }
    }

    public function comList(Request $request)
    {
        session(['hotword_show_type' => 2]);
        $return_data = [];
        $search_key  = $request->input('key', '');
        $trade       = $request->input('trade');
        $nature      = $request->input('nature');
        $param_array = ['key', 'trade', 'nature'];
        $params      = [];
        $where       = [];
        if ($request->all()) {
            foreach ($request->all() as $k => $v) {
                if (in_array($k, $param_array) && $v) {
                    $params[$k] = $v;
                    if ($k != 'key') {
                        $where[] = [$k, '=', $v];
                    }
                }
            }
        }
        $where[] = ['user_status', '=', 1];
        $where[] = ['subsite_ids', '=', get_subsite_id()];

        //$order_by = array('refresh_time'=>'desc','id'=>'desc');
        $order_by = '';
        $list     = $this->searchService->search('Company', $where, $order_by, $search_key);
        if ($list->total() > 0) {
            //处理企业信息
            $list_items = $this->companyService->dealCompanyFields($list->items());
        } else {
            $list_items = [];
        }

        $filter_where = [
            'AIX_trade'        => 100,
            'AIX_company_type' => 100,
        ];
        $categories   = $this->categoryService->getCategories($filter_where);

        //热门关键字
        $job_hotwords     = $this->hotWordService->getHotWords(['type' => 1], 'list_order desc,w_hot desc', '10');
        $company_hotwords = $this->hotWordService->getHotWords(['type' => 2], 'list_order desc,w_hot desc', '10');

        $return_data = [
            'search_type'      => 'company',
            'params'           => $params,
            'categories'       => $categories,
            'list'             => $list,
            'list_items'       => $list_items,
            'job_hotwords'     => $job_hotwords,
            'company_hotwords' => $company_hotwords,
        ];
        //企业搜索
        return view('jkq.jobs.company_list', $return_data);
    }

    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 == 'apply') {
                    $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 == 'wage_min') {
                    $where[] = ['wage_min', '>=', $v];
                } elseif ($k == 'wage_max') {
                    $where[] = ['wage_max', '<=', $v];
                } elseif ($k != 'sort' && $k != 'key' && $k != 'search_type' && $k != 'm_zoom') {
                    $where[] = [$k, '=', $v];
                }
            }
        }
        $where[] = ['subsite_ids', '=', get_subsite_id()];
        return $where;
    }

    public function category()
    {
        session(['hotword_show_type' => 1]);
        $serch_type    = null;
        $district_info = $this->categoryService->getDefaultDistrictInfo();
        //获取职位分类信息
        $job_cates = $this->categoryService->getJobsCategories();
        //dd($job_cates[0]);
        $citys = $this->categoryService->getCitys();

        $job_hotwords     = $this->hotWordService->getHotWords(['type' => 1], 'list_order desc,w_hot desc', '10');
        $company_hotwords = $this->hotWordService->getHotWords(['type' => 2], 'list_order desc,w_hot desc', '10');

        $return_data = [
            'search_type'      => $serch_type,
            'city'             => $citys,
            'district_info'    => $district_info,
            'job_hotwords'     => $job_hotwords,
            'company_hotwords' => $company_hotwords,
            'job_cates'        => $job_cates,
        ];
        return view('jkq.jobs.category', $return_data);
    }

    public function hotWord(Request $request)
    {
        $key = $request->input('query', '');
        $key = trim($key);
        if (!$key) {
            return response()->json(['status' => 0, 'msg' => '请输入关健字!']);
        }
    }

    public function getUser()
    {
        $user = [];
        if (auth('web-member')->check()) {
            $user = auth('web-member')->user();
        } elseif (auth('web-company')->check()) {
            $user = auth('web-company')->user();
        }
        return $user;
    }

    public function show(Request $request)
    {
        $job_id  = $request->input('id');
        $job_rst = $this->jobsService->getJobInfo(['id' => $job_id], $this->getUser());    //获取job信息
        if ($job_rst['status'] == 0) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage($job_rst['error'], $back_url, true, '上一页', '3');
        }
        $job_info  = $job_rst['job'];
        $cate_jobs = $this->searchService->searchCateJobs($job_info, 6);      //看了此职位的人还会看(同类别6条其它职位)
        $this->putSeoData('job', $job_info);
        //当前公司的其它职位
        $other_where = [
            ['company_id', '=', $job_info->company_id],
            ['valid', '=', 1],
            ['display', '=', 1],
            ['id', '<>', $job_id],
        ];
        if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
            $other_where[] = ['audit', '=', 1];
        } else {
            $other_where[] = ['audit', '<>', 3];
        }
        $other_jobs  = $this->jobsService->getOtherJobs($other_where, 6);
        $return_data = [
            'info'         => $job_info,
            'other_jobs'   => $other_jobs,
            'cate_jobs'    => $cate_jobs,
            'redirect_url' => route('jobs.show', ['id' => $job_info->id]),
        ];
        return view('jkq.jobs.job_show', $return_data);
    }

    public function click(Request $request)
    {
        $id   = $request->input('id');
        $rst  = $this->jobsService->incrementData(['id' => $id], 1, 'click');
        $data = ['status' => 0];
        if ($rst) {
            $data = ['status' => 1];
        }
        return response()->json($data);
    }

    //留言
    public function sendMsg(MsgValidatorRequest $request)
    {
        $form_data = [
            'parent_id'  => $request->input('parent_id', '0'),
            'touid'      => $request->input('touid'),
            'message'    => $request->input('message'),
            'ip'         => ip2long($request->getClientIp()),
            'subsite_id' => get_subsite_id(),
            'ip_address' => '本机地址',
        ];

        $rst = $this->feedbackService->sendMsg($form_data, 3);
        if ($rst) {
            $data = ['status' => 1, 'msg' => '反馈成功,感谢您对本站的关注!', 'insert_id' => $rst['data']['id']];
        } else {
            $data = ['msg' => '数据保存失败!'];
        }
        return response()->json($data);
    }

    //收藏职位
    public function favor(Request $request)
    {
        $jid         = $request->jid;
        $reg         = $this->jobsService->jobFavor($jid);
        $return_data = ['status' => 0, 'msg' => '收藏失败!'];
        if ($reg) {
            $return_data = ['status' => 1, 'msg' => '收藏成功!'];
        }
        return response()->json($return_data);
    }

    public function loginDig(Request $request)
    {
        $html         = '';
        $redirect_url = $request->input('redirect_url', route('home'));
        if ($request->input('type') == 'per') {
            $html = view('jkq.common.ajax.per_login', ['redirect_url' => $redirect_url])->render();
        } elseif ($request->input('type') == 'com') {
            $html = view('jkq.common.ajax.com_login', ['redirect_url' => $redirect_url])->render();
        }
        $return_data = ['status' => 1, 'html' => $html];
        return response()->json($return_data);
    }

    //职位举报
    public function report(Request $request)
    {
        $jobs_id = $request->input('jobs_id');
        if (!$jobs_id) {
            throw new ResponseException('请选择要举报的职位!');
        }
        $report_types = $this->reportService->getReportTypes('1');
        $taskInfo     = $this->taskService->getTask('2', 'report_jobs'); //举报积分信息

        $page_data = ['type_arr' => $report_types, 'jobs_id' => $jobs_id, 'taskInfo' => $taskInfo];

        $html        = view('jkq.common.ajax.report_job', $page_data)->render();
        $return_data = ['status' => 1, 'html' => $html];
        return response()->json($return_data);
    }

    public function reportJobs(ReportValidatorRequest $request)
    {
        $report_type = $request->input('report_type');
        $jobs_id     = $request->input('jobs_id');
        $telephone   = trim($request->input('telephone'));
        $content     = trim($request->input('content'));
        if (!$content) {
            throw new ResponseException('请填写备注说明!');
        }
        if (!$telephone) {
            throw new ResponseException('请填写联系电话!');
        }

        //添加举报信息
        $report_data = [
            'utype'    => 1,
            'utype_id' => $jobs_id,
            'type_id'  => $report_type,
            'phone'    => $telephone,
            'content'  => $content,
            'audit'    => 1,
        ];
        $rst         = $this->reportService->addReport($report_data);
        if ($rst) {
            //添加会员日志
            $user_info = [
                'uid'         => auth('web-member')->user()->id,
                'utype'       => 2,
                'username'    => auth('web-member')->user()->username,
                'ip'          => ip2long($request->getClientIp()),
                'log_address' => '本机地址',
            ];
//            $this->feedbackService->addMembersLog($user_info, '2042', '投诉职位(职位id:'.$jobs_id.')');

            if (!$this->memberLogRepository->createLog(auth('web-member')->user(), 2042, $jobs_id)) {
                throw new \Exception("日志记失败!");
            }

            $return_data = ['status' => 1, 'msg' => '投诉成功!请等待管理员核实!'];
            return response()->json($return_data);
        } else {
            throw new ResponseException('举报失败!');
        }
    }

    //职位申请
    public function apply(Request $request)
    {
        //判断个人资料是否完善
        $jobs_id   = $request->input('jobs_id');
        $resume_id = $request->input('resume_id');
        if (!$jobs_id) {
            throw new ResponseException('请选择要投递的职位!');
        }
        if (!is_array($jobs_id)) {
            $jobs_id = explode(',', $jobs_id);
        }
        if ($resume_id) {
            //选择投递简历后
            $apply_rst = $this->personalJobsApplyService->applyJobs($jobs_id, $resume_id, $this->getUser());
            //完整度不够
            $return_data = [];
            if (array_get($apply_rst, 'status') == 0 && array_get($apply_rst, 'complete')) {
                $resume_complete = array_get($apply_rst, 'complete');
                $page_data       = ['info' => $resume_complete];
                $html            = view('jkq.common.ajax.apply_job_percent_tip', $page_data)->render();

                $return_data = [
                    'status'    => array_get($apply_rst, 'status'),
                    'html'      => $html,
                    'resume_id' => $resume_id,
                ];
                return response()->json($return_data);
            } else if (array_get($apply_rst, 'status') == 0) {
                return response()->json($return_data);
            }
            $tpl = 'jkq.common.ajax.batch_delivery_success';
            if ($apply_rst['data']['failure']) {
                $tpl = 'jkq.common.ajax.batch_delivery_fail';
            }
            //TODO 获取微信公众号名称

            $tpl_data    = [
                'jid'         => $jobs_id,
                'show_points' => $apply_rst['show_points'],
                'apply'       => $apply_rst['data'],
                'user_points' => $apply_rst['points_info'],
            ];
            $tpl_html    = view($tpl, $tpl_data)->render();
            $return_data = [
                'status'    => array_get($apply_rst, 'status'),
                'html'      => $tpl_html,
                'fail_jids' => $apply_rst['fail_job_ids'],
            ];
            return response()->json($return_data);
        } else {
            //未选择投递简历前
            $rst = $this->personalJobsApplyService->ifJobApply($jobs_id, $this->getUser());
            //判断是否需要选择简历
            if (array_get($rst, 'status') == 2) {
                $page_data   = ['status' => array_get($rst, 'status'), 'resumes' => array_get($rst, 'resumes'), 'def_resume' => array_get($rst, 'def_resume')];
                $html        = view('jkq.common.ajax.apply_resume', $page_data)->render();
                $return_data = ['status' => 2, 'html' => $html];
                return response()->json($return_data);
            } else {
                //判断
                $return_data = [];
                if (array_get($rst, 'status') == 0 && array_get($rst, 'complete')) {
                    $resume_complete = array_get($rst, 'complete');
                    $page_data       = ['info' => $resume_complete];
                    $html            = view('jkq.common.ajax.apply_job_percent_tip', $page_data)->render();

                    $return_data = [
                        'status'    => array_get($rst, 'status'),
                        'html'      => $html,
                        'resume_id' => array_get($rst, 'resume_id'),
                    ];
                    return response()->json($return_data);
                }
                $tpl = 'jkq.common.ajax.batch_delivery_success';
                if ($rst['data']['failure']) {
                    $tpl = 'jkq.common.ajax.batch_delivery_fail';
                }
                //获取微信公众号名称
                $tpl_data    = [
                    'jid'         => $jobs_id,
                    'show_points' => $rst['show_points'],
                    'apply'       => $rst['data'],
                    'user_points' => $rst['points_info'],
                ];
                $tpl_html    = view($tpl, $tpl_data)->render();
                $return_data = [
                    'status'    => array_get($rst, 'status'),
                    'html'      => $tpl_html,
                    'fail_jids' => $rst['fail_job_ids'],
                ];
                return response()->json($return_data);
            }
        }
    }

    public function jobMap(Request $request)
    {
        //设置职位默认显示方式
        if (!session('jobs_show_type')) {
            $type = config('aix.companyset.comset.show_set.jobs_list_show_type');
            session(['jobs_show_type' => $type]);
        }

        $params      = $request->all();
        $param_array = ['key', 'wage', 'trade', 'scale', 'nature', 'education', 'experience', 'settr', 'lng', 'lat', 'range', 'wa', 'm_zoom', 'search_type', 'sort', 'license', "apply", 'search_cont'];
        $params      = [];
        if ($request->all()) {
            foreach ($request->all() as $k => $v) {
                if (in_array($k, $param_array) && $v) {
                    $params[$k] = $v;
                }
            }
        }
        $position_search = false;
        if ($request->input('search_type') == 'position') {
            $position_search = true;
        }
        $filter_array = ['sort', 'search_cont', 'license', 'apply', 'search_type', 'key', 'wa', 'lng', 'lat', 'm_zoom'];
        $show_filter  = $this->showFilter($params, $filter_array);
        $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);

        $where      = $this->setWhere($params, [], []);   //组合where条件
        $order_by   = ['stime' => 'desc', 'refresh_time' => 'desc'];
        $search_key = '';
        if ($params) {
            if (array_has($params, 'sort')) {
                if ($params['sort'] == 'rtime') {
                    $order_by = ['refresh_time' => 'desc'];
                } else {
                    $order_by = [$params['sort'] => 'desc'];
                }
            }
            if (array_has($params, 'key')) {
                $search_key = $params['key'] ? $params['key'] : '';
            }
        }
        $map_data = [];
        if (array_has($params, 'lng') && array_has($params, 'lat') && array_has($params, 'wa')) {
            $map_data = ['lng' => $params['lng'], 'lat' => $params['lat'], 'map' => 1];
        }
        $list         = $this->searchService->search('Job', $where, $order_by, $search_key);
        $list_items   = [];
        $job_companys = [];
        if ($list->total() > 0) {
            $list_items   = $this->jobsService->dealjobFilelds($list->items(), $map_data);
            $job_companys = $this->jobsService->dealJobCompanies($list_items);
        }

        $emergency_jobs = $this->searchService->searchEmergencyJobs(4);     //紧急招聘
        $recommend_jobs = $this->searchService->searchRecommendJobs(5, $this->getUser());      //推荐职位
        $map_info       = $this->getMapInfo();
        $return_data    = [
            'params'          => $params,
            'categories'      => $categories,
            'show_filter'     => $show_filter,
            'list'            => $list,
            'list_items'      => $list_items,
            'job_companys'    => $job_companys,
            'emergency_jobs'  => $emergency_jobs,
            'position_search' => $position_search,
            'recommend_jobs'  => $recommend_jobs,
            'map_info'        => $map_info,
        ];

        return view('jkq.jobs.map', $return_data);
    }

    public function getMapInfo()
    {
        $m_zoom       = subsite_config('aix.system.map.map.max_level');
        $map_center_x = subsite_config('aix.system.map.map.map_x');
        $map_center_y = subsite_config('aix.system.map.map.map_y');
        return ['m_zoom' => $m_zoom, 'map_center_x' => $map_center_x, 'map_center_y' => $map_center_y];
    }

    public function showFilter($params, $filter_array)
    {
        $show_filter = false;
        if ($params && (count($params) <= count($filter_array))) {
            foreach ($params as $k => $v) {
                if (!in_array($k, $filter_array)) {
                    $show_filter = true;
                    break;
                }
            }
        } elseif (count($params) > count($filter_array)) {
            $show_filter = true;
        }
        return $show_filter;
    }
}