<?php

namespace App\Http\Controllers\Web;

use App\Models\Ad;
use App\Models\Recruit;
use App\Models\Recuperate;
use App\Models\RecuperateCategory;
use App\Models\ShortUrl;
use App\Models\SubsiteAd;
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 App\Repositories\MemberInfoRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
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;
    protected $memberInfoRepository;

    /**
     * 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, MemberInfoRepository $memberInfoRepository)
    {
        $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;
        $this->memberInfoRepository        = $memberInfoRepository;
    }


    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //分站
        $subsite_id = get_subsite_id();
        if ($subsite_id > 0) {
            return $this->_subsite();
        }

        $filter_data = [
            'AIX_indexfocus'   => 8, //首页轮播广告
            'AIX_indextopimg'  => 8, //首页上方横幅
            '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 = [
            'titlelen' => 14,
            'dot'      => '...',
            'size'     => 9,
        ];
        $notices       = $this->noticeServer->getNotices($notice_filter);

        //获取工作动态、校园招聘、重要通知的数据
        $article_map = [
            'type_id'  => [13, 14, 15, 16, 17, 18, 19, 25, 26, 27, 28, 29, 57, 58, 59],
            '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[] = ['small_img', '<>', ''];
//        $ad_pic1         = Article::where($ad_pic_where1)->whereIn('type_id', [58, 59])->orderBy('list_order', 'asc')->orderBy('id', 'desc')->limit(1)->get();
//        $ad_pic1         = Article::whereNotNull('small_img')->orderBy('list_order', 'desc')->orderBy('id', 'desc')->limit(1)->get();

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

        //人才新闻
        $ad_pic3 = Article::whereIn('type_id', [58, 59])->where('is_display', 1)->orderBy('list_order', 'desc')->orderBy('id', 'desc')->limit(12)->get();

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

        //招考系统
        $recruit = Recruit::where([['status', '=', 1]])->where('id','<>',126)->orderBy('ordid','desc')->orderBy(DB::raw('field(current,1,2,3,4,5,6,7,8,9,0)'))->orderBy('updated_at','desc')->limit(4)->get();
        if (!$recruit->isEmpty()) {
            foreach ($recruit as $k => $v) {
                $recruit[$k] = Recruit::parse_index($v);
            }
        }

        $return_data = [
            '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 ($subsite_id > 0) {
            $tpl_name = $this->subsiteService->getSubsiteTpl($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 = [
            'alias' => $alias,
            'type'  => $type,
            'limit' => $limit,
        ];
        $links = $this->LinkService->getLinks($where);
        return $links;
    }

    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 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 = [
                'username' => $user->username,
                'userType' => 1,
                'timestr'  => time(),
                /*                'name'=>$user->companyname,
                                'idCard'=>$user->organization_code,
                                'type'=>1*/

            ];

            ksort($data);
            $sign_arr       = array_merge($data, ['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');

        }

    }

    /**
     * 短链接生成
     */
    public function short_url($url)
    {
        $short_url = ShortUrl::where('key', $url)->first();
        if (empty($short_url)) {
            return redirect(route('home'));
        } else {
            return redirect($short_url['url']);
        }
    }

    /**
     * 分站
     */
    private function _subsite()
    {
        //特殊网站
        $site_module = explode('.', request()->server('HTTP_HOST'))[0];
        if (method_exists($this, $site_module)) {
            return $this->$site_module();
        }

        $return_data = [];
        $subsite_id  = get_subsite_id();

        //公司
        $return_data['seatmeal_companies'] = $this->_dealCompany($subsite_id);

        //个人登录
        if (auth('web-member')->check()) {
            $return_data['memberInfo'] = $this->memberInfoRepository->getMemberInfo(auth('web-member')->id());
        }

        //首页轮播图
        $return_data['ad_list'] = [];
        $ad_ids                 = SubsiteAd::where('subsite_id', $subsite_id)->get(['ad_id'])->pluck('ad_id')->toArray();
        if (!empty($ad_ids)) {
            $return_data['ad_list'] = Ad::whereIn('id', $ad_ids)->get();
        }

        //文章列表
        $return_data['article_list'] = (new Article())->whereHas('subsites', function ($query) {
            $query->where('subsite_id', get_subsite_id());
        })->orderByRaw('list_order desc,created_at desc')->limit(10)->get();

        //办理人数
        $jkq_order                = collect(DB::table('configs')->where('type_id', '=', 73)->get(['alias', 'value']))->keyBy('alias');
        $return_data['jkq_order'] = $jkq_order;

        return view('subsite.index', $return_data);
    }

    /**
     * 首页公司信息
     */
    private function _dealCompany($subsite_id)
    {
        $seatmeal_companies = $this->companyService->getCompaniesByConditions(['subsite_id' => $subsite_id], 20);
        $res                = [];
        foreach ($seatmeal_companies as $v) {
            $jobs = [];
            if (!empty($v['jobs'])) {
                foreach ($v['jobs'] as $k => $job) {
                    if ($k == 4) {
                        break;
                    }
                    $jobs[] = [
                        'id'        => $job['id'],
                        'jobs_name' => $job['jobs_name'],
                        'amount'    => $job['amount'],
                    ];
                }
            }
            $res[] = [
                'id'          => $v['id'],
                'logo'        => $v['logo'],
                'companyname' => $v['companyname'],
                'jobs'        => $jobs,
            ];
        }

        return json_encode($res, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
    }

    /**
     * 经开区分站
     */
    private function jkq()
    {
        $return_data = [];
        $subsite_id  = get_subsite_id();

        //公司
        $return_data['seatmeal_companies'] = $this->_dealCompany($subsite_id);

        //个人登录
        if (auth('web-member')->check()) {
            $return_data['memberInfo'] = $this->memberInfoRepository->getMemberInfo(auth('web-member')->id());
        }

        //首页轮播图
        $return_data['ad_list'] = [];
        $ad_ids                 = SubsiteAd::where('subsite_id', $subsite_id)->get(['ad_id'])->pluck('ad_id')->toArray();
        if (!empty($ad_ids)) {
            $return_data['ad_list'] = Ad::whereIn('id', $ad_ids)->get();
        }

        //文章列表
        $return_data['article_list'] = (new Article())->whereHas('subsites', function ($query) {
            $query->where('subsite_id', get_subsite_id());
        })->orderByRaw('list_order desc,created_at desc')->limit(10)->get();

        //办理人数
        $jkq_order                = collect(DB::table('configs')->where('type_id', '=', 73)->get(['alias', 'value']))->keyBy('alias');
        $return_data['jkq_order'] = $jkq_order;

        return view('subsite.jkq.index', $return_data);
    }
}