<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/28
 * Time: 14:30
 */

namespace App\Http\Controllers\Web\Hardware\Aio;

use App\Http\Controllers\Web\WebBaseController;
use App\Repositories\Jobfair\JobfairCompanyRepository;
use App\Repositories\Jobfair\JobfairPersonalJobsApplyRepository;
use App\Repositories\Jobfair\JobfairPutJobRepository;
use App\Repositories\Jobfair\JobfairRepository;
use App\Repositories\ResumeRepository;
use App\Services\Common\CategoryService;
use App\Services\Jobfair\JobfairPersonalJopApplyService;
use App\Services\Jobfair\JobfairService;
use App\Services\Person\ResumeService;
use Illuminate\Http\Request;
use App\Services\Company\CompanyDownResumeService;
use App\Services\Jobfair\JobfairPutJobService;
use App\Services\Jobfair\JobfairCompanyService;
use Illuminate\Support\Facades\DB;
class JobfairController extends WebBaseController
{

    protected $jobfairRepository;
    protected $jobfairCompanyRepository;
    protected $jobfairPutJobRepository;
    protected $categoryService;
    protected $jobfairService;
    protected $jobfairPersonalJopApplyService;
    protected $jobfairPersonalJobsApplyRepository;
    protected $resumeRepository;
    protected $companyDownResumeService;
    protected $resumeService;
    protected $jobfairPutJobService;
    protected $jobfairCompanyService;

    /**
     * JobfairController constructor.
     * @param  $jobfairRepository
     * @param  $jobfairCompanyRepository
     * @param  $jobfairService
     * @param  $jobfairPersonalJobsApplyRepository
     * @param  $resumeRepository
     * @param $companyDownResumeService
     * @param $jobfairPutJobService
     * @param $jobfairCompanyService
     */
    public function __construct(JobfairRepository $jobfairRepository, ResumeRepository $resumeRepository, JobfairPersonalJobsApplyRepository $jobfairPersonalJobsApplyRepository, JobfairPersonalJopApplyService $jobfairPersonalJopApplyService, JobfairService $jobfairService, CategoryService $categoryService, JobfairPutJobRepository $jobfairPutJobRepository, JobfairCompanyRepository $jobfairCompanyRepository, CompanyDownResumeService $companyDownResumeService,ResumeService $resumeService,JobfairPutJobService $jobfairPutJobService,JobfairCompanyService $jobfairCompanyService)
    {
        $this->jobfairRepository = $jobfairRepository;
        $this->jobfairCompanyRepository = $jobfairCompanyRepository;
        $this->jobfairPutJobRepository = $jobfairPutJobRepository;
        $this->categoryService = $categoryService;
        $this->jobfairPersonalJopApplyService = $jobfairPersonalJopApplyService;
        $this->jobfairService = $jobfairService;
        $this->jobfairPersonalJobsApplyRepository = $jobfairPersonalJobsApplyRepository;
        $this->resumeRepository = $resumeRepository;
        $this->companyDownResumeService = $companyDownResumeService;
        $this->resumeService = $resumeService;
        $this->jobfairPutJobService = $jobfairPutJobService;
        $this->jobfairCompanyService = $jobfairCompanyService;
    }


