<?php
namespace App\Http\Controllers\Statistics;
use App\Http\Controllers\Statistics\StatisticsBaseController;
use Illuminate\Http\Request;
use App\Services\Statistics\CompanyService;
use App\Services\Statistics\ResumeService;
use App\Services\Statistics\JobfairService;
use App\Services\Statistics\JobsService;
use App\Services\Statistics\CategoryService;


class JobfairController extends StatisticsBaseController
{
    protected $resumeService;
    protected $jobfairService;
    protected $companyService;
    protected $jobsService;
    protected $categoryService;
    /**
     * DemandController constructor.
     */
    public function __construct(JobfairService $jobfairService, ResumeService $resumeService, CompanyService $companyService, JobsService $jobsService, CategoryService $categoryService)
    {
        $this->jobfairService  = $jobfairService;
        $this->resumeService   = $resumeService;
        $this->companyService  = $companyService;
        $this->jobsService     = $jobsService;
        $this->categoryService = $categoryService;
    }

    public function index(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateDetail($request->all());
        $start_time  = $date_aprams['start_date']?date('Y-m-d H:i:s', strtotime($date_aprams['start_date'])):$date_aprams['start_date'];
        $end_time    = date('Y-m-d H:i:s', strtotime($date_aprams['end_date'].' +1 day')-1);

        //举办结束时间在当前时间段中的所有招聘会
        if ($subsite_id != -1) {
            $jobfairs_where[] = ['subsite_id','=',$subsite_id];
        }
        $jobfairs_where[] = ['holddate_end','>=',strtotime($start_time)];
        $jobfairs_where[] = ['holddate_end','<=',strtotime($end_time)];
        $jobfair_ids = $this->jobfairService->getJobfairIds($jobfairs_where);

        //招聘企业数 - 举办结束时间在当前时间段中的所有招聘会的所有审核通过的企业数量
        //$jobfair_company_where = ['audit'=>1];
        $jobfair_company_where = [['audit','<>',3]];
        $company_nums = $this->jobfairService->getCompanyCount($jobfair_company_where, ['jobfair_id'=>$jobfair_ids]);

        //招聘岗位数 - 举办结束时间在当前时间段中的所有招聘会的所有审核通过的职位数量
        if (config('aix.companyset.comset.show_set.jobs_display')==1) {
            $job_where[] = array('audit','=',1);
        } else {
            $job_where[] = array('audit','<>',3);
        }
        $jobs_nums = $this->jobfairService->getJobsCount($job_where, ['jobfair_id'=>$jobfair_ids]);

        //招聘会需求总数
        $jobs_amounts = $this->jobfairService->getJobsAmount($job_where, ['jobfair_id'=>$jobfair_ids]);

        //统计招聘会进场个人用户信息(一个个人用户同一场招聘会进出多次统计成一次)
        //性别分布
        $sex_arr = $this->getPersonSexNums($jobfair_ids);

        //学历分布(统计有学历信息的数据)
        $edu_arr = $this->getPersonEducationNums($jobfair_ids);

        //年龄分布 - 后台读取年龄分类
        $wage_cates = $this->categoryService->getCategories(['AIX_age'=>100]);
        $age_names = [];
        if (array_has($wage_cates, 'AIX_age') && $wage_cates['AIX_age']) {
            foreach ($wage_cates['AIX_age'] as $k => $v) {
                $age_names[] = $v['demand'];
            }
        }

        $age_data  = [];
        foreach ($age_names as $k => $v) {
            $age_arr = explode('-', $v);
            $max_age = 0;
            $min_age = 0;
            if (count($age_arr) == 1 && stristr($v, '以下')) {
                $max_age = (int)$age_arr[0];
            } else {
                $min_age = (int)$age_arr[0];
            }
            if (array_has($age_arr, 1)) {
                $max_age = (int)$age_arr[1];
            }
            if ($min_age>0 && $max_age>0) {
                $age_num = $this->getPersonAgeNums([date('Y')-$max_age,date('Y')-$min_age], $jobfair_ids);
            } elseif ($min_age==0 && $max_age>0) {
                $age_num = $this->getPersonAgeNums([date('Y')-$max_age, 0], $jobfair_ids);
            } elseif ($min_age>0 && $max_age==0) {
                $age_num = $this->getPersonAgeNums([0, date('Y')-$min_age], $jobfair_ids);
            }
            $age_data[$v] = $age_num;
        }

        //详细数据-职位大类top10  需求人数+求职人数 按需求人数排序
        $topclass_data = $this->jobsService->getJobsTopclass($job_where, ['jobfair_id'=>$jobfair_ids], 'sum(amount) as num, topclass', ['topclass'], 'sum(amount) desc', 10);

        //获取求职登记人数
        $member_where = [
            ['utype','=',2],
            ['status','=',1],
            ['created_at','>=',$start_time],
            ['created_at','<=',$end_time]
        ];
        if ($subsite_id !='-1') {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $resume_where = [];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }
        $resume_fields = "count(id) as num,substring_index(intention_jobs_id,'.',1) as class";
        $resume_group = "class";
        $personal_nums = $this->resumeService->getResumeNumByClass($resume_where, $member_where, $resume_fields, $resume_group);
        if ($topclass_data) {
            $i =1;
            foreach ($topclass_data as $k => $v) {
                if (array_has($personal_nums, $k)) {
                    $topclass_data[$k]['resume_num'] = $personal_nums[$k];
                } else {
                    $topclass_data[$k]['resume_num'] = 0;
                }
                $topclass_data[$k]['order'] = $i;
                $i++;
            }
        }

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'jobfair_num'      => count($jobfair_ids),
            'company_nums'     => $company_nums,
            'jobs_nums'        => $jobs_nums,
            'jobs_amounts'     => $jobs_amounts,
            'sex_arr'          => $sex_arr,
            'edu_arr'          => $edu_arr,
            'age_data'         => $age_data,
            'topclass_data'    => $topclass_data
        ];

