<?php
/**
 * Created by PhpStorm.
 * User: wuzhenke
 * Date: 2018/11/6
 * Time: 13:18
 */

namespace App\Repositories;

use App\Models\Jobs;
use App\Models\JobsContact;
use App\Models\Company;
use App\Models\Category;
use Prettus\Repository\Criteria\RequestCriteria;
use Prettus\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class JobsRepository extends BaseRepository
{
    /*protected $company;
    protected $jobs;*/
    /**
     * JobsRepository constructor.
     */
    /*public function __construct(Jobs $jobs, Company $company)
    {
        $this->company = $company;
        $this->jobs    = $jobs;
    }*/


    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Jobs::class;
    }

    /**
     * Boot up the repository, pushing criteria
     */
    public function boot()
    {
        $this->pushCriteria(app(RequestCriteria::class));
    }

    public function getFires($job_id)
    {
        return $this->model->where(['id'=>$job_id])->first();
    }

    public static function countAuditJobsNum()
    {
        $where['company_id'] = auth('web-company')->user()->id;
        $map = [];
        if (config('aix.companyset.comset.show_set.jobs_display') == 1) {
            $where['audit'] = 1;
        } else {
            $map[] = ['id','>',0];
        }
        return Jobs::where($where)->where($map)->count();
    }

    public function getJobsList($where,$limit = 10)
    {
        return $this->model->where($where)->paginate($limit);
    }

    /**
     * 根据企业ID获取职位
     * @param $company_id
     * @return mixed
     */
    public function getJobsByUid($company_id)
    {
        return $this->findWhere(['company_id'=>$company_id]);
    }

    /**
     * 根据职位ID获取职位信息
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Model[]|null
     */
    public function getJobsById($id)
    {
        return $this->model->with('jobsContact')->with('subsites')->find($id);
    }

    public function jobsSelect($uid)
    {
        return $this->model->where('company_id', $uid)->orderBy('created_at', 'asc')->get();
    }

    public function modifyData($ids, $data)
    {
        return $this->model->whereIn('id', $ids)->update($data);
    }

    public function modifyCom($comidArr, $data)
    {
        return $this->model->whereIn('id', $comidArr)->update($data);
    }

    /**
     * 更新map数据
     * @param $id
     * @param $data
     * @return mixed
     */
    public function updateMap($id, $data)
    {
        return $this->model->where('company_id', $id)->update($data);
    }


    public function updateSubsite($jidArr, $subsite_id)
    {
        return $this->model->whereIn('id', $jidArr)->update(['subsite_id'=>$subsite_id]);
    }
    /**
     * 职位管理列表
     * @param $page
     * @param $where
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function list($page, $where, $orwhere)
    {
        return $this->model->with(['promotion'])->where($where)->where(function ($query) use ($orwhere) {
            if ($orwhere) {
                if (isset($orwhere[3])) {
                    $query->orWhere('display', $orwhere[0])->orWhere('valid', $orwhere[1])->orWhere('audit', "=", 3);
                } else {
                    $query->orWhere('display', $orwhere[0])->orWhere('valid', $orwhere[1])->orWhere('audit', "<>", $orwhere[2]);
                }
            }
        })->orderByRaw('display asc,audit asc,refresh_time desc')->paginate($page, ['*']);
    }

    /**
     * 某企业发布职位数
     * @return mixed
     */
    public function jobsTotal($where)
    {
        return $this->model->where($where)->count();
    }

    /**
     * 我是否有这个职位
     * @return mixed
     * @param $user
     * @param  $ids
     */
    public function jobsHas($user,$ids)
    {
        if (is_string($ids)){
            $ids=explode(",",$ids);
        }
        return $this->model->whereIn("id",$ids)->where('company_id',$user->id)->count();
    }

    public function jobAuditTotal($where, $audit)
    {
        return $this->model->where($where)->whereIn('audit',$audit)->count();
    }

    public function getComJobs($where, $field = '*')
    {
        return $this->model->select($field)->where($where)->get()->toArray();
    }

    /**
     * 添加职位
     * @param $jobData
     * @return mixed
     */
    public function store($jobData)
    {

         return  $this->model->create($jobData);
    }

    /**
     * 关闭职位
     * @param $ids
     * @return mixed
     */
    public function closeJobs($ids)
    {
        return $this->model->whereIn('id', $ids)->update(['display'=>2,'valid'=>0]);
    }

    /**恢复职位
     * @param $ids
     * @return mixed
     */
    public function showJobs($ids, $data)
    {
        return $this->model->whereIn('id', $ids)->update($data);
    }

    /**
     * 删除职位
     * @param $ids
     * @return mixed
     */
    public function delJobs($ids)
    {
        return $this->model->whereIn('id', $ids)->delete();
    }

    public function getJobs($id)
    {
        return $this->model->with('jobsContact')->whereIn('id', $id)->get();
    }
    public function jobsRefresh($job_id)
    {
        return $this->update(['refresh_time'=>time()], $job_id);
    }

    public function findJobsName($jid)
    {
        return $this->model->whereIn('id', $jid)->select('id', 'jobs_name')->get()->toArray();
    }

    public function applyJobs($where, $id)
    {
        return $this->model->where($where)->where('company_id', $id)->select(['id','jobs_name'])->get()->toArray();
    }

    /**
     * 查找职位
     * @param $map
     * @return mixed
     */
    public function jobsList($map)
    {
        return $this->model->select(['id', 'jobs_name'])->where($map)->get();
    }
    /**
     * 获取职位
     * @param $where
     * @return mixed
     */
    public function getInfo($where)
    {
        return $this->model->where($where)->first();
    }
    //增加点击量
    public function incrementData($where, $num, $filed)
    {
        $model = $this->model->where($where)->first();
        $model->click = $model->$filed + $num;
        $model->timestamps = false;
        return $model->save();
    }
    //根据条件获取职位列表
    public function getOtherJobs($where, $limit = '')
    {
//        $rst = $this->model->whereHas('subsites', function ($query) { $query->where('subsite_id', get_subsite_id());})->where($where)->orderBy('stime', 'DESC')->orderBy('refresh_time', 'DESC');
        $rst = $this->model->where($where)->orderBy('stime', 'DESC')->orderBy('refresh_time', 'DESC');
        if ($limit) {
            return $rst->paginate($limit);
        }else{
            return $rst->get();
        }

    }

    public function getCompanyOtherJobs($where,$page=1,$pageSize=6,$category_id=[])
    {
        $offset = ($page - 1) * $pageSize;
        return $this->model->whereHas('subsites', function ($query) {
            $query->where('subsite_id', get_subsite_id());
        })->where(function ($query) use($where,$category_id){
            if($category_id){
                $query->whereIn('category',$category_id);
            }
            $query->where($where);
        })->orderBy('stime', 'DESC')->orderBy('refresh_time', 'DESC')->offset($offset)->limit($pageSize)->get();
    }

    public function getOtherJobsCount($where, $limit = '')
    {
        $rst = $this->model->where($where)->orderBy('stime', 'DESC')->orderBy('refresh_time', 'DESC');
        if ($limit) {
            return $rst->paginate($limit);
        } else {
            return $rst->get();
        }
    }

    //获取符合条件的职位数量
    public function getJobsCount($where)
    {
        return $this->model->whereHas('subsites', function ($query) { $query->where('subsite_id', get_subsite_id());})->where($where)->count();
    }


    /**
     * 获取单条职位(在招的)
     * @param $data 条件
     * @return bool返回值 如果有返回职位数组,否则返回 false
     */
    public function getAuditJobsOne($data)
    {
        $val = $this->model->where($data)->first();
        if (!$val) {
            return false;
        }
        $val->contact= JobsContact::where('job_id', $val->id)->first();
        $val->deadline_days=($val->deadline-time())>0?"距到期时间还有<strong style=\"color:#FF0000\">".sub_day($val->deadline, time())."</strong>":"<span style=\"color:#FF6600\">目前已过期</span>";
        return $val;
    }

    public function recommendJobs($intenionArrTwo, $intenionArrThree, $page=1, $where, $pageSize=12)
    {
        $offset = ($page - 1) * $pageSize;
        return $this->model->whereIn('audit', $where)->where('display', 1)->where('valid', 1)->where(function ($query) use ($intenionArrTwo, $intenionArrThree) {
            $query->whereIn('category', $intenionArrTwo)->orWhereIn('subclass', $intenionArrThree);
        })->offset($offset)->limit($pageSize)->get();
    }
    
    public function nearbyJobs($lng, $lat, $page=1, $where, $pageSize=12)
    {
        $offset = ($page - 1) * $pageSize;
        return $this->model->whereBetween('map_x', $lng)->whereBetween('map_y', $lat)->whereIn('audit', $where)->where('display', 1)->where('valid', 1)->offset($offset)->limit($pageSize)->get();
    }

    public function new_jobs($data, $page=1, $where, $pageSize=12)
    {
        $offset = ($page - 1) * $pageSize;
        return $this->model->where('refresh_time', '>', $data)->whereIn('audit', $where)->where('display', 1)->where('valid', 1)->offset($offset)->limit($pageSize)->get();
    }

    /**
     * 获取已关闭/未关闭的职位.
     */
    public function getDisplayJobs($id, $display)
    {
        return $this->model->whereIn('id', $id)->where('display', $display)->get()->toArray();
    }

    public function getLastJobsCount($where)
    {
        return $this->model->where($where)->where('created_at', '>=', date('Y-m-01 00:00:00', strtotime('-1 month')))->where('created_at', '<=', date("Y-m-d 23:59:59", strtotime(-date('d').'day')))->count();
    }

    public function getNextJobsCount($where)
    {
        return $this->model->where($where)->where('created_at', '>=', date('Y-m-01 00:00:00', strtotime(date("Y-m-d"))))->where('created_at', '<=', date('Y-m-d 23:59:59', strtotime(date('Y-m-01', strtotime(date("Y-m-d")))." +1 month -1 day")))->count();
    }

    public function getJobCount($where)
    {
        return $this->model->where($where)->count();
    }
    //获取用户中心用于匹配推荐简历的职位
    public function getMatchJob($where, $whereNotIn = array(), $order_by = array())
    {
        $rst = $this->model->where($where);
        if ($whereNotIn) {
            $rst->whereNotIn(key($whereNotIn), $whereNotIn[key($whereNotIn)]);
        }
        if (is_array($order_by)) {
            foreach ($order_by as $k => $v) {
                $rst->orderBy($k, $v);
            }
        } else {
            $rst->orderBy('stime', 'DESC')->orderBy('refresh_time', 'DESC');
        }
        return $rst->first();
    }
    //获取有招聘职位的知名企业
    public function getJobCompanies($where, $order, $limit = '')
    {
        $rst = $this->model->whereHas('subsites', function ($query) { $query->where('subsite_id', get_subsite_id());})->select(DB::raw('distinct company_id,count(id) as jobs_num'))->where($where);
        if ($order && is_array($order)) {
            foreach ($order as $k => $v) {
                $rst->orderBy($k, $v);
            }
        }
        $rst->groupBy('company_id');
        if ($limit) {
            $rst->limit($limit);
        }
        return $rst->get();
    }
    public function getCompanyJobs($where = array(), $where_in = array(), $order = array(), $limit = '')
    {
        $rst = $this->model->with('company')->where($where);
        if ($where_in) {
            foreach ($where_in as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        if ($order && is_array($order)) {
            foreach ($order as $k => $v) {
                $rst->orderBy($k, $v);
            }
        }
        if ($limit) {
            $rst->limit($limit);
        }
        return $rst->get();
    }
    public function fliterJobs($where = array(), $where_in = array(), $order = array())
    {
        $rst = $this->model->where($where);
        if ($where_in) {
            foreach ($where_in as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        if ($order && is_array($order)) {
            foreach ($order as $k => $v) {
                $rst->orderBy($k, $v);
            }
        }
        return $rst->get();
    }

    public function autoRefreshJobs($ids)
    {
        return $this->model->whereIn('id', $ids)->update(['refresh_time'=>time()]);
    }

    public function getName($id)
    {
        return $this->model->where('id', $id)->value('jobs_name');
    }
    public function getJobNumGroup($where, $company_where, $group_by)
    {
        return $this->model->select(DB::raw('count(id),DATE(created_at)'))
            ->where($where)
            ->when($company_where, function ($query) use ($company_where) {
                $query->whereHas('company', function ($query) use ($company_where) {
                    $query->where($company_where);
                });
            })
            ->groupBy($group_by)
            ->get();
    }

    public function getNumsByGroup($where, $company_where, $fields, $group_by = '', $order_by = '', $whereIn = [])
    {
        $rst = $this->model->select(DB::raw($fields))->where($where)->when($company_where, function ($query) use ($company_where) {
                $query->whereHas('company', function ($query) use ($company_where) {
                    $query->where($company_where);
                });
        });
        if ($whereIn) {
            foreach ($whereIn as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        if ($group_by) {
            if (is_array($group_by)) {
                foreach ($group_by as $k => $v) {
                    $rst->groupBy($v);
                }
            } else {
                $rst->groupBy($group_by);
            }
        }
        if ($order_by) {
            $rst->orderByRaw($order_by);
        }
        return $rst->get();
    }

    public function getJobNumByTradeGroup($where, $fields, $group_by, $order_by = '', $limit = '')
    {
        $rst = DB::table(Jobs::getTableName().' as j')->select(DB::raw($fields))
                 ->leftjoin(Company::getTableName().' as c', 'c.id', '=', 'j.company_id')
                 ->where($where)
                 ->whereRaw('j.deleted_at is null and c.deleted_at is null')
                 ->groupBy($group_by);
        if ($order_by) {
            $rst->orderByRaw($order_by);
        }
        if ($limit) {
            $rst->offset(0)->limit($limit);
        };
        return $rst->get();
    }

    public function getAvgWageByGroup($where, $company_where, $fields, $group_by, $order_by, $limit)
    {
        $rst = $this->model->select(DB::raw($fields))->where($where)->when($company_where, function ($query) use ($company_where) {
            $query->whereHas('company', function ($query) use ($company_where) {
                $query->where($company_where);
            });
        });
        if ($group_by) {
            $rst->groupBy($group_by);
        }
        if ($order_by) {
            $rst->orderByRaw($order_by);
        }
        if ($limit) {
            $rst->offset(0)->limit($limit);
        }
        return $rst->get();
    }
    public function getJobIndustryAmount($where, $company_where, $industry_ids)
    {
        $rst = $this->model->where($where)->when($company_where, function ($query) use ($company_where, $industry_ids) {
            $query->whereHas('company', function ($query) use ($company_where, $industry_ids) {
                $query->where($company_where);
                if ($industry_ids) {
                    $query->whereIn('industry', $industry_ids);
                }
            });
        });
        return $rst->sum('amount');
    }

    public function getIndustryAmount($where, $company_where, $trades)
    {
        $rst = $this->model->where($where)->when($company_where, function ($query) use ($company_where, $trades) {
            $query->whereHas('company', function ($query) use ($company_where, $trades) {
                $query->where($company_where);
                if ($trades) {
                    $query->whereIn('trade', $trades);
                }
            });
        });
        return $rst->sum('amount');
    }

    public function getJobAmountByNature($where, $job_where, $company_where)
    {
        $rst = DB::table(Jobs::getTableName().' as j')->selectRaw('sum(j.amount) as num, p.nature')
            ->leftjoin(Company::getTableName().' as p', 'p.id', '=', 'j.company_id')
            ->leftjoin(Category::getTableName().' as c', 'c.id', '=', 'p.nature')
            ->where($job_where)
            ->where($company_where)
            ->whereRaw($where)
            ->groupBy('p.nature')
            ->orderByRaw('p.nature asc')
            ->get();
        return $rst;
    }

    public function getJobAmountByEconomy($where, $job_where, $company_where, $nature_ids)
    {
        $rst = DB::table(Jobs::getTableName().' as j')
            ->selectRaw('IFNULL(sum(j.amount),0) as num, p.economy')
            ->leftjoin(Company::getTableName().' as p', 'p.id', '=', 'j.company_id')
            ->leftjoin(Category::getTableName().' as c', 'c.id', '=', 'p.economy')
            ->where($job_where)
            ->where($company_where)
            ->whereRaw($where)
            ->whereIn('p.nature', $nature_ids)
            ->groupBy('p.economy')
            ->orderByRaw('p.economy asc')
            ->get();
        return $rst;
    }
    public function getJobAmountByEconomyGroup($where, $job_where, $company_where, $fields = 'IFNULL(sum(j.amount),0) as num, p.economy', $group = [], $order = '')
    {
        $rst = DB::table(Jobs::getTableName().' as j')
            ->selectRaw($fields)
            ->leftjoin(Company::getTableName().' as p', 'p.id', '=', 'j.company_id')
            ->where($job_where)
            ->where($company_where);
        if ($where) {
            $rst->whereRaw($where);
        }
        if ($group) {
            foreach ($group as $k => $v) {
                $rst->groupBy($v);
            }
        }
        if ($order) {
            $rst->orderByRaw('p.economy asc');
        }
        $res = $rst->get();
        return $res;
    }
    public function getJobTypeAmount($job_where, $company_where, $types)
    {
        return $this->model->where($job_where)->when($company_where, function ($query) use ($company_where) {
                    $query->whereHas('company', function ($query) use ($company_where) {
                        $query->where($company_where);
                    });
        })->when($types, function ($query) use ($types) {
            $query->whereIn('category', $types);
        })->sum('amount');
    }
    public function getJobAmountByType($job_where, $company_where, $whereRaw)
    {
        return $this->model->where($job_where)->when($company_where, function ($query) use ($company_where) {
            $query->whereHas('company', function ($query) use ($company_where) {
                $query->where($company_where);
            });
        })->when($whereRaw, function ($query) use ($whereRaw) {
            $query->whereRaw($whereRaw);
        })->get();
    }

    public function getJobAmountByAge($where, $job_where, $company_where, $fields, $group_by = '', $order_by = '')
    {
        $rst = $this->model->select(DB::raw($fields))->where($job_where)->when($where, function ($query) use ($where) {
            $query->whereRaw($where);
        })->when($company_where, function ($query) use ($company_where) {
            $query->whereHas('company', function ($query) use ($company_where) {
                $query->where($company_where);
            });
        });
        if ($group_by) {
            $rst->groupBy($group_by);
        }
        if ($order_by) {
            $rst->orderByRaw($order_by);
        }
        return $rst->get();
    }

    public function getJobAmountByAges($age_data, $age_text, $ages, $where, $job_where, $company_where, $fields, $group_by = '', $order_by = '')
    {
        $rst = $this->model->select(DB::raw($fields))->where($job_where)->when($where, function ($query) use ($where) {
            $query->whereRaw($where);
        })->when($company_where, function ($query) use ($company_where) {
            $query->whereHas('company', function ($query) use ($company_where) {
                $query->where($company_where);
            });
        });
        if ($group_by) {
            $rst->groupBy($group_by);
        }
        if ($order_by) {
            $rst->orderByRaw($order_by);
        }
        $res = $rst->chunk(500, function ($lave_rst) use (&$age_data, $age_text, $ages) {
            if ($lave_rst->isNotEmpty()) {
                //处理每条数据所属年龄段
                foreach ($lave_rst as $key => $val) {
                    if ($val->num > 0) {
                        $j_min_age = $val['min_age'];
                        $j_max_age = $val['max_age'];
                        $relative_age_arr = [];
                        foreach ($ages as $k => $v) {
                            $min_age = $v['min_age'];
                            $max_age = $v['max_age'];
                            if ($j_min_age && $j_max_age) {
                                if ($j_min_age <= $max_age && $j_max_age>=$min_age) {
                                    $relative_age_arr[] = $age_text[$k];
                                }
                            }
                        }
                        if ($relative_age_arr) {
                            //将职位招聘人数平均分配给符合的年龄段,剩余的给第一个符合的年龄段
                            $lave_quotient = intval(floor($val->num/count($relative_age_arr)));
                            $lave_remainder = $val->num % count($relative_age_arr);
                            foreach ($relative_age_arr as $n => $r) {
                                $age_data[$r] = (int)$age_data[$r] + $lave_quotient;
                            }
                            $age_data[$relative_age_arr[0]] = (int)$age_data[$relative_age_arr[0]] + $lave_remainder;
                        }
                    }
                }
            }
        });
        return $age_data;
    }

    public function getCrmJobs($where, $where_in = [], $order_by = [], $fileds = '', $offset = '', $limit = '')
    {
        if ($fileds) {
            $rst = $this->model->select(DB::raw($fileds))->where($where);
        } else {
            $rst = $this->model->where($where);
        }
        if ($where_in) {
            foreach ($where_in as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        if ($order_by) {
            if (is_array($order_by)) {
                foreach ($order_by as $k => $v) {
                    $rst->orderBy($k, $v);
                }
            } else {
                $rst->orderByRaw($order_by);
            }
        }
        if ($offset !='' && $limit!='') {
            $rst->offset($offset)->limit($limit);
        };
        return $rst->get();
    }
    public function getCrmJobCount($where, $where_in)
    {
        $rst = $this->model->where($where);
        if ($where_in) {
            foreach ($where_in as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        return $rst->count();
    }
    public function getCrmInfo($where)
    {
        return $this->model->with(['company','jobsContact'])->where($where)->first();
    }
    public function getJobNum($where, $company_where)
    {
        $rst = $this->model->where($where)->when($company_where, function ($query) use ($company_where) {
            $query->whereHas('company', function ($query) use ($company_where) {
                $query->where($company_where);
            });
        })->count();
        return $rst;
    }
    public function AdminFind($where,$select){

        return $this->model->where($where)->select($select)->first()->toArray();
    }

    public function getPluck($where,$column)
    {
        return $this->model->where($where)->pluck($column);
    }
}