<?php

namespace App\Http\Controllers\Web;

use App\Models\Recruit;
use App\Models\Recuperate;
use App\Models\RecuperateCategory;
use App\Services\Content\LinkService;
use App\Services\HomeService;
use App\Services\Company\JobsService;
use App\Services\Common\CategoryService;
use App\Services\Company\CompanyDownResumeService;
use App\Services\Common\SearchService;
use App\Services\Person\ResumeService;
use App\Services\Company\CompanyService;
use App\Services\Jobfair\JobfairService;
use App\Services\Content\NoticeServer;
use App\Services\Content\ArticleService;
use App\Services\SubsiteService;
use App\Repositories\PersonalJobsApplyRepository;
use App\Repositories\ViewJobRepository;
use App\Repositories\PmsRepository;
use App\Repositories\ResumeRepository;
use App\Repositories\CompanyInterviewRepository;
use App\Repositories\companyFavoriteRepository;
use App\Repositories\ViewResumeRepository;
use App\Repositories\TaskLogRepository;
use App\Services\Content\PolicyService;
use App\Models\Article;
use App\Repositories\PersonFocusComRepository;
use App\Repositories\MemberSetmealRepository;
use App\Repositories\JobsRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\View;

class HomeController extends WebBaseController
{
    protected $LinkService;
    protected $subsite_id;
    protected $homeService;
    protected $jobsService;
    protected $categoryService;
    protected $companyDownResumeService;
    protected $searchService;
    protected $resumeService;
    protected $companyService;
    protected $jobfairService;
    protected $noticeServer;
    protected $articleService;
    protected $subsiteService;
    protected $personalJobsApplyRepository;
    protected $viewJobRepository;
    protected $pmsRepository;
    protected $resumeRepository;
    protected $companyInterviewRepository;
    protected $companyFavoriteRepository;
    protected $viewResumeRepository;
    protected $taskLogRepository;
    protected $personFocusComRepository;
    protected $memberSetmealRepository;
    protected $jobsRepository;
    protected $policyService;

    /**
     * HomeController constructor.
     * @param $LinkService
     * @param $homeService
     * @param $jobsService
     * @param $categoryService
     * @param $companyDownResumeService
     * @param $searchService
     * @param $resumeService
     * @param $companyService
     * @param $jobfairService
     * @param $noticeServer
     * @param $articleService
     * @param $subsiteService
     */
    public function __construct(LinkService $LinkService, HomeService $homeService, JobsService $jobsService, CategoryService $categoryService, CompanyDownResumeService $companyDownResumeService, SearchService $searchService, ResumeService $resumeService, CompanyService $companyService, JobfairService $jobfairService, NoticeServer $noticeServer, ArticleService $articleService, SubsiteService $subsiteService, PersonalJobsApplyRepository $personalJobsApplyRepository, ViewJobRepository $viewJobRepository, PmsRepository $pmsRepository, ResumeRepository $resumeRepository, CompanyInterviewRepository $companyInterviewRepository, companyFavoriteRepository $companyFavoriteRepository, ViewResumeRepository $viewResumeRepository, TaskLogRepository $taskLogRepository, PersonFocusComRepository $personFocusComRepository, MemberSetmealRepository $memberSetmealRepository, JobsRepository $jobsRepository,PolicyService $policyService)
    {
        $this->LinkService = $LinkService;
        $this->homeService = $homeService;
        $this->jobsService = $jobsService;
        $this->categoryService = $categoryService;
        $this->companyDownResumeService = $companyDownResumeService;
        $this->searchService = $searchService;
        $this->resumeService = $resumeService;
        $this->companyService = $companyService;
        $this->jobfairService = $jobfairService;
        $this->noticeServer = $noticeServer;
        $this->articleService = $articleService;
        $this->subsiteService = $subsiteService;
        $this->personalJobsApplyRepository = $personalJobsApplyRepository;
        $this->viewJobRepository = $viewJobRepository;
        $this->pmsRepository = $pmsRepository;
        $this->resumeRepository = $resumeRepository;
        $this->companyInterviewRepository = $companyInterviewRepository;
        $this->companyFavoriteRepository = $companyFavoriteRepository;
        $this->viewResumeRepository = $viewResumeRepository;
        $this->taskLogRepository = $taskLogRepository;
        $this->personFocusComRepository = $personFocusComRepository;
        $this->memberSetmealRepository = $memberSetmealRepository;
        $this->jobsRepository = $jobsRepository;
        $this->policyService   = $policyService;
    }


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $filter_data = array(
            'AIX_indexfocus' => 6, //首页轮播广告
            'AIX_indextopimg' => 6, //首页上方横幅
            'AIX_index_center' => 8, //首页中部横幅

            'index_famous' => 8, //首页中部名企推荐广告 - 六栏格子广告
            'index_famous1' => 8, //首页中部横幅
            'index_famous2' => 8, //首页两栏广告
            'index_famous3' => 8, //首页三栏广告
            'index_famous4' => 8, //首页浮窗广告
            'index_famous5' => 8, //首页浮窗广告
            'index_famous6' => 8, //首页浮窗广告
            'index_famous7' => 8, //首页浮窗广告
        );
        $ads = $this->homeService->getAds($filter_data);

//        $seatmeal_companies = [];
//        $seatmeal_arr = array(
//            0 => '',
//            1 => '14',
//            2 => '11',
//            3 => '26,27,28',
//            4 => '13,35,153',
//            5 => '25',
//            6 => '3,4,6,9,10,16,17,20,21,25,28,30,31,34,36,37,40,41,44,45,151,165,213,314'
//        );
//        foreach ($seatmeal_arr as $key => $val) {
//            $seatmeal_companies[]= $this->companyService->getSetmailCompanies(array('trade'=>$val));
//        }


