<?php
namespace App\Http\Controllers\Statistics;
use App\Admin\Exports\Caiqing\TechLevelExport;
use App\Http\Controllers\Statistics\StatisticsBaseController;
use Illuminate\Http\Request;
use App\Services\Statistics\CompanyService;
use App\Services\Statistics\JobsService;
use App\Services\Statistics\ResumeService;
use App\Services\Statistics\MemberService;
use App\Services\Statistics\CategoryService;
use App\Services\Common\SearchService;
use Illuminate\Support\Collection;
use App\Admin\Exports\Caiqing\OverallExport;
use App\Admin\Exports\Caiqing\JobGapExport;
use App\Admin\Exports\Caiqing\ResumeGapExport;
use App\Admin\Exports\Caiqing\IndustryExport;
use App\Admin\Exports\Caiqing\TradeExport;
use App\Admin\Exports\Caiqing\CompanyTypeExport;
use App\Admin\Exports\Caiqing\TypeExport;
use App\Admin\Exports\Caiqing\EducationExport;
use App\Admin\Exports\Caiqing\PersonTypeExport;
use App\Admin\Exports\Caiqing\AgeExport;



class DemandController extends StatisticsBaseController
{
    protected $jobsService;
    protected $resumeService;
    protected $memberService;
    protected $companyService;
    protected $apply_state;
    protected $searchService;
    protected $categoryService;
    /**
     * DemandController constructor.
     */
    public function __construct(JobsService $jobsService, ResumeService $resumeService, MemberService $memberService, CompanyService $companyService, SearchService $searchService, CategoryService $categoryService)
    {
        $this->jobsService = $jobsService;
        $this->resumeService = $resumeService;
        $this->memberService = $memberService;
        $this->companyService = $companyService;
        $this->searchService  = $searchService;
        $this->categoryService = $categoryService;
        $this->apply_state = ['1' => '合适', '2' => '不合适', '3' => '待定', '4' => '未接通'];
    }

