<?php

namespace App\Http\Controllers\Web;

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\Models\ArticleCategory;
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;

    /**
     * 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)
    {
        $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;
    }


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

            'index_famous' => 8, //首页中部名企推荐广告 - 六栏格子广告
            'index_famous1' => 8, //首页中部横幅
            'index_famous2' => 8, //首页两栏广告
            'index_famous3' => 8, //首页三栏广告
            'index_famous4' => 8, //首页浮窗广告
            'index_famous5' => 8, //首页浮窗广告
            'index_famous6' => 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));
        }

        //处理首页六栏格子推荐企业广告
//        if (array_has($ads, 'index_famous4')) {
//            $com_ids = [];
//            foreach ($ads['index_famous4'] as $k => $v) {
//                $com_ids[] = $v->uid;
//            }
//            //获取关联企业的职位信息
//            $seatmeal_filter = array(
//                'jobs_num' => 2,
//                'companynamelen' => 8,
//                'dot' => '...',
//                'size' => 24,
//                'id' => $com_ids
//            );
//            $ad_companies = $this->searchService->searchSeatmealCompanies($seatmeal_filter, 'ad');
//        } else {
//            $ad_companies = [];
//        }

        $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(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);

        $categories_jobs_arr = [];
        $trade_arr = array(
            0 => array('纺织', '服装'),
            1 => array('制鞋'),
            2 => array('陶瓷', '建材'),
            3 => array('食品', '饮料'),
            4 => array('纸制品', '包装', '印刷'),
            5 => array('高端装备', '装备', '机械'),
            6 => array('新材料', '材料'),
            7 => array('光', '电', '信息'),
            8 => array('海洋', '生物'),
            9 => array('高端', '包装', '印刷'),
            10 => array('科创', '设计'),
            11 => array('商贸', '物流'),
            12 => array('互联网', '信息'),
            13 => array('文化', '旅游'),
            14 => array('体育', '健康'),
            15 => array('金融', '理财', '保险', '会计'),
            16 => array('集成', '电路'),
            17 => array('其他', '行业')
        );
        foreach ($trade_arr as $key => $val) {
            $categories_jobs_arr[] = $this->categoryService->getCategoryByTrade($val);
        }

        //企业登录后需要展示的数据
        //当前时间
        $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]);
            }
        }

        $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,
            'categories_jobs_arr' => $categories_jobs_arr,
        );
        //获取分站模板信息
        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');
        }else{
            return redirect()->away('http://rc.jucai.gov.cn/login');

        }

    }
}