        $links_logo = $this->getLinks('AIX_index', '2', '18');
        $links_url = $this->getLinks('AIX_index', '1', '50');
        if ($user = auth('web-member')->user()) {
            $userInfo = $this->homeService->getUserInfo($user);
        } elseif ($user = auth('web-company')->user()) {
            $userInfo = $this->homeService->getUserInfo($user);
        } else {
            $userInfo = [];
        }
        $time = $this->homeService->getTime();
        //公告公示
        $notice_filter = array(
            'titlelen' => 14,
            'dot' => '...',
            'size' => 9
        );
        $notices = $this->noticeServer->getNotices($notice_filter);

        //获取工作动态、校园招聘、重要通知的数据
        $article_map = array(
            'type_id' => array(48,2, 3, 30, 31, 13, 14, 15, 16, 17, 18, 19, 25, 26, 27, 28, 29),
            'limit' => 12,
            'titlelen' => 25,
            'dot' => '...'
        );
        $articles = $this->articleService->getArticleCache($article_map, 'home');

        $articles_img = $this->articleService->getArticlesByType(3, 5);


        //企业登录后需要展示的数据
        //当前时间
        $hour = date('G');
        if ($hour < 11) {
            $am_pm = '早上好';
        } else if ($hour < 13) {
            $am_pm = '中午好';
        } else if ($hour < 17) {
            $am_pm = '下午好';
        } else {
            $am_pm = '晚上好';
        }


        //是否签到
        $isSign = 0;
        //套餐职位数量
        $jobs_meanwhile = 0;
        //已经发布的职位数量
        $jobsCount = 0;
        //待处理简历数
        $resumesCount = 0;
        //谁关注我数量
        $concern = 0;
        //我的消息数量
        $pms = 0;

        //个人登录后需要显示的数据
        $resumeid = 0;
        //面试邀请数量
        $interview = 0;
        //谁关注我数量
        $viewResume = 0;
        //我的消息数量
        $mypms = 0;


        if ($this->getUser()) {
            //企业
            if ($this->getUser()->utype == 1) {
                //是否已签到
                $isSign = $this->taskLogRepository->getTaskLogCount($user->id, 18, $user->utype);
                //待处理简历
                $condition1 = [
                    'is_reply' => 0,
                    'company_id' => $this->getUser()->id,
                ];
                $resumesCount = $this->personalJobsApplyRepository->resumesCount($condition1);
                //谁看过我

                $map['company_id'] = auth('web-company')->user()->id;
                $concern = $this->personFocusComRepository->getFansCount($map);

                //我的消息
                $where['msgtouid'] = $this->getUser()->id;
                $where['utype'] = $this->getUser()->utype;
                $where['new'] = 1;

                $pms = $this->pmsRepository->getPmsCount($where);

                $company_setmeal = $this->memberSetmealRepository->getSetmealByUid($user->id, $user->utype);//会员套餐
                $jobs_meanwhile = $company_setmeal->jobs_meanwhile;
                $jobsCountwhere[] = ['company_id', '=', $user->id];
                $jobsCount = $this->jobsRepository->getJobCount($jobsCountwhere);
            } else {
                //是否已签到
                $isSign = $this->taskLogRepository->getTaskLogCount($user->id, 3, $user->utype);
                $resume = $this->resumeRepository->getPersonInfo($this->getUser()->id);
                if ($resume) {
                    $interview = $this->companyInterviewRepository->getInterview($this->getUser()->id, getJobsStatus());
                    $viewResume = $this->companyFavoriteRepository->getAttentionByResume($resume->id);
                    $resumeid = $resume->id;
                } else {
                    $interview = 0;
                    $viewResume = 0;
                }
                $mypms = $this->pmsRepository->getPmsCount(['msgtype' => 1, 'new' => 1, 'utype' => 2, 'msgtouid' => $this->getUser()->id]);
            }
        }