        return view('statistics.app.jobfair.index', $return_data);
    }

    public function getPersonEducationNums($jobfair_ids)
    {
        //获取uid>0的学历信息
        $where = [
            ['s.type','=',1],
            ['s.uid','>',0]
        ];
        $field = 's.uid,s.jobfairid,s.sex,s.idcard,m.education,m.education_cn';
        $edu_rst1 = $this->jobfairService->getSignPersonEducations('uid', $where, ['s.jobfairid'=>$jobfair_ids], ['s.jobfairid', 's.uid'], $field);
        $data1 = $edu_rst1->groupBy('education')->toArray();
        $education_data = [];
        if ($data1) {
            foreach ($data1 as $k => $v) {
                $education_data[$k] = count($v);
            }
        }

        //获取uid=0,idcard注册过简历的用户的学历分组信息
        $where2 = [
            ['s.type','=',1],
            ['s.uid','=',0]
        ];
        $field2 = 's.uid,s.jobfairid,s.sex,s.idcard,m.education,m.education_cn';
        $edu_rst2 = $this->jobfairService->getSignPersonEducations('idcard', $where2, ['s.jobfairid'=>$jobfair_ids], ['s.jobfairid', 's.idcard'], $field);
        $data2 = $edu_rst2->groupBy('education')->toArray();
        if ($data1) {
            foreach ($data2 as $k => $v) {
                $k = (int)$k;
                if (array_has($education_data, $k)) {
                    $education_data[$k] = count($v) + (int)$education_data[$k];
                } else {
                    $education_data[$k] = count($v);
                }
            }
        }

        //获取学历名称
        $cate_filter = ['AIX_education'=>100];
        $cates = $this->companyService->getCategories($cate_filter);
        $edu_arr = [];
        foreach ($cates['AIX_education'] as $k => $v) {
            $edu_arr[$v['id']] = ['name'=>$v['demand']];
            if ($education_data && array_has($education_data, $v['id'])) {
                $edu_arr[$v['id']]['value'] = $education_data[$v['id']];
            } else {
                $edu_arr[$v['id']]['value'] = 0;
            }
        }
        $edu_arr['0'] = ['name'=>'无学历信息', 'value'=>array_has($education_data, '0')?$education_data[0]:0];
        return $edu_arr;
    }

    public function getPersonSexNums($jobfair_ids)
    {
        $sex_rst1 = $this->jobfairService->getPersonNums([['uid','>',0],['type','=',1]], ['jobfairid'=>$jobfair_ids], ['jobfairid', 'uid']);
        $sex_group = $sex_rst1->groupBy('sex');
        $sex_data = [];
        if ($sex_group) {
            foreach ($sex_group as $k => $v) {
                $val = $v->toArray();
                $sex_data[$val[0]['sex']] = $v->count();
            }
        }
        //2.统计uid=0,idcard有值的次数
        $sex_rst2 = $this->jobfairService->getPersonNums([['uid','=',0],['type','=',1]], ['jobfairid'=>$jobfair_ids], ['jobfairid', 'idcard']);
        $sex_group2 = $sex_rst2->groupBy('sex');
        if ($sex_group2) {
            foreach ($sex_group2 as $k => $v) {
                $val = $v->toArray();
                if (array_has($sex_data, $val[0]['sex'])) {
                    $sex_data[$val[0]['sex']] = $v->count() + (int)$sex_data[$val[0]['sex']];
                } else {
                    $sex_data[$val[0]['sex']] = $v->count();
                }
            }
        }
        $sex_name = ['男', '女'];
        $sex_arr['男']  = array_has($sex_data, '1')?$sex_data['1']:0;
        $sex_arr['女']  = array_has($sex_data, '2')?$sex_data['2']:0;
        return $sex_arr;
    }

    public function getPersonAgeNums($age_arr, $jobfair_ids)
    {
        $min_age = $age_arr[0];
        $max_age = $age_arr[1];

        if ($max_age>0 && $min_age>0) {
            $age_where1[] = ['birthday', '>=', $min_age];
            $age_where1[] = ['birthday', '<=', $max_age];
        } elseif ($max_age==0) {
            $age_where1[] = ['birthday', '>=', $min_age];
        } elseif ($min_age ==0) {
            $age_where1[] = ['birthday', '<=', $max_age];
        }

        $age_where1[] = ['uid', '>', '0'];
        $age_where1[] = ['type','=',1];
        $age_rst1 = $this->jobfairService->getPersonNums($age_where1, ['jobfairid'=>$jobfair_ids], ['jobfairid', 'uid'])->count();

        if ($max_age>0 && $min_age>0) {
            $age_where2[] = ['birthday', '>=', $min_age];
            $age_where2[] = ['birthday', '<=', $max_age];
        } elseif ($max_age==0) {
            $age_where2[] = ['birthday', '>=', $min_age];
        } elseif ($min_age ==0) {
            $age_where2[] = ['birthday', '<=', $max_age];
        }
        $age_where2[] = ['uid', '=', '0'];
        $age_where2[] = ['type','=',1];
        $age_rst2 = $this->jobfairService->getPersonNums($age_where2, ['jobfairid'=>$jobfair_ids], ['jobfairid', 'idcard'])->count();
        $total_num = (int)$age_rst1 + (int)$age_rst2;
        return $total_num;
    }



}