    /**招聘会列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        $page = 4;
        $allJobfair = $this->jobfairRepository->AioAllJobfair($page);
        $res = [
            'allJobfair'=>$allJobfair,
            'week'=>['星期日','星期一','星期二','星期三','星期四','星期五','星期六']
        ];
        return view('app.hardware.aio.jobfair.index', $res);
    }

    public function jobfairDetail($id)
    {
        if (!$id) {
            return $this->showMessage('参数错误', route('hardware.aio.jobfair.index'));
        }
        if (!$jobfair = $this->jobfairRepository->find($id)) {
            return $this->showMessage('无此招聘会', route('hardware.aio.jobfair.index'));
        }

        // 1预定中 0结束预定
        $time = time();
        if ($jobfair->predetermined_start and $jobfair->predetermined_start < $time && $jobfair->predetermined_status == 1 and $jobfair->predetermined_end >$time) {
            $jobfair->predetermined_ok = 1;
        } elseif ($jobfair->predetermined_start and $jobfair->predetermined_start > $time && $jobfair->predetermined_status == 1) {
            $jobfair->predetermined_ok = 2;
        } else {
            $jobfair->predetermined_ok = 0;
        }

        $res = [
            'jobfair'=>$jobfair,
        ];
        return view('app.hardware.aio.jobfair.jobfair_detail', $res);
    }

    /**参会企业
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function jobfairCom($id)
    {
        if (!$id) {
            return $this->showMessage('参数错误', route('hardware.aio.jobfair.index'));
        }
        if (!$this->jobfairRepository->find($id)) {
            return $this->showMessage('无此招聘会', route('hardware.aio.jobfair.index'));
        }
        $where['jobfair_id']=$id;
        $where['audit']=1;
        $page = 4;
        $jobfairComList = $this->jobfairCompanyRepository->aioFindCompany($where, $page);
        $res = [
            'jobfairComList'=>$jobfairComList,
        ];
        return view('app.hardware.aio.jobfair.jobfair_com', $res);
    }

    /**招聘会企业详情
     * @param $uid
     * @param $jobfair_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function jobfairComDetail($uid, $jobfair_id)
    {
        if (!$uid || !$jobfair_id) {
            return $this->showMessage('参数错误', route('hardware.aio.jobfair.com'));
        }
        $put_jobs_where = [
            'jobfair_id'=>$jobfair_id,
            'company_id'=>$uid
        ];
        $jobs_where = [
            'display'=>1,
            'audit'=>1
        ];
        $jobfair_com = $this->jobfairCompanyRepository->findOneCom($put_jobs_where);
        $jobs = $this->jobfairPutJobRepository->getWhere($jobs_where,$put_jobs_where);
        $res = [
            'jobfair_com'=>$jobfair_com,
            'jobs'=>$jobs,
        ];
        return view('app.hardware.aio.jobfair.jobfair_com_detail', $res);
    }


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

    public function jobfairJob(Request $request)
    {

        $params = array();
        $param_array = array('citycategory','wage','trade','education','key');
        if ($request->all()) {
            foreach ($request->all() as $k => $v) {
                if (in_array($k, $param_array) && $v) {
                    $params[$k] = $v;
                }
            }
        }
        //所在地区(默认地区)
        $citys = $this->categoryService->getCitys();

        $orwhere=[];
        $where = $this->setWhere($params);
        if (array_key_exists('orwhere', $where)) {
            $orwhere = $where['orwhere'];
            unset($where['orwhere']);
        }
        $limit = 10;
        $list = $this->jobfairPutJobRepository->aioJobfairJob($where, $orwhere, $limit);
        $res = [
            'params'=>$params,
            'list'=>$list,
            'arealist'   => $citys,
            'user' => $this->getUser(),
        ];
        return view('app.hardware.aio.jobfair.job.jobfair_job', $res);
    }

    /**招聘会职位详情
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */

    public function jobfairJobDetail($id)
    {
        if (!$id) {
            return $this->showMessage('参数错误', route('hardware.aio.jobfair.com'));
        }

        $jobfairJobInfo = $this->jobfairPutJobRepository->getOne(['id'=>$id]);

        $res = [
            'info'=>$jobfairJobInfo,
            'user'=>$this->getUser(),
        ];
        return view('app.hardware.aio.jobfair.job.job_detail', $res);
    }

    /**个人预约招聘会职位
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\ResponseException
     * @throws \Throwable
     */