        //人才新闻
        $ad_pic_where1[] = array('type_id', '=',3);
        $ad_pic_where1[] = array('small_img', '<>','');
        $ad_pic1 = Article::where($ad_pic_where1)->orderBy('list_order', 'asc')->orderBy('id', 'desc')->limit(1)->get();

        //人才疗休养活动
        $ad_pic_where2[] =array('r_c_id', '!=',0);
        $ad_pic_where2[] =array('deleted_at', '=',null);
        $ad_pic_where2[] = array('small_img', '<>','');
        $ad_pic2 = Recuperate::where($ad_pic_where2)->orderBy('list_order', 'asc')->orderBy('id', 'desc')->limit(4)->get();
        //人才疗休养分类
        $Recuperatecategory_arr=RecuperateCategory::where('deleted_at',null)->select('id','name')->get()->toArray();

        //人才新闻
        $ad_pic_where3[] = array('type_id', '=',51);
        $ad_pic_where3[] = array('small_img', '<>','');
        $ad_pic3 = Article::where($ad_pic_where3)->orderBy('list_order', 'asc')->orderBy('id', 'desc')->limit(4)->get();

        $rcinfos=$this->policyService->getRcInfosByIndex();

        //招考系统
        $recruit = Recruit::where([['status','=',1]])->orderBy('ordid','desc')->orderBy('updated_at','desc')->limit(4)->get();
        if (!$recruit->isEmpty()) {
            foreach ($recruit as $k => $v) {
                $recruit[$k] = Recruit::parse_index($v);
            }
        }

        $return_data = array(
            'links_logo' => $links_logo,
            'links_url' => $links_url,
            'ads' => $ads,
            'userInfo' => $userInfo,
            'time' => $time,
            'notices' => $notices,
            'articles' => $articles,
            //'seatmeal_companies' => $seatmeal_companies,
            'am_pm' => $am_pm,
            'isSign' => $isSign,
            'jobs_meanwhile' => $jobs_meanwhile,
            'jobsCount' => $jobsCount,
            'resumesCount' => $resumesCount,
            'concern' => $concern,
            'pms' => $pms,
            'resumeid' => $resumeid,
            'interview' => $interview,
            'viewResume' => $viewResume,
            'mypms' => $mypms,
            'articles_img' => $articles_img,
            'ad_pic1' => $ad_pic1,
            'ad_pic2' => $ad_pic2,
            'ad_pic3' => $ad_pic3,
            'rcinfos' => $rcinfos,
            'recuperate_category_arr' => $Recuperatecategory_arr,
            'recruit' => $recruit,
        );
        //获取分站模板信息
        if (get_subsite_id() > 0) {
            $tpl_name = $this->subsiteService->getSubsiteTpl(get_subsite_id());
            //判断模板是否存在
            if (View::exists('home.' . $tpl_name . '.index')) {
                return view('company.' . $tpl_name . '.index', $return_data);
            } else {
                return view('app.index', $return_data);
            }
        } else {
            return view('app.index', $return_data);
        }
    }

    public function getNewestCompanies($params)
    {
        $lists = Cache::get('newest_jobs_company_list_' . get_subsite_id());
        if ($lists === null) {
            $lists = $this->searchService->searchSeatmealCompanies($params);
            Cache::put('newest_jobs_company_list_' . get_subsite_id(), $lists, 5);
        }
        return $lists;
    }

    public function getLinks($alias, $type = '', $limit = 18)
    {
        $where = array(
            'alias' => $alias,
            'type' => $type,
            'limit' => $limit
        );
        $links = $this->LinkService->getLinks($where);
        return $links;
    }

    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 developing()
    {
        return view('app.developing');
    }

    /*优秀人才申请*/
    public function  declare(Request $request){

        if($this->getUser()){
            if(!$user=auth('web-company')->user()){
                return $this->showMessage('个人未开放申请优秀人才申报系统功能!', route('home'), true,'','1');
            }
            $url='http://rc.jucai.gov.cn/api/jucaiInterface/login';
            $data=array(
                'username'=>$user->username,
                'userType'=>1,
                'timestr'=>time(),
/*                'name'=>$user->companyname,
                'idCard'=>$user->organization_code,
                'type'=>1*/

            );

            ksort($data);
            $sign_arr=array_merge($data,array( 'key'=>'rsKVyec52fqEKpk4RRD2TU8fKvPxt6ombKg0qSq1velPQtBHVi'));
            $sign=strtoupper(md5(http_build_query($sign_arr)));
            $data['sign']=$sign;
            $data['name']=htmlspecialchars($user->companyname);
            $data['idCard']=$user->organization_code;
            $data['type']=1;
            return redirect()->away('http://rc.jucai.gov.cn/api/jucaiInterface/login?timestr='.time().'&userType=1&username='.$user->username.'&sign='.$sign.'&name='.$user->companyname.'&idCard='.$user->organization_code.'&type=1&id='.$user->id);
        }else{
            return redirect()->away('http://rc.jucai.gov.cn/login');

        }

    }
}