<?php
namespace App\Http\Controllers\Statistics;
use App\Http\Controllers\Statistics\StatisticsBaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Services\Statistics\MemberService;
use App\Services\Statistics\ResumeService;
use App\Services\Statistics\CategoryService;


class PersonController extends StatisticsBaseController
{
    protected $memberService;
    protected $resumeService;
    protected $categoryService;
    /**
     * PersonController constructor.
     */
    public function __construct(MemberService $memberService, ResumeService $resumeService, CategoryService $categoryService)
    {
        $this->memberService   = $memberService;
        $this->resumeService   = $resumeService;
        $this->categoryService = $categoryService;
    }

    public function getBasicInfo($start_time, $end_time, $subsite_id)
    {
        $member_map = [['utype','=',2], ['status','=',1]];
        if ($subsite_id !='-1') {
            $member_map[]   = ['subsite_id','=',$subsite_id];
        }
        //获取会员数量
        $all_member_num = $this->memberService->getMemberNums($member_map);
        $member_where = [
            ['utype','=',2],
            ['status','=',1],
            ['created_at','>=',$start_time],
            ['created_at','<=',$end_time]
        ];
        if ($subsite_id !='-1') {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $current_member_num = $this->memberService->getMemberNums($member_where);
        $all_resume_where = [];
        $resume_where = [['created_at','>=',$start_time], ['created_at','<=',$end_time]];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
            $all_resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
            $all_resume_where[] = array('audit','<>','0');
        }

        //简历数量统计
        $resume_all_nums = $this->resumeService->getResumeNum($all_resume_where, $member_map);
        $resume_current_nums = $this->resumeService->getResumeNum($resume_where, $member_map);

        return ['all_member_num' => $all_member_num,'current_member_num'=>$current_member_num, 'resume_all_nums'=>$resume_all_nums,'resume_current_nums'=>$resume_current_nums];
    }
    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);

        $member_where = [
            ['utype','=',2],
            ['status','=',1],
            ['created_at','>=',$start_time],
            ['created_at','<=',$end_time]
        ];
        if ($subsite_id !='-1') {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }

        //获取会员、简历数量信息
        $person_num_data = $this->getBasicInfo($start_time, $end_time, $subsite_id);

        $edu_fields = 'count(id) as num, education_cn';
        $edu_group = 'education';

        //学历分布
        $edu_rst = $this->memberService->getMemberNumsGroup([], $member_where, $edu_fields, $edu_group);
        $edu_data = [];
        $edu_names = [];
        if ($edu_rst) {
            foreach ($edu_rst as $k => $v) {
                $edu_data[] = ['value'=>$v['num'],'name'=>$v['education_cn']];
                $edu_names[] = $v['education_cn'];
            }
        }

        //年龄分布 - 改成后台配置项 有些数据可能查询不到
        //获取系统年龄分类
        $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  = [];
        $age_fields = 'count(id) as num';
        $age_group = '';
        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];
            }
            $where = [];
            if ($min_age>0) {
                $where[] = ['birthday', '<=',date('Y', strtotime("-$min_age year"))];
            }
            if ($max_age>0) {
                $where[] = ['birthday', '>=',date('Y', strtotime("-$max_age year"))];
            }
            $age_rst = $this->memberService->getMemberNumsGroup($where, $member_where, $age_fields, $age_group);
            $age_data[] = $age_rst[0]['num'];
        }

        //性别分布
        $sex_fields = 'count(id) as num, sex_cn';
        $sex_group = 'sex';
        $sex_rst = $this->memberService->getMemberNumsGroup([], $member_where, $sex_fields, $sex_group);
        $sex_data = [];
        $sex_names = [];
        if ($sex_rst) {
            foreach ($sex_rst as $k => $v) {
                $sex_data[] = ['value'=>$v['num'],'name'=>$v['sex_cn']];
                $sex_names[] = $v['sex_cn'];
            }
        }
        //户籍分布 - 后台设置中的默认地区统计三级地区(三级地区选择不限则显示二级地区),其他显示省,默认地区所在省不包括默认地区
        $all_districts = $this->categoryService->getDistricts();//获取所有地区名称
        $default_district = config('aix.system.site_other.site_other.district');//获取默认地区

        $address_fields = "count(id) as num, householdaddress_cn,substring_index(householdaddress,'.',1) as f_district,substring_index(substring_index(householdaddress,'.',2),'.',-1) as s_district,substring_index(householdaddress,'.',-1) as t_district,if(substring_index(householdaddress,'.',2) = '".$default_district."',householdaddress_cn,substring_index(householdaddress_cn,'-',1)) as address_cn,if(substring_index(householdaddress,'.',2)='".$default_district."',substring_index(householdaddress,'.',-1),substring_index(householdaddress,'.',1)) as address_id";
        $address_group = 'address_id';
        $address_order = 'count(id) desc';
        $address_rst = $this->memberService->getMemberNumsGroup([['householdaddress','<>', '']], $member_where, $address_fields, $address_group, $address_order, 10);
        $address_data = [];
        $address_names = [];
        if ($address_rst) {
            foreach ($address_rst as $k => $v) {
                $address_data[] = $v['num'];
                if ($v['address_id'] == 0) {
                    $address_cn = $all_districts[$v['s_district']]['name'];
                } else {
                    if ($all_districts[$v['address_id']]['parent_id']>0) {
                        $address_cn = $all_districts[$v['s_district']]['name'].'-'.$all_districts[$v['address_id']]['name'];
                    } else {
                        $address_cn = $all_districts[$v['address_id']]['name'];
                    }
                }
                $address_names[] = $address_cn;

            }
        }

        $return_data = [
            'date_aprams'  => $date_aprams,
            'current_member_num' => $person_num_data['current_member_num'],
            'all_member_num'     => $person_num_data['all_member_num'],
            'resume_all_nums'    => $person_num_data['resume_all_nums'],
            'resume_current_nums'=> $person_num_data['resume_current_nums'],
            'edu_data'     => $edu_data,
            'edu_names'    => $edu_names,
            'age_data'     => $age_data,
            'age_names'    => $age_names,
            'sex_data'     => $sex_data,
            'sex_names'    => $sex_names,
            'address_data' => $address_data,
            'address_names'=> $address_names,
            'action_name'  => app('request')->route()->getName()
        ];
        return view('statistics.app.person.index', $return_data);
    }
    public function jobAnalysis(Request $request)
    {
        $subsite_id = session('caiqing_susbite_id');
        if ($subsite_id === null) {
            $subsite_id = -1;
        }

        //时间过滤
        $date_aprams = $this->getDateDetail($request->all());
        $start_time  = date('Y-m-d H:i:s', strtotime($date_aprams['start_date']));
        $end_time    = date('Y-m-d H:i:s', strtotime($date_aprams['end_date'].' +1 day')-1);

        //获取会员、简历数量信息
        $person_num_data = $this->getBasicInfo($start_time, $end_time, $subsite_id);

        $member_where = [
            ['utype','=',2],
            ['status','=',1]
        ];
        if ($subsite_id !='-1') {
            $member_where[] = ['subsite_id','=',$subsite_id];
        }
        $resume_where = [['created_at','>=',$start_time], ['created_at','<=',$end_time]];
        if (config('aix.personal_set.per_set.show_set.resume_display')=='1') {
            $resume_where[] = array('audit','=','2');
        } else {
            $resume_where[] = array('audit','<>','0');
        }

        //职位大类top10 + 职位小类top10
        $class_fields = 'id,intention_jobs_id,intention_jobs';
        $class_group = '';
        $class_order = 'id desc';
        $class_rst = $this->resumeService->getResumeNumByClassGroup($resume_where, $member_where, $class_fields, $class_group, $class_order, '10');

        //获取投递前十的职位种类的简历数量 - 简历所在分站的所有投递信息,包括已删除数据
        $apply_where = [['p.created_at','>=',$start_time], ['p.created_at','<=',$end_time]];
        if ($subsite_id !='-1') {
            $apply_where[] = ['m.subsite_id','=',$subsite_id];
        }
        $apply_group = 'cp.trade';
        $apply_order = 'count(p.id) DESC';
        $order_fileds = 'count(p.id) as num,cp.trade,c.demand';
        $apply_rst = $this->resumeService->getResumeApplyGroup($apply_where, $order_fileds, $apply_group, $apply_order, 10);
        $apply_data = [];
        $apply_name = [];
        if ($apply_rst->isNotEmpty()) {
            foreach ($apply_rst as $k => $v) {
                $apply_name[] = $v->demand;
                $apply_data[] = $v->num;
            }
        }

        //按学历分布的薪资(统计各个学历的平均薪资(如工资要求2000~3000,则取2500,工资要求10000以上取10000,工资要求1000以下,取1000))
        $edu_fields = 'education,education_cn,count(id) as num,sum((if(wage_min=0 && wage_max>0, wage_max, wage_min)+if(wage_max=0 && wage_min>0, wage_min, wage_max))/2) as total_wage';
        $edu_group = 'education';
        $edu_order = '';
        $edu_rst = $this->resumeService->getAvgWageByEducation($resume_where, $member_where, $edu_fields, $edu_group, $edu_order);
        $wage_data = [];
        $edu_data  = [];
        if ($edu_rst) {
            foreach ($edu_rst as $k => $v) {
                $wage_data[] = round(($v['total_wage']/$v['num']), 2);
                $edu_data[]  = $v['education_cn'];
            }
        }

        $return_data = [
            'date_aprams'      => $date_aprams,
            'action_name'      => app('request')->route()->getName(),
            'top_data'         => $class_rst['top_arr'],
            'top_name_data'    => $class_rst['top_name_arr'],
            'second_data'      => $class_rst['second_arr'],
            'second_name_data' => $class_rst['second_name_arr'],
            'wage_data'        => $wage_data,
            'edu_data'         => $edu_data,
            'apply_name'       => $apply_name,
            'apply_data'       => $apply_data,
            'date_aprams'        => $date_aprams,
            'current_member_num' => $person_num_data['current_member_num'],
            'all_member_num'     => $person_num_data['all_member_num'],
            'resume_all_nums'    => $person_num_data['resume_all_nums'],
            'resume_current_nums'=> $person_num_data['resume_current_nums'],
        ];
        return view('statistics.app.person.job_anaysis', $return_data);
    }



}