<?php

namespace App\Repositories;

use App\Models\Resume;
use App\Models\MemberInfo;
use App\Models\Member;
use Prettus\Repository\Eloquent\BaseRepository;
use Prettus\Repository\Criteria\RequestCriteria;
use Illuminate\Support\Facades\DB;

/**
 * Class MemberRepositoryEloquent.
 *
 * @package namespace App\Repositories;
 */
class ResumeRepository extends BaseRepository
{
    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Resume::class;
    }



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

    /**
     * @param $uid
     * @return mixed
     */
    public function getPersonInfo($uid)
    {
        return $this->model->where(['uid'=>$uid,'def'=>1])->first();
    }

    /**
     * 获取所有的简历。
     */
    public function getAllResume($uid)
    {
        return $this->model->with('resumeEntrusts')->where(['uid'=>$uid])->get();
    }

    /**
     * 获取审核通过的简历。
     */
    public function getSuccessResume($uid, $data)
    {
        return $this->model->where(['uid'=>$uid])->whereIn('audit', $data)->get();
    }

    public function getSuccessResumeByid($where, $data)
    {
        return $this->model->where($where)->whereIn('audit', $data)->first();
    }

    public function getSuccessResumeCount($uid, $data)
    {
        return $this->model->where(['uid'=>$uid])->whereIn('audit', $data)->count();
    }

    public function resumeAdd($date)
    {
        return $this->model->create($date);
    }

    public function getResumeCount($uid)
    {
        return $this->model->where('uid', $uid)->count();
    }

    public function getResumeById($id)
    {
        return $this->model->with('memberInfos')->find($id);
    }

    public function getOneResume($where)
    {
        return $this->model->where($where)->first();
    }

    public function updateById($data, $id)
    {
        return $this->update($data, $id);
    }

    public function getArrayById($id)
    {
        return $this->model->find($id)->toArray();
    }

    public function resumeShow($id)
    {
        return $this->model->with('memberInfos')->with('members')->find($id)->toArray();
    }

    public function delResume($id)
    {
        return $this->delete($id);
    }

    public function attentionMe($data)
    {
        return $this->model->where($data)->get();
    }

    public function getResumeMemInfo($id)
    {
        return $this->model->with('memberInfos')->find($id);
    }
    public function getResume($id)
    {
        return $this->model->find($id);
    }
    public function getResumeList($ids)
    {
        return $this->model->whereIn('id', $ids)->get();
    }

    public function findResumeList($uidArr)
    {
        return $this->model->whereIn('uid', $uidArr)->where('def', 1)->orderByRaw("FIELD(uid,".implode(",", $uidArr).")")->paginate(2);
    }

    //根据条件获取简历信息
    public function getResumes($where)
    {
        return $this->model->where($where)->get();
    }
    public function getResumeInfo($where)
    {
        return $this->model->where($where)->orderBy('def','desc')->first();
    }
    public function getResumesWithInfo($ids)
    {
        return $this->model->with('memberInfos')->whereIn('id', $ids)->get();
    }
    public function getResumeBasic($uid, $id)
    {
        $id=intval($id);
        $uid=intval($uid);
        $where['uid']=$uid;
        $where['id']=$id;
        $info = $this->model->where($where)->first();
        if (!$info) {
            return false;
        }
        $info->age=date("Y")-$info->birthdate;
        $info->number="N".str_pad($info->id, 7, "0", STR_PAD_LEFT);
        $info->lastname=$info->fullname;
        return $info;
    }

    public function updateWord($id, $date)
    {
        return $this->model->where('id', $id)->update($date);
    }

    public function updateAllResume($id, $date)
    {
        return $this->model->whereIn('id', $id)->update($date);
    }

    public function getLastResumeCount($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 getNextResumeCount($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 getResumesCount($where)
    {
        return $this->model->where($where)->count();
    }

    public function getAuditCount($where)
    {
        return $this->model->where($where)->count();
    }

    //增加点击量
    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 getMatchResume($where, $whereIn = array(), $where_notIn = array(), $orderby = array())
    {
        $rst = $this->model->where($where);
        if ($whereIn && is_array($whereIn)) {
            foreach ($whereIn as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        if ($where_notIn && is_array($where_notIn)) {
            foreach ($where_notIn as $k => $v) {
                $rst->whereNotIn($k, $v);
            }
        }
        if ($orderby) {
            if (is_array($orderby)) {
                foreach ($orderby as $k => $v) {
                    $rst->orderBy($k, $v);
                }
            } else {
                $rst->orderbyRaw($orderby);
            }
        }
        return $rst->first();
    }

    public function getResumeNumGroup($where, $group_by)
    {
        return $this->model->where($where)->select(DB::raw('count(id),DATE(created_at)'))->groupBy($group_by)->get();
    }
    public function getResumeNum($where, $member_where)
    {
        $rst = $this->model->where($where)->when($member_where, function ($query) use ($member_where) {
            $query->whereHas('members', function ($query) use ($member_where) {
                $query->where($member_where);
            });
        })->count();
        return $rst;
    }

    public function getAvgWageByGroup($where, $member_where, $fields, $group_by, $order_by = '', $limit = '')
    {
        $rst = $this->model->select(DB::raw($fields))->where($where)->when($member_where, function ($query) use ($member_where) {
            $query->whereHas('members', function ($query) use ($member_where) {
                $query->where($member_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 getNumByClassGroup($where, $member_where, $fields, $group_by, $limit = '', $order_by = '')
    {
        $rst = $this->model->withTrashed()->select(DB::raw($fields))->where($where)->when($member_where, function ($query) use ($member_where) {
            $query->whereHas('members', function ($query) use ($member_where) {
                $query->withTrashed()->where($member_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 getResumeNumByClassGroup($where, $member_where, $fields, $group_by, $order_by = '', $limit = '')
    {
        $top_arr = [];
        $second_arr = [];

        $rst = $this->model->select(DB::raw($fields))->where($where)->when($member_where, function ($query) use ($member_where) {
            $query->whereHas('members', function ($query) use ($member_where) {
                $query->where($member_where);
            });
        });
        if ($order_by) {
            $rst->orderByRaw($order_by);
        }
        $res = $rst->chunk(1000, function ($resumes) use (&$top_arr, &$second_arr) {
            foreach ($resumes as $k => $resume) {
                //处理期望职位所属分类
                $id_arr = explode(",", $resume->intention_jobs_id);
                foreach ($id_arr as $k => $v) {
                    $ids = explode('.', $v);
                    if (array_has($top_arr, $ids[0])) {
                        $top_arr[$ids[0]] = $top_arr[$ids[0]]+1;
                    } else {
                        $top_arr[$ids[0]] = 1;
                    }
                    if (array_has($second_arr, $ids[1])) {
                        $second_arr[$ids[1]] = $second_arr[$ids[1]]+1;
                    } else {
                        $second_arr[$ids[1]] = 1;
                    }
                }
            }
        });
        arsort($top_arr);
        arsort($second_arr);
        if ($limit) {
            $top_arr = array_slice($top_arr, 0, $limit, true);
            $second_arr = array_slice($second_arr, 0, $limit, true);
        }
        return ['topClass'=>$top_arr,'secondClass'=>$second_arr];
    }

    public function getResumeNumByEducationGroup($where, $resume_where, $member_where, $resume_fields, $group_by, $order_by)
    {
        $resume_rst = DB::table(Resume::getTableName().' as r')->select(DB::raw($resume_fields))
            ->leftjoin(MemberInfo::getTableName().' as mu', 'mu.uid', '=', 'r.uid')
            ->leftjoin(Member::getTableName().' as m', 'm.id', '=', 'r.uid')
            ->where($resume_where)
            ->where($member_where)
            ->whereRaw($where)
            ->groupBy($group_by)
            ->orderByRaw($order_by)
            ->get();
        return $resume_rst;
    }

    public function getResumeNumsByAgeGroup($where, $resume_where, $member_where, $info_where, $resume_fields, $group_by, $order_by = '')
    {
        $resume_rst = DB::table(Resume::getTableName().' as r') //->select(DB::raw($resume_fields))
                            ->leftjoin(MemberInfo::getTableName().' as mu', 'mu.uid', '=', 'r.uid')
                            ->leftjoin(Member::getTableName().' as m', 'm.id', '=', 'r.uid')
                            ->where($resume_where)
                            ->where($member_where)
                            ->where($info_where)
                            ->whereRaw($where);
        if ($group_by) {
            $resume_rst->groupBy($group_by);
        }
        if ($order_by) {
            $resume_rst->orderByRaw($order_by);
        }
        $rst = $resume_rst->count();
        return $rst;
    }

    public function clearResumeExpires()
    {
        return $this->model->where('expires','>',0)->where('expires','<',time())->get()->toArray();
    }

    public function getCrmResumes($where, $whereIn = [])
    {
        $rst = $this->model->with(['members:id,username,mobile'])->where($where);
        if ($whereIn) {
            foreach ($whereIn as $k => $v) {
                $rst->whereIn($k, $v);
            }
        }
        return $rst->get();
    }

    public function getResumeNumByGroup($resume_where, $member_where, $info_where, $resume_fields, $group_by, $order_by = '')
    {
        $where = 'r.deleted_at is null and mu.deleted_at is null and m.deleted_at is null';
        $resume_rst = DB::table(Resume::getTableName().' as r')->select(DB::raw($resume_fields))
                        ->leftjoin(MemberInfo::getTableName().' as mu', 'mu.uid', '=', 'r.uid')
                        ->leftjoin(Member::getTableName().' as m', 'm.id', '=', 'r.uid')
                        ->where($resume_where)
                        ->where($member_where)
                        ->where($info_where)
                        ->whereRaw($where);
        if ($group_by) {
            $resume_rst->groupBy($group_by);
        }
        if ($order_by) {
            $resume_rst->orderByRaw($order_by);
        }
        $rst = $resume_rst->get();
        return $rst;
    }

}