    public function jobfairJobApply(Request $request)
    {
        $user = $this->getUser();

        $jid = $request->jobsfair_job_id;
        $jobfair_id = $request->jobfair_id;
        $position_id = $request->position_id;
        $company_id = $request->company_id;
        $resume_id = $request->resume_id?$request->resume_id:0;

        $jobfair = $this->jobfairRepository->find($jobfair_id);
        if ($jobfair->isEmpty ||  $jobfair->holddate_end < time()) {
            return response()->json(['status'=>0, 'html'=>"招聘会已停止"]);
        }

        if ($resume_id) {
            $data['resume_id'] = $resume_id;
            $this->resumeService->isOwn($resume_id,$user);
            $this->jobfairPutJobService->isOwn($jid,$company_id);
            //错综复杂的关系
            $this->jobfairCompanyService->isPositionOwn($position_id,$jobfair_id,$company_id,$jid);
            $data['personal_uid'] = $user->id;
            $data['jobs_id'] = $jid;
            $data['company_id'] = $company_id;
            $data['jobfair_id'] = $jobfair_id;
            $data['position_id'] = $position_id;
            //简历完整度
            $res_complete = $this->resumeRepository->find($resume_id, ['complete_percent']);
            if ($res_complete['$res_complete'] < config('aix.personal_set.per_set.per_set.apply_job_min_percent')) {
                return response()->json(['status'=>0,'html'=>'请完善简历后再预约职位']);
            }
            if ($this->jobfairPersonalJobsApplyRepository->findWhere(['resume_id'=>$resume_id, 'jobs_id'=>$jid, 'company_id'=>$company_id, 'jobfair_id'=>$jobfair_id, 'position_id'=>$position_id])->isNotEmpty()) {
                return response()->json(['status'=>0, 'html'=>"您已预约该职位,请勿重复预约!"]);
            }
            DB::beginTransaction();
            try {
                $this->jobfairPersonalJopApplyService->applyJob($data);
                $this->companyDownResumeService->addDownResumes($company_id,$resume_id);
                DB::commit();
                return response()->json(['status'=>1, 'html'=>"职位预约成功!"]);
            } catch (\Exception $e) {
                DB::rollback();
                return response()->json(['status'=>0,'type'=>0 , 'html'=>"职位预约失败!"]);
            }
        } else {
            $result = $this->jobfairPersonalJopApplyService->ifJobApply($user);
            if ($result['status'] == 2) {  //返回结果,让用户选择简历投递
                $page_data = array('status'=>array_get($result, 'status'),'resumes'=>array_get($result, 'resumes'),'def_resume'=>array_get($result, 'def_resume'),'jobs_id'=>$jid);
                $page_data['company_id'] = $company_id;
                $page_data['jobfair_id'] = $jobfair_id;
                $page_data['position_id'] = $position_id;
                $page_data['jobs_id'] = $jid;
                $html = view('app.hardware.aio.jobfair.job.ajax_apply', $page_data)->render();
                return response()->json(['status'=>2,'html'=>$html]);
            } elseif ($result['status'] == 3) { //直接投递
                $this->jobfairPutJobService->isOwn($jid,$company_id);
                //错综复杂的关系
                $this->jobfairCompanyService->isPositionOwn($position_id,$jobfair_id,$company_id,$jid);
                $resume = $result['resumes'][0];
                $data['resume_id'] = $resume->id;
                $data['personal_uid'] = $user->id;
                $data['jobs_id'] = $jid;
                $data['company_id'] = $company_id;
                $data['jobfair_id'] = $jobfair_id;
                $data['position_id'] = $position_id;
                $res_complete = $this->resumeRepository->find($resume->id, ['complete_percent']);
                if ($res_complete['complete_percent'] < config('aix.personal_set.per_set.per_set.apply_job_min_percent')) {
                    return response()->json(['status'=>0,'html'=>'请完善简历后再预约职位']);
                }
                if ($this->jobfairPersonalJobsApplyRepository->findWhere(['resume_id'=>$resume->id, 'jobs_id'=>$jid, 'company_id'=>$company_id, 'jobfair_id'=>$jobfair_id, 'position_id'=>$position_id])->isNotEmpty()) {
                    return response()->json(['status'=>0, 'html'=>"您已预约该职位,请勿重复预约!"]);
                }
                DB::beginTransaction();
                try {
                    $this->jobfairPersonalJopApplyService->applyJob($data);
                    $this->companyDownResumeService->addDownResumes($company_id,$resume->id);
                    DB::commit();
                    return response()->json(['status'=>1, 'html'=>"职位预约成功!"]);
                } catch (\Exception $e) {
                    DB::rollback();
                    return response()->json(['status'=>0,'type'=>0 , 'html'=>"职位预约失败!"]);
                }
            }
        }
    }

    protected function setWhere($params)
    {
        $where = [
            ['audit','=',1],
            ['display','=',1]
        ];
        if ($params) {
            foreach ($params as $k => $v) {
                if ($k == 'citycategory') {
                    //地标地段
                    $district = getDistrict($v);
                    $where[] = array('district','like',"%$district%");
                } elseif ($k =='key') {
                    $where['orwhere'] = [['jobs_name', 'like', "%$v%"],['company_name', 'like', "%$v%"]];
                } else {
                    $where[] = [$k,'=', $v];
                }
            }
        }
        return $where;
    }



}