    public function index(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //近1年的起始时间
        $end_date = date('Y-m', time());
        $end_time = date("Y-m-d H:i:s", strtotime("$end_date +1 month")-1);
        $start_time = date("Y-m-d H:i:s", strtotime("$end_date -11 month"));

        //需求人数(职位人数总和)
        $job_where = [
            ['created_at','<=',$end_time],
            ['created_at','>=',$start_time],
            ['valid','=',1],
            ['display','=',1]
        ];
        if (config('aix.companyset.comset.show_set.jobs_display')==1) {
            $job_where[] = array('audit','=',1);
        } else {
            $job_where[] = array('audit','<>',3);
        }
        $company_where = ['utype'=>1,'user_status'=>1];
        if ($subsite_id != -1) {
            $company_where[] = ['subsite_id','=',$subsite_id];
        }
        $job_group = "create_month";
        $job_fields = 'count(id),sum(amount) as num,date_format(created_at, "%y-%m") as create_month';
        $job_order  = 'create_month asc';
        $jobs_rst = $this->jobsService->getJobNumsByGroup($job_where, $company_where, $job_fields, $job_group, $job_order);
        $jobs_res = [];
        if ($jobs_rst) {
            foreach ($jobs_rst as $k => $v) {
                $jobs_res[$v['create_month']] = $v['num']?$v['num']:0;
            }
        }

        //求职人数(简历数量)
        $resume_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
        ];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }
        $member_where = array(
            ['utype','=',2],
            ['status','=',1]
        );
        if ($subsite_id != -1) {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $resume_group = "create_month";
        $resume_fields = 'count(id) as num,date_format(created_at, "%y-%m") as create_month';
        $resume_order  = 'create_month asc';
        $resume_rst = $this->resumeService->getResumeNumsByGroup($resume_where, $member_where, $resume_fields, $resume_group, $resume_order);

        //求人倍率(需求人数/求职人数)
        $start_date = date("Y-m", strtotime($start_time));
        $date_arr = [];
        $multiple = [];
        $job_num  = [];
        $resume_num = [];
        for ($i=0; $i<12; $i++) {
            $start = date("y.n", strtotime($start_date));
            $s_date = date("y-m", strtotime($start_date));
            $date_arr[] = $start;
            if (!array_has($jobs_res, $s_date)) {
                $job_num[$start] = 0;
            } else {
                $job_num[$start] = $jobs_res[$s_date];
            }
            if (!array_has($resume_rst, $s_date)) {
                $resume_num[$start] = 0;
            } else {
                $resume_num[$start] = $resume_rst[$s_date];
            }
            $jnum = $job_num[$start];
            $rnum = $resume_num[$start];
            if ($jnum==0 || $rnum==0) {
                $multiple[$start] = 0;
            } else {
                $multiple[$start] = sprintf("%.2f", (int)$jnum/(int)$rnum);
            }
            $start_date = date("Y-m", strtotime("$start_date +1 month"));
        }

        $return_data = [
            'jobs_data'   => $job_num,
            'resume_data' => $resume_num,
            'multiple'    => $multiple,
            'date_arr'    => $date_arr,
            'job_total'   => array_sum($job_num),
            'resume_total'=> array_sum($resume_num),
        ];
        if ($request->input('isExcel')==1) {
            $data = [];
            if ($date_arr) {
                foreach ($date_arr as $k => $v) {
                    $job_amount = array_has($job_num, $v)?$job_num[$v]:'0';
                    $resume_amount = array_has($resume_num, $v)?$resume_num[$v]:'0';
                    $multiple = '0';
                    if ($job_amount==0 || $resume_amount==0) {
                        $multiple = '0';
                    } else {
                        $multiple = sprintf("%.2f", (int)$job_amount/(int)$resume_amount);
                    }
                    $data[] = ['date_time'=>$v,'job_num'=>$job_amount.'','resume_num'=>$resume_amount.'','multiple'=>$multiple];
                }
                //合计
                $all_multiple = 0;
                if ($resume_num > 0) {
                    $all_multiple = sprintf("%.2f", (int)array_sum($job_num)/(int)array_sum($resume_num));
                }
                $data[] = ['date_time'=>'合计','job_num'=>array_sum($job_num).'','resume_num'=>array_sum($resume_num).'','multiple'=>$all_multiple];
            }

            //导出文件
            $export = new OverallExport('总体分析 - 近一年的供求情况');
            $c = new Collection($data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.basic_analysis', $return_data);
        }
    }

    public function compareEducation(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        //获取文化程度数据 + 无要求
        $cates = $this->companyService->getCategories(['AIX_education'=>100]);
        $edu_cates = [];
        if (array_has($cates, 'AIX_education')) {
            $edu_cates = $cates['AIX_education'];
            $edu_cates['0'] = ['id'=>0, 'demand'=>'无要求'];
        }

        //获取需求信息
        $job_where = array(
            array('valid','=','1'),
            array('display','=',1),
            array('created_at','>=',$start_time),
            array('created_at','<=',$end_time)
        );
        if (config('aix.companyset.comset.show_set.jobs_display')==1) {
            $job_where[] = array('audit','=',1);
        } else {
            $job_where[] = array('audit','<>',3);
        }
        $company_where = ['utype'=>1,'user_status'=>1];
        if ($subsite_id != -1) {
            $job_where[] = ['subsite_id','=',$subsite_id];
            $company_where[] = ['subsite_id','=',$subsite_id];
        }
        $edu_fields = 'sum(amount) as num, education';
        $edu_group = 'education';
        $edu_order  = 'education asc';
        $edu_rst = $this->jobsService->getJobNumsByGroup($job_where, $company_where, $edu_fields, $edu_group, $edu_order);
        $job_data = [];
        if ($edu_rst) {
            foreach ($edu_rst as $k => $v) {
                $job_data[$v['education']] = $v['num'];
            }
        }

        //获取求职人数
        $member_where = [
            ['m.utype','=',2],
            ['m.status','=',1],
            ['r.created_at','>=',$start_time],
            ['r.created_at','<=',$end_time]
        ];
        if ($subsite_id !='-1') {
            $member_where[] = ['m.subsite_id','=',$subsite_id];
        }
        $edu_fields = 'count(r.id) as num, mi.education,mi.education_cn';
        $edu_group = 'mi.education';
        $where_str = 'm.deleted_at IS NULL AND mi.deleted_at IS NULL AND r.deleted_at IS NULL';

        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $member_where[] = array('r.audit','=','2');
        } else {
            $member_where[] = array('r.audit','<>','0');
        }
        //学历分布
        $resume_rst = $this->memberService->getJobSeekersByGroup($member_where, $where_str, $edu_fields, $edu_group);
        $resume_data = $resume_rst->pluck('num', 'education')->toArray();

        $table_data = [];
        if ($edu_cates) {
            foreach ($edu_cates as $k => $v) {
                $job_num = array_has($job_data, $k)?$job_data[$k]:0;
                $resume_num = array_has($resume_data, $k)?$resume_data[$k]:0;


                if ($resume_num==0 || $job_num==0) {
                    $rate = 0;
                } else {
                    $rate = $resume_num>0?sprintf("%.2f", (int)$job_num/(int)$resume_num):'0';
                }
                $table_data[] = ['education'=>$k,'education_cn'=>$v['demand'], 'job_num'=>$job_num?$job_num:0, 'resume_num'=>$resume_num?$resume_num:0, 'rate'=>$rate];
            }
        }
        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'data'             => $table_data,
            'resume_total'     => array_sum($resume_data),
            'job_total'        => array_sum($job_data)
        ];
        return view('statistics.app.demand.education_compare', $return_data);
    }
    //需求大于求职缺口最大的前十个职业(二级分类)
    public function jobGap(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        //根据二级分类分组计算需求人数
        $job_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
            ['valid', '=', 1],
            ['display', '=', 1],
            ['category','<>',0]
        ];
        if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
            $job_where[] = array('audit', '=', 1);
        } else {
            $job_where[] = array('audit', '<>', 3);
        }
        $company_where = [
            ['utype', '=', 1],
            ['user_status', '=', 1]
        ];
        if ($subsite_id != -1) {
            $company_where['subsite_id'] = $subsite_id;
        }
        $job_field = "IFNULL(sum(amount),0) as num,category,CONCAT_WS('.',topclass,category) as cate";
        $job_group = 'category';
        $job_rst = $this->jobsService->getJobNumsByCategory($job_where, $company_where, $job_field, $job_group);

        //获取求职人数(统计简历数量)
        $resume_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
        ];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }
        $member_where = array(
            ['utype','=',2],
            ['status','=',1]
        );
        if ($subsite_id != -1) {
            //$resume_where[] = ['subsite_id','=',$subsite_id];
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $resume_group = "job_cate";
        $resume_fields = "count(id) as num,SUBSTRING_INDEX(intention_jobs_id, '.', 2) as job_cate";
        $resume_order  = '';
        $resume_rst = $this->resumeService->getResumeNumsGroup($resume_where, $member_where, $resume_fields, $resume_group, $resume_order);
        $resume_data = $resume_rst->pluck('num', 'job_cate')->toArray();

        //处理数据
        $table_data = [];
        if ($job_rst) {
            foreach ($job_rst as $k => $v) {
                $resume_num = 0;
                if (array_has($resume_data, $k)) {
                    $resume_num = $resume_data[$k];
                }
                if ($v > $resume_num) {
                    $rate = sprintf("%.2f", $resume_num>0?((int)$v/(int)$resume_num):'0');
                    $table_data[$k] = ['cate'=>$k,'job_num'=>$v, 'resume_num'=>$resume_num, 'gap'=>$v-$resume_num, 'rate'=>$rate];
                }
            }
        }
        //根据缺口对排序二维数组进行排序
        usort($table_data, function ($a, $b) {
            if ($a['gap'] == $b['gap']) {
                return 0;
            }
            return ($a['gap'] > $b['gap']) ? -1 : 1;
        });
        $data = array_slice($table_data, 0, 10);    //保留数组里前10条元素

        //处理职位分类名称
        $res_data = $this->resumeService->dealJobCategory($data);

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'res_data'         => $res_data
        ];
        if ($request->input('isExcel')==1) {
            //导出文件
            if ($res_data) {
                $total_job = 0;
                $total_resume = 0;
                foreach ($res_data as $k => $v) {
                    $total_job = (int)$total_job + (int)$v['job_num'];
                    $total_resume = (int)$total_resume + (int)$v['resume_num'];
                }
                //合计
                $total_gap = $total_job - $total_resume;
                $total_rate = 0;
                if ($total_resume>0) {
                    $total_rate = sprintf("%.2f", ((int)$total_job/(int)$total_resume));
                }
                $res_data[] = ['cate_name'=>'合计','job_num'=>$total_job, 'resume_num'=>$total_resume, 'gap'=>$total_gap, 'rate'=>$total_rate];
            }
            $export = new JobGapExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月求职缺口最大的前十个职业");
            $c = new Collection($res_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.job_gap', $return_data);
        }
    }

    //求职缺口 简历数量大于职位招聘数量(二级分类)
    public function resumeGap(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        //获取求职人数(统计简历数量)
        $resume_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
        ];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }
        $member_where = array(
            ['utype','=',2],
            ['status','=',1]
        );
        if ($subsite_id != -1) {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $resume_group = "job_cate";
        $resume_fields = "count(id) as num,SUBSTRING_INDEX(intention_jobs_id, '.', 2) as job_cate";
        $resume_order  = '';
        $resume_rst = $this->resumeService->getResumeNumsGroup($resume_where, $member_where, $resume_fields, $resume_group, $resume_order);
        $resume_data = $resume_rst->pluck('num', 'job_cate')->toArray();

        $job_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
            ['valid', '=', 1],
            ['display', '=', 1],
            ['category','<>',0]
        ];
        if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
            $job_where[] = array('audit', '=', 1);
        } else {
            $job_where[] = array('audit', '<>', 3);
        }
        $company_where = [
            ['utype', '=', 1],
            ['user_status', '=', 1]
        ];
        if ($subsite_id != -1) {
            $company_where['subsite_id'] = $subsite_id;
        }
        $job_field = "IFNULL(sum(amount),0) as num,CONCAT_WS('.',topclass,category) as cate";
        $job_group = 'category';
        $job_rst = $this->jobsService->getJobNumsByCategory($job_where, $company_where, $job_field, $job_group);

        //处理数据
        $data = [];
        if ($resume_data) {
            foreach ($resume_data as $k => $v) {
                $job_num = 0;
                if (array_has($job_rst, $k)) {
                    $job_num = $job_rst[$k];
                }
                if ($v > $job_num) {
                    $rate = sprintf("%.2f", $v>0?((int)$job_num/(int)$v):'0');
                    $data[$k] = ['cate'=>$k,'job_num'=>$job_num, 'resume_num'=>$v, 'gap'=>$v-$job_num, 'rate'=>$rate];
                }
            }
        }
        //根据缺口对排序二维数组进行排序
        usort($data, function ($a, $b) {
            if ($a['gap'] == $b['gap']) {
                return 0;
            }
            return ($a['gap'] > $b['gap']) ? -1 : 1;
        });
        $table_data = array_slice($data, 0, 10);    //保留数组里前10条元素

        //处理职位分类名称
        $res_data = $this->resumeService->dealJobCategory($table_data);

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'res_data'         => $res_data
        ];
        if ($request->input('isExcel')==1) {
            if ($res_data) {
                $total_job = 0;
                $total_resume = 0;
                $total_gap = 0;
                foreach ($res_data as $k => $v) {
                    $total_job = $total_job + (int)$v['job_num'];
                    $total_resume = $total_resume + (int)$v['resume_num'];
                }
                $total_gap = $total_resume - $total_job;
                $total_rate = 0;
                if ($total_resume>0) {
                    $total_rate = sprintf("%.2f", ((int)$total_job/(int)$total_resume));
                }
                $res_data[] = ['cate_name'=>'合计','job_num'=>$total_job, 'resume_num'=>$total_resume, 'gap'=>$total_gap, 'rate'=>$total_rate];
            }
            //导出文件
            $export = new ResumeGapExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月需求缺口最大的前十个职业");
            $c = new Collection($res_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.resume_gap', $return_data);
        }
    }

    public function dealResume(Request $request)
    {
        //过滤投递的企业所在分站
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $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);

        $company_where = [['utype','=','1'],['audit','<>','3']/*['user_status','=','1']*/];
        if ($subsite_id != '-1') {
            $company_where[] = ['subsite_id','=',$subsite_id];
        }

        //获取简历投递数量
        $apply_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time]
        ];
        $apply_nums = $this->resumeService->getApplyNum($apply_where, $company_where);

        //获取已处理简历数
        $processed_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
            ['is_reply', '>', 0]
        ];
        $processed_nums = $this->resumeService->getApplyNum($processed_where, $company_where);

        //获取待处理简历数
        $unprocessed_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
            ['is_reply', '=', 0]
        ];
        $unprocessed_nums = $this->resumeService->getApplyNum($unprocessed_where, $company_where);

        //已处理简历分组情况
        $processed_rst = $this->resumeService->getApplyNumByGroup($processed_where, $company_where, 'count(id) as count, is_reply', ['is_reply'], 'is_reply asc');
        $processed_res = $processed_rst->pluck('count', 'is_reply')->toArray();

        $apply_state = $this->apply_state;
        $processed_arr = [];
        foreach ($apply_state as $k => $v) {
            $count = 0;
            if (array_has($processed_res, $k)) {
                $count = $processed_res[$k];
            }
            $processed_arr[$k] = ['name'=>$v.'简历数', 'count'=>$count];
        }

        //获取简历未处理数量前10的企业和简历数量
        $unprocessed_companys = $this->resumeService->getApplyNumByCompanyGroup($unprocessed_where, $company_where, 'count(id) as count, company_id', ['company_id'], 'count(id) desc', 10);

        //简历合适前20企业
        $apt_where = array(
            array('created_at', '<=', $end_time),
            array('created_at', '>=', $start_time),
            array('is_reply', '=', 1)
        );
        $apt_companys = $this->resumeService->getApplyNumByCompanyGroup($apt_where, $company_where, 'count(id) as count, company_id', ['company_id'], 'count(id) desc', 20);

        $return_data = [
            'date_aprams'          => $date_aprams,
            'action_name'          => app('request')->route()->getName(),
            'apply_nums'           => $apply_nums,
            'processed_nums'       => $processed_nums,
            'unprocessed_nums'     => $unprocessed_nums,
            'processed_arr'        => $processed_arr,
            'unprocessed_companys' => $unprocessed_companys,
            'apt_companys'         => $apt_companys
        ];
        return view('statistics.app.demand.resume_deal', $return_data);
    }
    public function applyCompany(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);

        $company_where = [['utype','=','1'],['user_status','=','1']];
        if ($subsite_id != '-1') {
            $company_where[] = ['subsite_id','=',$subsite_id];
        }
        $apply_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time]
        ];

        //获取简历未处理数量前50的企业和简历数量
        $company_applys = $this->resumeService->getApplyNumByCompanyGroup($apply_where, $company_where, 'count(id) as count, company_id', ['company_id'], 'count(id) desc', 50);

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'company_applys'   => $company_applys
        ];
        return view('statistics.app.demand.company_apply', $return_data);
    }
    //按产业分组
    public function industry(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        //分别获取第一产业、第二产业和第三产业数据
        $job_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
            ['valid', '=', 1],
            ['display', '=', 1]
        ];
        if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
            $job_where[] = array('audit', '=', 1);
        } else {
            $job_where[] = array('audit', '<>', 3);
        }
        $company_where = [
            ['utype', '=', 1],
            ['user_status', '=', 1]
        ];
        if ($subsite_id != '-1') {
            $company_where['subsite_id'] = $subsite_id;
        }
        $first_industry_num = $this->jobsService->getIndustryAmount($job_where, $company_where, [44]);
        $second_industry_num = $this->jobsService->getIndustryAmount($job_where, $company_where, [6,7,13,14,15,16,17,18,19,21,25,27,28,39,40,41]);
        $third_industry_num = $this->jobsService->getIndustryAmount($job_where, $company_where, [1,2,3,4,5,8,9,10,11,12,20,22,23,24,26,29,30,31,32,33,34,35,36,37,38,42,43,45]);
        $total_num = (int)$first_industry_num + (int)$second_industry_num + (int)$third_industry_num;
        $table_data = [
            ['name'=>'第一产业', 'value'=>$first_industry_num, 'rate'=> $total_num>0?sprintf("%.4f", (int)$first_industry_num/(int)$total_num)*100:0.00],
            ['name'=>'第二产业', 'value'=>$second_industry_num , 'rate'=> $total_num>0?sprintf("%.4f", (int)$second_industry_num/(int)$total_num)*100:0.00],
            ['name'=>'第三产业', 'value'=>$third_industry_num , 'rate'=> $total_num>0?sprintf("%.4f", (int)$third_industry_num/(int)$total_num)*100:0.00]
        ];

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'table_data'       => $table_data,
            'total_num'        => $total_num
        ];

        if ($request->input('isExcel')==1) {
            if ($table_data) {
                $rate = 0;
                if ($total_num>0) {
                    $rate = 100;
                }
                $table_data[] = ['name'=>'合计','value'=>$total_num, 'rate'=>$rate];
            }
            //导出文件
            $export = new IndustryExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按产业分组的需求人数");
            $c = new Collection($table_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.industry', $return_data);
        }
    }
    //按行业分组
    public function tradeGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        $rst = $this->jobsService->getTradeAmount($start_time, $end_time, $subsite_id);

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'table_data'       => $rst['data'],
            'total_amount'     => $rst['total']
        ];

        if ($request->input('isExcel')==1) {
            $export_data = $rst['data'];
            if ($export_data) {
                $export_total = $rst['total'];
                $export_rate = 0;
                if ($export_total>0) {
                    $export_rate = 100;
                }
                $export_data[] = ['name'=>'合计','number'=>count($export_data)+1,'job_amount'=>$export_total,'rate'=>$export_rate];
            }
            //导出文件
            $export = new TradeExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按行业分组的需求人数");
            $c = new Collection($export_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.trade', $return_data);
        }
    }

    //按用人单位性质、经济类型分组
    public function companyGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        $rst = $this->jobsService->getEconomicAmount($start_time, $end_time, $subsite_id);

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'chart_data'       => $rst['chart_data'],
            'table_data'       => $rst['table_data'],
            'nature_total'     => $rst['nature_total'],
            'domestic_data'    => $rst['domestic_data'],
        ];
        if ($request->input('isExcel')==1) {
            //导出文件
            $export = new CompanyTypeExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按经济类型分组的需求人数");
            $c = new Collection($rst['table_data']);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.economic', $return_data);
        }
    }

    //按职业分组
    public function jobTypeGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        $job_num1 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [20], $subsite_id);  //单位负责人
        $job_num2 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [29,31,33,35,36,37,38,39,41,42,43,44,45,46,47,48,49], $subsite_id);  //专业技术人员
        $job_num3 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [18,23,25], $subsite_id);  //办事人员和有关人员
        $job_num4 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [11,12,13,14,15,16,17,21,22,24,26,27,28,32,40,50], $subsite_id);  //商业和服务业人员
        $job_num5 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [51], $subsite_id);  //农林牧渔水利生产人员
        $job_num6 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [19,30,34], $subsite_id);  //生产运输设备操作工
        $job_num7 = $this->jobsService->getJobTypeAmount($start_time, $end_time, [0,52], $subsite_id);  //其他
        $job_total = (int)$job_num1 + (int)$job_num2 + (int)$job_num3 + (int)$job_num4 + (int)$job_num5 + (int)$job_num6 + (int)$job_num7;

        $resume_num1 = $this->getResumeTypeAmount($start_time, $end_time, [20], $subsite_id);  //单位负责人
        $resume_num2 = $this->getResumeTypeAmount($start_time, $end_time, [29,31,33,35,36,37,38,39,41,42,43,44,45,46,47,48,49], $subsite_id);  //专业技术人员
        $resume_num3 = $this->getResumeTypeAmount($start_time, $end_time, [18,23,25], $subsite_id);  //办事人员和有关人员
        $resume_num4 = $this->getResumeTypeAmount($start_time, $end_time, [11,12,13,14,15,16,17,21,22,24,26,27,28,32,40,50], $subsite_id);  //商业和服务业人员
        $resume_num5 = $this->getResumeTypeAmount($start_time, $end_time, [51], $subsite_id);  ///农林牧渔水利生产人员
        $resume_num6 = $this->getResumeTypeAmount($start_time, $end_time, [19,30,34], $subsite_id);  //生产运输设备操作工
        $resume_num7 = $this->getResumeTypeAmount($start_time, $end_time, [0,52], $subsite_id);  //其他
        $resume_total = (int)$resume_num1 + (int)$resume_num2 + (int)$resume_num3 + (int)$resume_num4 + (int)$resume_num5 + (int)$resume_num6 + (int)$resume_num7;

        //处理数据
        $data = [
            ['name'=>'单位负责人',          'job_amount'=>$job_num1, 'resume_num'=>$resume_num1, 'multiple'=>$resume_num1>0?sprintf("%.2f", (int)$job_num1/(int)$resume_num1):'0'],
            ['name'=>'专业技术人员',        'job_amount'=>$job_num2, 'resume_num'=>$resume_num2, 'multiple'=>$resume_num2>0?sprintf("%.2f", (int)$job_num2/(int)$resume_num2):'0'],
            ['name'=>'办事人员和有关人员',  'job_amount'=>$job_num3, 'resume_num'=>$resume_num3, 'multiple'=>$resume_num3>0?sprintf("%.2f", (int)$job_num3/(int)$resume_num3):'0'],
            ['name'=>'商业和服务业人员',    'job_amount'=>$job_num4, 'resume_num'=>$resume_num4, 'multiple'=>$resume_num4>0?sprintf("%.2f", (int)$job_num4/(int)$resume_num4):'0'],
            ['name'=>'农林牧渔水利生产人员','job_amount'=>$job_num5, 'resume_num'=>$resume_num5, 'multiple'=>$resume_num5>0?sprintf("%.2f", (int)$job_num5/(int)$resume_num5):'0'],
            ['name'=>'生产运输设备操作工',  'job_amount'=>$job_num6, 'resume_num'=>$resume_num6, 'multiple'=>$resume_num6>0?sprintf("%.2f", (int)$job_num6/(int)$resume_num6):'0'],
            ['name'=>'其他',                 'job_amount'=>$job_num7, 'resume_num'=>$resume_num7, 'multiple'=>$resume_num7>0?sprintf("%.2f", (int)$job_num7/(int)$resume_num7):'0'],
        ];
        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'job_amount'       => $job_total,
            'resume_total'     => $resume_total,
            'data'             => $data
        ];
        if ($request->input('isExcel')==1) {
            if ($data) {
                foreach ($data as $k => $v) {
                    $job_rate = '0';
                    if ($job_total !=0) {
                        $job_rate = sprintf("%.4f", $v['job_amount']>0?((int)$v['job_amount']/(int)$job_total):'0')*100;
                    }
                    $data[$k]['job_rate'] = $job_rate;

                    $resume_rate = '0';
                    if ($resume_total !=0) {
                        $resume_rate = sprintf("%.4f", $v['resume_num']>0?((int)$v['resume_num']/(int)$resume_total):'0')*100;
                    }
                    $data[$k]['resume_rate'] = $resume_rate;
                }
                //添加合计信息
                $all_multiple = 0;
                if ($resume_total !=0) {
                    $all_multiple = sprintf("%.2f", $resume_total>0?((int)$job_total/(int)$resume_total):'0');
                }
                $all_job_rate = '0';
                if ($job_total>0) {
                    $all_job_rate = '100';
                }
                $all_resume_rate = '0';
                if ($resume_total>0) {
                    $all_resume_rate = '100';
                }
                $data[] = [
                    'name'       => '合计',
                    'job_amount' => $job_total,
                    'resume_num' => $resume_total,
                    'job_rate'   => $all_job_rate,
                    'resume_rate'=> $all_resume_rate,
                    'multiple'   => $all_multiple
                ];
            }
            //导出文件
            $export = new TypeExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按职业分组的供求人数");
            $c = new Collection($data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.job_type', $return_data);
        }
    }
    public function getResumeTypeAmount($start_time, $end_time, $types, $subsite_id)
    {
        $resume_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
        ];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }
        $resume_where[] = ['intention_jobs_id','in',$types];
        if ($subsite_id != '-1') {
            $resume_where[] = array('subsite_id','=',$subsite_id);
        }
        $list = $this->searchService->search('Resume', $resume_where, ['id'=>'asc'], '');
        return $list->total();
    }

    public function getEducationJobNums($start_time, $end_time, $subsite_id)
    {
        $where = $this->getJobWhere($subsite_id, $start_time, $end_time);
        $job_where = $where['job_where'];
        $company_where = $where['company_where'];
        $edu_fields = 'sum(amount) as num, education';
        $edu_group = 'education';
        $edu_order  = 'education asc';
        $edu_rst = $this->jobsService->getJobNumsByGroup($job_where, $company_where, $edu_fields, $edu_group, $edu_order);
        $job_data = [];
        if ($edu_rst) {
            foreach ($edu_rst as $k => $v) {
                $job_data[$v['education']] = $v['num'];
            }
        }
        return $job_data;
    }
    public function getEducationResumeNums($start_time, $end_time, $subsite_id)
    {
        $member_where = [
            ['m.utype','=',2],
            ['r.created_at','>=',$start_time],
            ['r.created_at','<=',$end_time]
        ];
        if ($subsite_id !='-1') {
            $member_where[] = ['m.subsite_id','=',$subsite_id];
        }
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $member_where[] = array('r.audit','=','2');
        } else {
            $member_where[] = array('r.audit','<>','0');
        }
        $edu_fields = 'count(r.id) as num, mi.education,mi.education_cn';
        $edu_group = 'mi.education';
        $where_str = 'm.deleted_at IS NULL AND mi.deleted_at IS NULL AND r.deleted_at IS NULL';
        $resume_rst = $this->memberService->getJobSeekersByGroup($member_where, $where_str, $edu_fields, $edu_group);
        $resume_data = $resume_rst->pluck('num', 'education')->toArray();
        return $resume_data;
    }

    //按文化程度分组的供求人数
    public function educationGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $EndDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$EndDate +1 month")-1);

        $date_params = $this->getCompareDate($request->all());
        $compare_start_date = $date_params['start_date_arr']?implode(' - ', $date_params['start_date_arr']):'';
        $compare_end_date   = $date_params['end_date_arr']?implode(' - ', $date_params['end_date_arr']):'';
        if ($date_params['end_date_arr']) {
            $start_time = date('Y-m-d H:i:s', strtotime($date_params['end_date_arr'][0]));
            $end_time = date('Y-m-d H:i:s', strtotime($date_params['end_date_arr'][1]." +1 day")-1);
        } else {
            $start_time = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][0]));
            $end_time = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][1]." +1 day")-1);
        }
        //过滤时间不等,需要显示对比数据
        $compare_flag = false;
        if (($date_params['end_date_arr'] != $date_params['start_date_arr']) && $date_params['end_date_arr'] && $date_params['start_date_arr']) {
            $compare_flag = true;
        }

        //获取文化程度数据 + 无要求
        $cates = $this->companyService->getCategories(['AIX_education'=>100]);
        $edu_cates = [];
        if (array_has($cates, 'AIX_education')) {
            $edu_cates = $cates['AIX_education'];
            $edu_cates['0'] = ['id'=>0, 'demand'=>'无要求'];
        }

        //获取需求信息
        $job_data = $this->getEducationJobNums($start_time, $end_time, $subsite_id);
        //获取求职人数
        $resume_data = $this->getEducationResumeNums($start_time, $end_time, $subsite_id);

        $compare_job_data = array();
        $compare_resume_data = array();
        if ($compare_flag) {
            $c_stime = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][0]));
            $c_etime = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][1]." +1 day")-1);
            $compare_job_data = $this->getEducationJobNums($c_stime, $c_etime, $subsite_id);
            $compare_resume_data = $this->getEducationResumeNums($c_stime, $c_etime, $subsite_id);
        }

        $resume_total   = array_sum($resume_data);
        $job_total      = array_sum($job_data);
        $c_job_total    = array_sum($compare_job_data);
        $c_resume_total = array_sum($compare_resume_data);
        $c_table_data = [];
        $table_data = [];
        if ($edu_cates) {
            foreach ($edu_cates as $k => $v) {
                $job_num = array_has($job_data, $k)?$job_data[$k]:0;
                $resume_num = array_has($resume_data, $k)?$resume_data[$k]:0;
                if ($resume_num==0 || $job_num==0) {
                    $rate = 0;
                } else {
                    $rate = $resume_num>0?sprintf("%.2f", (int)$job_num/(int)$resume_num):'0';
                }
                $job_rate = 0;
                if ($job_total) {
                    $job_rate = sprintf("%.4f", (int)$job_num/(int)$job_total)*100;
                }
                $resume_rate = 0;
                if ($resume_total) {
                    $resume_rate = sprintf("%.4f", (int)$resume_num/(int)$resume_total)*100;
                }

                $table_data[] = ['name'=>$v['demand'], 'job_amount'=>$job_num?$job_num:0,'job_rate'=>$job_rate, 'resume_num'=>$resume_num?$resume_num:0, 'resume_rate'=>$resume_rate,'multiple'=>$rate];

                //对比数据
                $c_job_num = array_has($compare_job_data, $k)?$compare_job_data[$k]:0;
                $c_resume_num = array_has($compare_resume_data, $k)?$compare_resume_data[$k]:0;
                if ($c_job_num==0 || $c_resume_num==0) {
                    $c_rate = 0;
                } else {
                    $c_rate = $c_resume_num>0?sprintf("%.2f", (int)$c_job_num/(int)$c_resume_num):'0';
                }
                $c_job_rate = 0;
                if ($c_job_total) {
                    $c_job_rate = sprintf("%.4f", (int)$c_job_num/(int)$c_job_total)*100;
                }
                $c_resume_rate = 0;
                if ($c_resume_total) {
                    $c_resume_rate = sprintf("%.4f", (int)$c_resume_num/(int)$c_resume_total)*100;
                }
                $c_table_data[] = ['name'=>$v['demand'], 'job_amount'=>$c_job_num?$c_job_num:0, 'job_rate'=>$c_job_rate,'resume_num'=>$c_resume_num?$c_resume_num:0, 'resume_rate'=>$c_resume_rate,'multiple'=>$c_rate];
            }
        }

        $return_data = [
            'date_aprams'          => $date_aprams,
            'date_params'          => $date_params,
            'compare_flag'         => $compare_flag,
            'compare_start_date'   => $compare_start_date,
            'compare_end_date'     => $compare_end_date,
            'compare_table_data'   => $c_table_data,
            'compare_job_total'    => $c_job_total,
            'compare_resume_total' => $c_resume_total,
            'compare_flag'         => $compare_flag,
            'action_name'          => app('request')->route()->getName(),
            'table_data'           => $table_data,
            'resume_total'         => $resume_total,
            'job_total'            => $job_total
        ];
        if ($request->input('isExcel')==1) {
            if ($table_data) {
                foreach ($table_data as $k => $v) {
                    $job_rate = '0';
                    if ($job_total !=0) {
                        $job_rate = sprintf("%.4f", $v['job_amount']>0?((int)$v['job_amount']/(int)$job_total):'0')*100;
                    }
                    $table_data[$k]['job_rate'] = $job_rate;

                    $resume_rate = '0';
                    if ($resume_total !=0) {
                        $resume_rate = sprintf("%.4f", $v['resume_num']>0?((int)$v['resume_num']/(int)$resume_total):'0')*100;
                    }
                    $table_data[$k]['resume_rate'] = $resume_rate;
                }
                //添加合计信息
                $all_multiple = 0;
                if ($resume_total !=0) {
                    $all_multiple = sprintf("%.2f", $resume_total>0?((int)$job_total/(int)$resume_total):'0');
                }
                $all_job_rate = '0';
                if ($job_total>0) {
                    $all_job_rate = '100';
                }
                $all_resume_rate = '0';
                if ($resume_total>0) {
                    $all_resume_rate = '100';
                }
                $table_data[] = [
                    'name'       => '合计',
                    'job_amount' => $job_total,
                    'resume_num' => $resume_total,
                    'job_rate'   => $all_job_rate,
                    'resume_rate'=> $all_resume_rate,
                    'multiple'   => $all_multiple
                ];
            }
            //导出文件
            $export = new EducationExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按文化程度分组的需求人数");
            $c = new Collection($table_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.education', $return_data);
        }
    }

    //按人员类别分组
    public function personTypeGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $endDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$endDate +1 month")-1);

        //按就业状态分组获取所有求职信息 AIX_current
        $resume_where = [
            ['created_at', '<=', $end_time],
            ['created_at', '>=', $start_time],
        ];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }
        $member_where = array(
            ['utype','=',2],
            ['status','=',1]
        );
        if ($subsite_id != -1) {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $resume_group = "current";
        $resume_fields = "count(id) as num,current,current_cn";
        $resume_order  = 'current desc';
        $resume_rst = $this->resumeService->getResumeNumsGroup($resume_where, $member_where, $resume_fields, $resume_group, $resume_order);
        $chart_data = [
            ['name'=>'新成长失业青年','value'=>0],
            ['name'=>'就业专业人员','value'=>0],
            ['name'=>'在业人员','value'=>0],
        ];
        $resume_num1 = 0;
        $resume_num2 = 0;
        $resume_num3 = 0;
        $resume_total = 0;
        if ($resume_rst->isNotEmpty()) {
            foreach ($resume_rst->toArray() as $k => $v) {
                if ($v['current_cn'] == '应届毕业生') {  //获取新成长失业青年求职数量(应届毕业生 245)
                    $resume_num1 = (int)$resume_num1 + (int)$v['num'];
                } elseif ($v['current_cn'] == '我目前已离职,可快速到岗') {     //获取就业专业人员求职数量(已离职可快速到岗 241)
                    $resume_num2 = (int)$resume_num2 + (int)$v['num'];
                } else {    //获取在业人员求职数量 (在职、考虑、无跳槽 242,243,244)
                    $resume_num3 = (int)$resume_num3 + (int)$v['num'];
                }
                $resume_total = (int)$resume_total + (int)$v['num'];
            }
            $chart_data = [
                ['name'=>'新成长失业青年','value'=>$resume_num1],
                ['name'=>'就业专业人员','value'=>$resume_num2],
                ['name'=>'在业人员','value'=>$resume_num3],
            ];
        }

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'chart_data'       => $chart_data,
            'resume_total'     => $resume_total
        ];
        if ($request->input('isExcel')==1) {
            if ($chart_data) {
                foreach ($chart_data as $k => $v) {
                    $rate = 0;
                    if ($resume_total>0) {
                        $rate = sprintf("%.4f", $v['value']>0?((int)$v['value']/(int)$resume_total):'0')*100;
                    }
                    $chart_data[$k]['rate'] = $rate;
                }
                $all_rate = 0;
                if ($resume_total>0) {
                    $all_rate = 100;
                }
                $chart_data[] = array('name'=>'合计','value'=>$resume_total,'rate'=>$all_rate);
            }
            $export = new PersonTypeExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按人员类别分组的供求人数");
            $c = new Collection($chart_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.person_type', $return_data);
        }
    }
    //按年龄分组
    /**
     * 年龄分组的统计口径为:
     * 在后台自动获取年龄段,每个年龄段招聘人数的计算方式为:取职位中填写的年龄段和后台年龄段对比,查看跨越几个年龄段,平均分到各个年龄段,如果有余数加到最小的年龄段内。
     * */
    public function ageGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }
        //时间过滤
        $date_aprams = $this->getDateParams($request->all());
        $start_time = date('Y-m-d H:i:s', strtotime($date_aprams['start_year'].'-'.$date_aprams['start_month']));
        $endDate = date('Y-m-d H:i:s', strtotime($date_aprams['end_year'].'-'.$date_aprams['end_month']));
        $end_time = date('Y-m-d H:i:s', strtotime("$endDate +1 month")-1);

        //获取后台年龄分类信息 categories AIX_age
        $cates = $this->categoryService->getCategories(['AIX_age'=>100]);
        if (array_has($cates, 'AIX_age')) {
            $age_cates = $cates['AIX_age'];
        } else {
            $age_cates = [];
        }
        $age_arr = [];
        $age_val_arr = [];
        if ($age_cates) {
            foreach ($age_cates as $k => $v) {
                $age_arr[] = $v['demand'];
                if (preg_match_all('(\d+)', $v['demand'], $reg)) {
                    $reg = $reg[0];
                    if (count($reg)>1) {
                        $min_age = $reg[0];
                        $max_age = $reg[1];
                    } else {
                        $min_age = $reg[0];
                        $max_age = '';
                    }
                    $age_val_arr[] = array('min_age'=>$min_age, 'max_age'=>$max_age);
                }
            }
        }
        //获取职位查询条件
        $where_arr = $this->getJobWhere($subsite_id, $start_time, $end_time);

        //获取不同年龄段的招聘人数
        $job_amounts = $this->jobsService->getJobAmountByAge($where_arr, $age_val_arr, $age_arr);
        //获取求职人数(计算简历数量)
        $resume_nums = $this->resumeService->getResumeNumsByAgeGroup($subsite_id, $start_time, $end_time, $age_val_arr, $age_arr);
        $job_total = array_sum($job_amounts);
        $resume_total = array_sum($resume_nums);
        $table_data = [];
        foreach ($age_arr as $k => $v) {
            $job_num = array_has($job_amounts, $v)?$job_amounts[$v]:0;
            $resume_num = array_has($resume_nums, $v)?$resume_nums[$v]:0;
            $job_rate = 0;
            if ($job_total) {
                $job_rate = sprintf("%.4f", (int)$job_num/(int)$job_total)*100;
            }
            $resume_rate = 0;
            if ($resume_total) {
                $resume_rate = sprintf("%.4f", (int)$resume_num/(int)$resume_total)*100;
            }
            $multiple = 0;
            if ($resume_num) {
                $multiple = sprintf("%.2f", (int)$job_num/(int)$resume_num);
            }
            $table_data[] = ['name'=>$v, 'job_amount'=>$job_num,'job_rate'=>$job_rate, 'resume_num'=>$resume_num,'resume_rate'=>$resume_rate, 'multiple'=>$multiple];
        }
        $chart_data = $table_data;

        //添加合计信息
        $total_job_rate = 0;
        if ($job_total) {
            $total_job_rate = 100;
        }
        $total_resume_rate = 0;
        $total_multiple = 0;
        if ($resume_total) {
            $total_resume_rate = 100;
            $total_multiple = sprintf("%.2f", (int)$job_total/(int)$resume_total);
        }
        $table_data[] = ['name'=>'合计', 'job_amount'=>$job_total, 'job_rate'=>$total_job_rate, 'resume_num'=>$resume_total, 'resume_rate'=>$total_resume_rate, 'multiple'=>$total_multiple];

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'table_data'       => $table_data,
            'chart_data'       => $chart_data
        ];
        if ($request->input('isExcel')==1) {
            $export = new AgeExport("总体分析 - ".$date_aprams['start_year']."年".$date_aprams['start_month']."月到".$date_aprams['end_year']."年".$date_aprams['end_month']."月按年龄分组的供求人数");
            $c = new Collection($table_data);
            $export->setCustomerData($c)->export();
        } else {
            return view('statistics.app.demand.age', $return_data);
        }
    }
    //按性别分组
    public function sexGroup(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }

        //时间过滤
        $date_params = $this->getCompareDate($request->all());
        $compare_start_date = $date_params['start_date_arr']?implode(' - ', $date_params['start_date_arr']):'';
        $compare_end_date   = $date_params['end_date_arr']?implode(' - ', $date_params['end_date_arr']):'';
        if ($date_params['end_date_arr']) {
            $start_time = date('Y-m-d H:i:s', strtotime($date_params['end_date_arr'][0]));
            $end_time = date('Y-m-d H:i:s', strtotime($date_params['end_date_arr'][1]." +1 day")-1);
        } else {
            $start_time = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][0]));
            $end_time = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][1]." +1 day")-1);
        }

        //过滤时间不等,需要显示对比数据
        $compare_flag = false;
        if (($date_params['end_date_arr'] != $date_params['start_date_arr']) && $date_params['end_date_arr'] && $date_params['start_date_arr']) {
            $compare_flag = true;
        }

        //获取简历数据 - 求职信息
        $resume_rst = $this->resumeService->getResumeBySexGroup($subsite_id, $start_time, $end_time);
        $resume_data = $this->dealSexData($resume_rst, 1);
        $resume_total = array_sum($resume_data);

        $c_resume_data  = [];
        $c_resume_total = 0;
        $c_job_data     = [];
        $c_job_total    = 0;

        //职位数量分组
        $job_rst = $this->getJobNumsBySexGroup($subsite_id, $start_time, $end_time);
        $job_data = $this->dealSexData($job_rst, 2);
        $job_total = array_sum($job_data);

        if ($compare_flag) {
            $c_stime = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][0]));
            $c_etime = date('Y-m-d H:i:s', strtotime($date_params['start_date_arr'][1]." +1 day")-1);

            $c_resume_rst = $this->resumeService->getResumeBySexGroup($subsite_id, $c_stime, $c_etime);
            $c_resume_data = $this->dealSexData($c_resume_rst);
            $c_resume_total = array_sum($c_resume_data);

            $c_job_rst = $this->getJobNumsBySexGroup($subsite_id, $c_stime, $c_etime);
            $c_job_data = $this->dealSexData($c_job_rst, 2);
            $c_job_total = array_sum($c_job_data);
        }

        //处理数据
        $sex_cates = array('0'=>'不限','1'=>'男','2'=>'女');
        $table_data = array();
        $c_table_data = array();
        foreach ($sex_cates as $k => $v) {
            $job_amount = array_has($job_data, $k)?$job_data[$k]:0;
            $resume_num = array_has($resume_data, $k)?$resume_data[$k]:0;
            $job_rate = 0;
            if ($job_total>0) {
                $job_rate = sprintf("%.4f", (int)$job_amount/(int)$job_total)*100;
            }
            $resume_rate = 0;
            if ($resume_total>0) {
                $resume_rate = sprintf("%.4f", (int)$resume_num/(int)$resume_total)*100;
            }
            if ($resume_num==0 || $job_amount==0) {
                $multiple = 0;
            } else {
                $multiple = $resume_num>0?sprintf("%.2f", (int)$job_amount/(int)$resume_num):'0';
            }
            $table_data[] = array(
                'name'=>$v,
                'job_amount'=>$job_amount,
                'job_rate'=>$job_rate,
                'resume_num'=>$resume_num,
                'resume_rate'=>$resume_rate,
                'multiple'=>$multiple
            );

            //对比数据
            $c_job_amount = array_has($c_job_data, $k)?$c_job_data[$k]:0;
            $c_resume_num = array_has($c_resume_data, $k)?$c_resume_data[$k]:0;
            $c_job_rate = 0;
            if ($c_job_total>0) {
                $c_job_rate = sprintf("%.4f", (int)$c_job_amount/(int)$c_job_total)*100;
            }
            $c_resume_rate = 0;
            if ($c_resume_total>0) {
                $c_resume_rate = sprintf("%.4f", (int)$c_resume_num/(int)$c_resume_total)*100;
            }
            if ($c_resume_num==0 || $c_job_amount==0) {
                $c_multiple = 0;
            } else {
                $c_multiple = $c_resume_num>0?sprintf("%.2f", (int)$c_job_amount/(int)$c_resume_num):'0';
            }
            $c_table_data[] = array(
                'name'=>$v,
                'job_amount'=>$c_job_amount,
                'job_rate'=>$c_job_rate,
                'resume_num'=>$c_resume_num,
                'resume_rate'=>$c_resume_rate,
                'multiple'=>$c_multiple
            );
        }
        //合计信息
        $all_job_rate = 0;
        if ($job_total>0) {
            $all_job_rate = sprintf("%.4f", (int)$job_total/(int)$job_total)*100;
        }
        $all_resume_rate = 0;
        if ($resume_total>0) {
            $all_resume_rate = sprintf("%.4f", (int)$resume_total/(int)$resume_total)*100;
        }
        $all_multiple = 0;
        if ($resume_total>0) {
            $all_multiple = sprintf("%.2f", (int)$job_total/(int)$resume_total);
        }
        $table_data[] = array(
            'name'=>'合计',
            'job_amount'=>$job_total,
            'job_rate'=>$all_job_rate,
            'resume_num'=>$resume_total,
            'resume_rate'=>$all_resume_rate,
            'multiple'=>$all_multiple
        );

        $call_job_rate = 0;
        if ($c_job_total>0) {
            $call_job_rate = sprintf("%.4f", (int)$c_job_total/(int)$c_job_total)*100;
        }
        $call_resume_rate = 0;
        if ($c_resume_total>0) {
            $call_resume_rate = sprintf("%.4f", (int)$c_resume_total/(int)$c_resume_total)*100;
        }
        $call_multiple = 0;
        if ($c_resume_total>0) {
            $call_multiple = sprintf("%.2f", (int)$c_job_total/(int)$c_resume_total);
        }
        $c_table_data[] = array(
            'name'=>'合计',
            'job_amount'=>$c_job_total,
            'job_rate'=>$call_job_rate,
            'resume_num'=>$c_resume_total,
            'resume_rate'=>$call_resume_rate,
            'multiple'=>$call_multiple
        );

        $return_data = [
            'date_params'          => $date_params,
            'compare_start_date'   => $compare_start_date,
            'compare_end_date'     => $compare_end_date,
            'action_name'          => app('request')->route()->getName(),
            'compare_flag'         => $compare_flag,
            'table_data'           => $table_data,
            'compare_table_data'   => $c_table_data,
            'job_total'            => $job_total,
            'compare_job_total'    => $c_job_total,
            'resume_total'         => $resume_total,
            'compare_resume_total' => $c_resume_total
        ];
        return view('statistics.app.demand.sex', $return_data);
    }
    public function getJobNumsBySexGroup($subsite_id, $start_time, $end_time)
    {
        $job_where = [
            ['created_at','<=',$end_time],
            ['created_at','>=',$start_time],
            ['valid','=',1]
        ];
        if (config('aix.companyset.comset.show_set.jobs_display')==1) {
            $job_where[] = array('audit','=',1);
        } else {
            $job_where[] = array('audit','<>',3);
        }
        $company_where = array(array('utype','=',1),array('audit','<>',3));
        if ($subsite_id != -1) {
            $company_where[] = ['subsite_id','=',$subsite_id];
        }
        $fields = 'sum(amount) as num,sex';
        $group_by = 'sex';
        return $this->jobsService->getJobNumsByGroup($job_where, $company_where, $fields, $group_by);
    }
    public function dealSexData($data, $type = 1)
    {
        $rst = array();
        if ($type == 1) {
            if (count($data)) {
                foreach ($data as $k => $v) {
                    $rst[$v->sex] = $v->num;
                }
            }
        } else {
            if (count($data)) {
                foreach ($data as $k => $v) {
                    $rst[$v['sex']] = $v['num'];
                }
            }
        }

        return $rst;
    }

    public function getJobWhere($subsite_id, $start_time, $end_time)
    {
        $job_where = [
            ['created_at','<=',$end_time],
            ['created_at','>=',$start_time],
            ['valid','=',1],
            //['display','=',1]
        ];
        if (config('aix.companyset.comset.show_set.jobs_display')==1) {
            $job_where[] = array('audit','=',1);
        } else {
            $job_where[] = array('audit','<>',3);
        }
        //$company_where = ['utype'=>1,'user_status'=>1];
        $company_where = [['utype','=',1],['audit','<>',3]];
        if ($subsite_id != -1) {
            $company_where[] = ['subsite_id','=',$subsite_id];
        }
        return ['job_where'=>$job_where, 'company_where'=>$company_where];
    }


    public function getJobfairs($subsite_id)
    {
        $j_where = array();
        if ($subsite_id != -1) {
            $j_where[] = ['subsite_id','=',$subsite_id];
        }
        $j_where[] = ['holddate_end','<=',time()];
        $j_order = 'id desc';
        $jobfair_rst = $this->jobfairService->getJobfairs($j_where, $j_order);
        $jobfairs = array();
        if ($jobfair_rst->isNotEmpty()) {
            foreach ($jobfair_rst as $k => $v) {
                $jobfairs[$v->id] = array('title'=>$v->title,'holddate_end'=>$v->holddate_end);
            }
        }
        return $jobfairs;
    }
}