<?php
namespace app\bsadmin\controller;
use think\facade\Session;
use think\facade\Db;
use think\facade\View;
use think\helper\Str;
use think\exception\ValidateException;
use app\common\validate\Resume as ResumeValidate;
use app\bsadmin\model\Config as ConfigModel;
use app\common\model\Resume as ResumeModel;
use app\common\model\ResumeExamineLog as ResumeExamineLogModel;
use app\common\model\ResumeEmploymentIntention as ResumeEmploymentIntentionModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\ResumeDownloaded as ResumeDownloadedModel;
use app\common\model\ResumeWorks as ResumeWorksModel;
use app\common\model\ResumeConsignment as ResumeConsignmentModel;
use app\common\model\ResumeCertificate as ResumeCertificateModel;
use app\common\model\ResumeEducationalExperience as ResumeEducationalExperienceModel;
use app\common\model\ResumeLanguageAbility as ResumeLanguageAbilityModel;
use app\common\model\ResumeProjectExperience as ResumeProjectExperienceModel;
use app\common\model\ResumeSelfDescription as ResumeSelfDescriptionModel;
use app\common\model\ResumeSpecialtyLabel as ResumeSpecialtyLabelModel;
use app\common\model\ResumeTrainingExperience as ResumeTrainingExperienceModel;
use app\common\model\ResumeWorkExperience as ResumeWorkExperienceModel;
use app\common\model\ResumeRefreshLog as ResumeRefreshLogModel;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserTimer as UserTimerModel;
use app\common\controller\Resume as ResumeController;
use app\common\controller\Jobs as JobsController;
use app\common\model\Feedback as FeedbackModel;
use app\bsadmin\model\Admin as AdminModel;
use app\common\model\PushTask as PushTaskModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
class Resume extends Base
{
    public function index()
    {
    	if(request()->isAjax()){
            $G=request()->get();
            $where=$this->getSearchResumeWhere();
            $DataObj=ResumeModel::alias('resume')->where($where);
            if (!empty($G['jid'])&&$G['jid']) {
                $DataObj->where('resume.id', 'NOTIN', function ($query)use($G) {
                    $query->name('job_fair_resume')->where(['jid'=>$G['jid']])->field('resume_id');
                });
            }
            $Data=$DataObj->join('user m','m.id = resume.uid')
                ->where(['edu.alias'=>'resume/educational_background'])
            	->where(['job_status.alias'=>'resume/job_status'])
            	->join('status_alias edu','edu.value=resume.educational_background')
                ->join('user_info uinfo','uinfo.uid = m.id')
                ->join('status_alias job_status','job_status.value = resume.job_status')
                ->join('api_app app','app.app_id = resume.app_id','LEFT')
                ->field('resume.*,m.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                	$v['nickname']=base64_decode($v['nickname']);
                	$v['headimg']=config('web.imgurl').$v['headimg'];
                    $v['app_name']=$v['app_name']?$v['app_name']:'后台添加';
                    $v['refresh_time']=$v['refresh_time']?date('Y-m-d H:i',$v['refresh_time']):'';
                    $v['friendly_time']=friendly_time($v['refresh_time'],'friendly');
                    $v['log']=ResumeExamineLogModel::where(['resume_id'=>$v->id])->limit(10)->order('id desc')->select();
                    $v->ResumeEmploymentIntention=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$v->id])
                        ->where(['nature_of_work.alias'=>'resume/nature_of_work'])
                        ->join('company_industry industry','industry.id=e.industry_id','LEFT')
                        ->join('jobs_cate jobs_cate1','jobs_cate1.id=e.jobscate1')
                        ->join('jobs_cate jobs_cate2','jobs_cate2.id=e.jobscate2')
                        ->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3')
                        ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work')
                        ->join('area province','province.id = e.job_area1','LEFT')
                        ->join('area city','city.id = e.job_area2','LEFT')
                        ->join('area area','area.id = e.job_area3','LEFT')
                        ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();
                    $v->resume_info=0;
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
    	}else{
            $AdminModel=AdminModel::where(['status'=>1])->field('id,headimg,nickname,adviser_default')->select();
            View::assign('admin',$AdminModel);
    		return View::fetch();
    	}
    }
    public function getSearchResumeWhere()
    {
        $G=request()->get();
        $where=[];
        if ($G['key']) {
            switch($G['search_type']){
                case 'id':
                    $where[]=['resume.id','=',$G['key']];
                    break;
                case 'uid':
                    $where[]=['resume.uid','=',$G['key']];
                    break;
                case 'name':
                    $where[]=['resume.name','like','%'.$G['key'].'%'];
                    break;
                case 'mobile':
                    $where[]=['m.mobile','=',$G['key']];
                    break;
                case 'email':
                    $where[]=['m.email','=',$G['key']];
                    break;
            }
        }
        if (!empty($G['progress'])&&$G['progress'])
            $where[]=['resume.progress','>',$G['progress']];
        if (isset($G['examine'])&&$G['examine']!='all')
            $where[]=['resume.examine','=',$G['examine']];
        if (!empty($G['refresh_time'])&&strtotime($G['refresh_time']))
            $where[]=['resume.refresh_time','>',strtotime($G['refresh_time'].' 00:00:00')];
        return $where;
    }
    public function exportResume()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=$this->getSearchResumeWhere();
            $Field=[
                'resume.*',
                'm.mobile,uinfo.nickname,uinfo.headimg,edu.title as educational_background,app.app_name,job_status.title as job_status',
                'app.app_name',
            ];
            $DataObj=ResumeModel::alias('resume')->where($where);
            if (!empty($G['jid'])&&$G['jid']) {
                $DataObj->where('resume.id', 'NOTIN', function ($query)use($G) {
                    $query->name('job_fair_resume')->where(['jid'=>$G['jid']])->field('resume_id');
                });
            }
            $Data=$DataObj->join('user m','m.id = resume.uid')
                ->where(['edu.alias'=>'resume/educational_background'])
                ->where(['job_status.alias'=>'resume/job_status'])
                ->join('status_alias edu','edu.value=resume.educational_background')
                ->join('user_info uinfo','uinfo.uid = m.id')
                ->join('status_alias job_status','job_status.value = resume.job_status')
                ->join('api_app app','app.app_id = resume.app_id','LEFT')
                ->field(implode(',',$Field))
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['app_name']=$v['app_name']?$v['app_name']:'后台添加';
                    $v['refresh_time']=$v['refresh_time']?date('Y-m-d H:i',$v['refresh_time']):'';
                    $v->employment_intention=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$v->id])
                        ->where(['nature_of_work.alias'=>'resume/nature_of_work'])
                        ->join('company_industry industry','industry.id=e.industry_id','LEFT')
                        ->join('jobs_cate jobs_cate1','jobs_cate1.id=e.jobscate1')
                        ->join('jobs_cate jobs_cate2','jobs_cate2.id=e.jobscate2')
                        ->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3')
                        ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work')
                        ->join('area province','province.id = e.job_area1','LEFT')
                        ->join('area city','city.id = e.job_area2','LEFT')
                        ->join('area area','area.id = e.job_area3','LEFT')
                        ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area2,nature_of_work.title as nature_of_work,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->select();

                    $v->educational_experience=ResumeEducationalExperienceModel::alias('edu')->where(['edu.resume_id'=>$v->id])
                        ->where(['educational_background.alias'=>'resume/educational_background'])
                        ->join('status_alias educational_background','educational_background.value=edu.educational_background')
                        ->withAttr('start_time',function($v,$data){
                            return date('Y-m',$v);
                        })->withAttr('end_time',function($v,$data){
                            return date('Y-m',$v);
                        })->field('edu.school_name,edu.specialities,edu.start_time,edu.end_time,educational_background.title as educational_background')->select();
                    $v->work_experience=ResumeWorkExperienceModel::alias('work')->where(['work.resume_id'=>$v->id])
                        ->join('jobs_cate jobs_cate1','jobs_cate1.id=work.jobscate1')
                        ->join('jobs_cate jobs_cate2','jobs_cate2.id=work.jobscate2')
                        ->join('jobs_cate jobs_cate3','jobs_cate3.id=work.jobscate3')
                        ->withAttr('start_time',function($v,$data){
                            return date('Y-m',$v);
                        })->withAttr('end_time',function($v,$data){
                            return date('Y-m',$v);
                        })->field('work.company_name,work.job_content,work.job_title,work.start_time,work.end_time,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3')->select();
                    $v->training_experience=ResumeTrainingExperienceModel::where(['resume_id'=>$v->id])
                        ->withAttr('start_time',function($v,$data){
                            return date('Y-m',$v);
                        })->withAttr('end_time',function($v,$data){
                            return date('Y-m',$v);
                        })->field('project_name,mechanism,training_content,start_time,end_time')->select();
                    $v->project_experience=ResumeProjectExperienceModel::where(['resume_id'=>$v->id])
                        ->withAttr('start_time',function($v,$data){
                            return date('Y-m',$v);
                        })->withAttr('end_time',function($v,$data){
                            return date('Y-m',$v);
                        })->field('project_name,project_role,project_content,project_link,start_time,end_time')->select();
                    $v->certificate=ResumeCertificateModel::where(['resume_id'=>$v->id])->column('certificate_name');
                    $v->language_ability=ResumeLanguageAbilityModel::where(['resume_id'=>$v->id])->column('language_name');
                    $v->specialty_label=ResumeSpecialtyLabelModel::where(['resume_id'=>$v->id])->column('specialty_label');
                    return $v;
                });
            if ($Data->items()) {
                $title = [
                    ['title'=>'ID','key'=>'id'],
                    ['title'=>'UID','key'=>'uid'],
                    ['title'=>'姓名','key'=>'name'],
                    ['title'=>'手机号','key'=>'mobile'],
                    ['title'=>'求职状态','key'=>'job_status'],
                    ['title'=>'求职意向','key'=>'employment_intention'],
                    ['title'=>'审核状态','key'=>'examine'],
                    ['title'=>'展示状态','key'=>'privacy'],
                    ['title'=>'教育经历','key'=>'educational_experience'],
                    ['title'=>'工作经历','key'=>'work_experience'],
                    ['title'=>'培训经历','key'=>'training_experience'],
                    ['title'=>'项目经历','key'=>'project_experience'],
                    ['title'=>'获得证书','key'=>'certificate'],
                    ['title'=>'语言能力','key'=>'language_ability'],
                    ['title'=>'特长标签','key'=>'specialty_label'],
                    ['title'=>'年龄','key'=>'age'],
                    ['title'=>'性别','key'=>'sex'],
                    ['title'=>'学历','key'=>'educational_background'],
                    ['title'=>'经验(年)','key'=>'work_experience_time'],
                    ['title'=>'来源','key'=>'app_name'],
                    ['title'=>'创建时间','key'=>'create_time'],
                    ['title'=>'刷新时间','key'=>'refresh_time']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();
             
                //表头
                //设置单元格内容
                $titCol = 'A';
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '1', $v['title']);
                    $titCol++;
                }
                $row=2;
                foreach($Data->items() as $item){
                    $dataCol='A';
                    foreach ($title as $key => $v) {
                        switch ($v['key']) {
                            case 'employment_intention':
                                $employment_intention=[];
                                foreach ($item->employment_intention as $obj) {
                                    $salary='面议';
                                    if($obj->salary_min>0)
                                        $salary=$obj->salary_min.'-'.$obj->salary_max;
                                    $employment_intention[]=$obj->jobs_cate3.'·'.($obj->industry?$obj->industry:'行业不限').'·'.($obj->area_city?$obj->area_city.$obj->area_area:'地区不限').'·'.$salary;
                                }
                                if (!empty($employment_intention))
                                $sheet->setCellValue($dataCol.$row, implode("\n",$employment_intention));
                                break;
                            case 'educational_experience':
                                $educational_experience=[];
                                foreach ($item->educational_experience as $obj) {
                                    $educational_experience[]=$obj->educational_background.'·'.$obj->school_name.'·'.$obj->specialities.'·'.$obj->start_time.'~'.$obj->end_time;
                                }
                                if (!empty($educational_experience))
                                $sheet->setCellValue($dataCol.$row, implode("\n",$educational_experience));
                                break;
                            case 'work_experience':
                                $work_experience=[];
                                foreach ($item->work_experience as $obj) {
                                    $work_experience[]=$obj->company_name.'·'.$obj->jobs_cate3.'·'.$obj->job_title.'·'.$obj->start_time.'~'.$obj->end_time;
                                }
                                if (!empty($work_experience))
                                $sheet->setCellValue($dataCol.$row, implode("\n",$work_experience));
                                break;
                            case 'training_experience':
                                $training_experience=[];
                                foreach ($item->training_experience as $obj) {
                                    $training_experience[]=$obj->mechanism.'·'.$obj->project_name.'·'.$obj->start_time.'~'.$obj->end_time;
                                }
                                if (!empty($training_experience))
                                $sheet->setCellValue($dataCol.$row, implode("\n",$training_experience));
                                break;
                            case 'project_experience':
                                $project_experience=[];
                                foreach ($item->project_experience as $obj) {
                                    $project_experience[]=$obj->project_name.'·'.$obj->project_role.'·'.$obj->project_link.'·'.$obj->start_time.'~'.$obj->end_time;
                                }
                                if (!empty($project_experience))
                                $sheet->setCellValue($dataCol.$row, implode("\n",$project_experience));
                                break;
                            case 'certificate':
                                if ($item->certificate)
                                $sheet->setCellValue($dataCol.$row, implode('·',$item->certificate));
                                break;
                            case 'language_ability':
                                if ($item->language_ability)
                                $sheet->setCellValue($dataCol.$row, implode('·',$item->language_ability));
                                break;
                            case 'specialty_label':
                                if ($item->specialty_label)
                                $sheet->setCellValue($dataCol.$row, implode('·',$item->specialty_label));
                                break;
                            case 'examine':
                                switch ($item->examine) {
                                    case 0:
                                        $sheet->setCellValue($dataCol.$row, '未审核');
                                        break;
                                    case 1:
                                        $sheet->setCellValue($dataCol.$row, '已审核');
                                        break;
                                    case 2:
                                        $sheet->setCellValue($dataCol.$row, '未通过');
                                        break;
                                }
                                break;
                            case 'privacy':
                                switch ($item->privacy) {
                                    case 0:
                                        $sheet->setCellValue($dataCol.$row, '未展示');
                                        break;
                                    case 1:
                                        $sheet->setCellValue($dataCol.$row, '展示中');
                                        break;
                                }
                                break;
                            case 'sex':
                                switch ($item->sex) {
                                    case 1:
                                        $sheet->setCellValue($dataCol.$row, '男');
                                        break;
                                    case 2:
                                        $sheet->setCellValue($dataCol.$row, '女');
                                        break;
                                }
                                break;
                            case 'work_experience_time':
                                $sheet->setCellValue($dataCol.$row, date('Y')-date('Y',$item->work_experience_time));
                                break;
                            case 'age':
                                $sheet->setCellValue($dataCol.$row, date('Y')-date('Y',$item->age));
                                break;
                            default:
                                $sheet->setCellValue($dataCol.$row, $item[$v['key']]);
                                break;
                        }
                        $dataCol++;
                    }
                    $row++;
                }
                $filename='output/resume/'.Session::get('AdminUser.uid').'_'.date('YmdHis').Str::random(4).'.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~',0,['url'=>'/'.$filename]);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }
    }
    public function getFind($id)
    {
        $D=[
            'is_admin'    =>  1
        ];
        $Find=ResumeController::getResumeInfo($id,$D);
        if ($Find) {
            /*记录访客*/
            View::assign('Find',$Find);
            View::assign('webtitle',$Find['name'].'的简历');
        }else{
            return redirect('/system/maintenance?msg=不存在该简历');
        }
        return View::fetch();
    }
    public function setResumeExamine($id,$status,$msg='')
    {
        $ResumeModel=ResumeModel::where(['id'=>$id])->find();
        $G=request()->get();
        if ($status==1) {
            $ResumeModel->examine=1;
            $ResumeExamineLogModel=new ResumeExamineLogModel;
            $ResumeExamineLogModel->resume_id=$ResumeModel->id;
            $ResumeExamineLogModel->status=1;
            $ResumeExamineLogModel->msg='审核通过';
            $ResumeExamineLogModel->admin_uid=Session::get('AdminUser.uid');
            $ResumeExamineLogModel->ip=request()->ip();
            $PushTaskModel=null;
            if(!empty($G['notice'])){
                $PushTaskModel=new PushTaskModel;
                $PushTaskModel->event       =   'ResumeExamine';
                $PushTaskModel->uid         =   $ResumeModel->uid;
                $PushData=$ResumeModel->toArray();
                $PushData['hi_text']='恭喜您';
                $PushData['status']='已通过';
                $PushData['msg']='通过';
                $PushData['time']=date('Y-m-d H:i:s');
                $PushTaskModel->data        =   json_encode($PushData,JSON_UNESCAPED_UNICODE);
            }
            // 启动事务
            Db::startTrans();
            try {
                $ResumeModel->save();
                if($PushTaskModel)$PushTaskModel->save();
                $ResumeExamineLogModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            $ResumeModel->examine=2;
            $ResumeExamineLogModel=new ResumeExamineLogModel;
            $ResumeExamineLogModel->resume_id=$ResumeModel->id;
            $ResumeExamineLogModel->status=2;
            $ResumeExamineLogModel->msg=$msg;
            $ResumeExamineLogModel->admin_uid=Session::get('AdminUser.uid');
            $ResumeExamineLogModel->ip=request()->ip();
            $PushTaskModel=null;
            if(!empty($G['notice'])){
                $PushTaskModel=new PushTaskModel;
                $PushTaskModel->event       =   'ResumeExamine';
                $PushTaskModel->uid         =   $ResumeModel->uid;
                $PushData=$ResumeModel->toArray();
                $PushData['hi_text']='很遗憾';
                $PushData['status']='未通过';
                $PushData['msg']=$msg;
                $PushData['time']=date('Y-m-d H:i:s');
                $PushTaskModel->data        =   json_encode($PushData,JSON_UNESCAPED_UNICODE);
            }
            // 启动事务
            Db::startTrans();
            try {
                $ResumeModel->save();
                if($PushTaskModel)$PushTaskModel->save();
                $ResumeExamineLogModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }
    }
    /**
     * 获取简历信息
     */
    public function getResumeInfo($id)
    {
        $Find=ResumeController::getResumeInfo($id,['is_admin'=>1]);
        if ($Find) {
            return $this->ajaxReturn('',0,$Find);
        }else{
            return $this->ajaxReturn('无此企业数据',-100);
        }
    }
    public function refreshResume($id)
    {
        $ResumeModel=ResumeModel::where(['id'=>$id])->find();
        $ResumeModel->refresh_time=time();
        if($ResumeModel->save()){
            return $this->ajaxReturn('已刷新',0,['refresh_time'=>date('Y-m-d H:i',$ResumeModel->refresh_time)]);
        }else{
            return $this->ajaxReturn('刷新失败，请重试',-100);
        }
    }
    public function editResume($id)
    {
        if (request()->isAjax()) {
            $D=request()->post();
            $D['uid']=$id;
            /*
            *  调用公共保存简历方法
            *  app\common\controller\Resume
            */
            return ResumeController::saveResume($D);
        }else{
            View::assign('Find',ResumeController::getResumeInfoAll($id));
            return View::fetch('add_resume');
        }
    }
    /**
     * 删除简历经历
     */
    public function delExperience($type,$id,$uid,$resume_id)
    {
        if (request()->isAjax() && request()->isGet()) {
            $D=[
                'id'        =>  $id,
                'type'      =>  $type,
                'uid'       =>  $uid,
                'resume_id' =>  $resume_id
            ];
            /*
            *  调用公共删除简历经历方法
            *  app\common\controller\Resume
            */
            return ResumeController::delExperience($D);
        }
    }
    public function addResume()
    {
        if (request()->isAjax()) {
            $D=request()->post();
            /**
             * 简历基本信息验证
             */
            try {
                validate(ResumeValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(),-100);
            }
            $required_field=config('xy_resume.required_field');
            if (in_array('self_description',$required_field)&&empty($D['self_description']))
                return $this->ajaxReturn('自我描述不能为空',-100);
            if (in_array('educational_experience',$required_field)&&empty($D['educational_experience']))
                return $this->ajaxReturn('教育经历不能为空',-100);
            if (in_array('work_experience',$required_field)&&empty($D['work_experience']))
                return $this->ajaxReturn('工作经历不能为空',-100);
            if (in_array('training_experience',$required_field)&&empty($D['training_experience']))
                return $this->ajaxReturn('培训经历不能为空',-100);
            if (in_array('project_experience',$required_field)&&empty($D['project_experience']))
                return $this->ajaxReturn('项目经历不能为空',-100);
            if (in_array('certificate',$required_field)&&empty($D['certificate']))
                return $this->ajaxReturn('证书不能为空',-100);
            if (in_array('language_ability',$required_field)&&empty($D['language_ability']))
                return $this->ajaxReturn('语言能力不能为空',-100);
            if (in_array('specialty_label',$required_field)&&empty($D['specialty_label']))
                return $this->ajaxReturn('特长不能为空',-100);
            /**
             * 用户
             */
            $UserModel=UserModel::where(['mobile'=>$D['mobile']])->find();
            $UserInfoModel=null;
            $UserTimerModel=null;
            if($UserModel){
                if(ResumeModel::where(['uid'=>$UserModel->id])->count())
                    return $this->ajaxReturn('该手机号已创建简历',-100);
            }else{
                $passHash=Str::random(4);
                $UserModel=new UserModel;
                $UserModel->mobile=$D['mobile'];
                $UserModel->email=$D['email'];
                $UserModel->password_hash=$passHash;
                if($D['password']){
                    $UserModel->password=UserModel::getPassword($passHash,$D['password']);
                }else{
                    $UserModel->password=UserModel::getPassword($passHash,$D['mobile']);
                }
                /**
                 * 用户信息
                 */
                $UserInfoModel=new UserInfoModel;
                $UserInfoModel->nickname=base64_encode('XY_'.substr_replace($D['mobile'],'****',3,4));
                $UserInfoModel->headimg=config('xy_default_avatar.user');
                $UserInfoModel->role_type=0;
                $UserTimerModel=new UserTimerModel;
                $UserTimerModel->online_time=time();
                $UserTimerModel->online_ip=request()->ip();
                $UserTimerModel->online_devices=substr(request()->header('user-agent'),0,200);
                $UserTimerModel->login_time=time();
                $UserTimerModel->login_ip=request()->ip();
                $UserTimerModel->login_devices=substr(request()->header('user-agent'),0,200);
                $UserTimerModel->register_time=time();
                $UserTimerModel->register_ip=request()->ip();
                $UserTimerModel->register_devices=substr(request()->header('user-agent'),0,200);
            }
            $ResumeModel=new ResumeModel;
            $ResumeModel->refresh_time          =   time();
            $ResumeModel->name                  =   $D['name'];
            $ResumeModel->sex                   =   $D['sex'];
            $ResumeModel->headimg_status        =   $D['headimg_status'];
            $ResumeModel->age                   =   round($D['age']/1000);
            $ResumeModel->educational_background=   $D['educational_background'];
            $ResumeModel->work_experience_time  =   round($D['work_experience_time']/1000);
            if (!empty($D['specialities']))
                $ResumeModel->specialities          =   $D['specialities'];
            $ResumeModel->residence             =   $D['residence'];
            $ResumeModel->native_place          =   $D['native_place'];
            $ResumeModel->is_marry              =   $D['is_marry'];
            $ResumeModel->contact_qq            =   $D['contact_qq'];
            $ResumeModel->contact_wechat        =   $D['contact_wechat'];
            $ResumeModel->job_status            =   empty($D['job_status'])?4:$D['job_status'];
            if (config('xy_resume.edit_resume_view_status'))
                $ResumeModel->examine=0;

            if ($ResumeModel) {
                $ResumeSelfDescriptionModel=ResumeSelfDescriptionModel::where(['resume_id'=>$ResumeModel->id])->find();
                if (!$ResumeSelfDescriptionModel)
                    $ResumeSelfDescriptionModel=new ResumeSelfDescriptionModel;
            }else{
                $ResumeSelfDescriptionModel=new ResumeSelfDescriptionModel;
            }
            $ResumeSelfDescriptionModel->self_description=$D['self_description'];

            $ResumeEmploymentIntentionModel=new ResumeEmploymentIntentionModel;
            $ResumeEmploymentIntentionList=[];
            if (!empty($D['employment_intention'])) {
                $ResumeEmploymentIntentionDefault=0;
                foreach ($D['employment_intention'] as $k => $v) {
                    if (count($ResumeEmploymentIntentionList)>=3)
                        break;
                    $ResumeEmploymentIntentionList[$k]=[
                        'nature_of_work'            =>  $v['nature_of_work'],
                        'industry_id'               =>  $v['industry_id'],
                        'jobscate1'                 =>  $v['jobscate'][0],
                        'jobscate2'                 =>  $v['jobscate'][1],
                        'jobscate3'                 =>  $v['jobscate'][2],
                        'expected_salary'           =>  $v['expected_salary'][0],
                        'expected_salary'           =>  $v['expected_salary'][1],
                        'default'                   =>  0,
                    ];
                    if (!empty($v['job_area'])&&count($v['job_area'])==3) {
                        $ResumeEmploymentIntentionList[$k]['job_area1']=$v['job_area'][0];
                        $ResumeEmploymentIntentionList[$k]['job_area2']=$v['job_area'][1];
                        $ResumeEmploymentIntentionList[$k]['job_area3']=$v['job_area'][2];
                    }
                    if ($v['id'])
                        $ResumeEmploymentIntentionList[$k]['id']=$v['id'];
                    if(!empty($v['default'])&&$v['default']&&!$ResumeEmploymentIntentionDefault){
                        $ResumeEmploymentIntentionList[$k]['default']=1;
                        $ResumeEmploymentIntentionDefault=1;
                    }
                }
            }
            if (empty($ResumeEmploymentIntentionList))
                return $this->ajaxReturn('求职意向不能为空',-100);
            /*教育经历*/
            $ResumeEducationalExperienceModel=new ResumeEducationalExperienceModel;
            $EducationalExperienceList=[];
            if (!empty($D['educational_experience'])) {
                foreach ($D['educational_experience'] as $k => $v) {
                    $EducationalExperienceList[$k]=[
                        'school_name'               =>  $v['school_name'],
                        'specialities'              =>  $v['specialities'],
                        'educational_background'    =>  $v['educational_background'],
                        'start_time'                =>  round($v['start_time']/1000),
                        'end_time'                  =>  round($v['end_time']/1000)
                    ];
                    if ($v['id'])
                        $EducationalExperienceList[$k]['id']=$v['id'];
                }
            }
            /*工作经历*/
            $ResumeWorkExperienceModel=new ResumeWorkExperienceModel;
            $ResumeWorkExperienceList=[];
            if (!empty($D['work_experience'])) {
                foreach ($D['work_experience'] as $k => $v) {
                    $ResumeWorkExperienceList[$k]=[
                        'company_name'              =>  $v['company_name'],
                        'jobscate1'                 =>  $v['jobscate'][0],
                        'jobscate2'                 =>  $v['jobscate'][1],
                        'jobscate3'                 =>  $v['jobscate'][2],
                        'job_content'               =>  $v['job_content'],
                        'job_title'                 =>  $v['job_title'],
                        'start_time'                =>  round($v['start_time']/1000),
                        'end_time'                  =>  round($v['end_time']/1000)
                    ];
                    if ($v['id'])
                        $ResumeWorkExperienceList[$k]['id']=$v['id'];
                }
            }
            /*培训经历*/
            $ResumeTrainingExperienceModel=new ResumeTrainingExperienceModel;
            $ResumeTrainingExperienceList=[];
            if (!empty($D['training_experience'])) {
                foreach ($D['training_experience'] as $k => $v) {
                    $ResumeTrainingExperienceList[$k]=[
                        'project_name'              =>  $v['project_name'],
                        'mechanism'                 =>  $v['mechanism'],
                        'training_content'          =>  $v['training_content'],
                        'start_time'                =>  round($v['start_time']/1000),
                        'end_time'                  =>  round($v['end_time']/1000)
                    ];
                    if ($v['id'])
                        $ResumeTrainingExperienceList[$k]['id']=$v['id'];
                }
            }
            $ResumeProjectExperienceModel=new ResumeProjectExperienceModel;
            $ResumeProjectExperienceList=[];
            if (!empty($D['project_experience'])) {
                foreach ($D['project_experience'] as $k => $v) {
                    $ResumeProjectExperienceList[$k]=[
                        'project_name'              =>  $v['project_name'],
                        'project_role'              =>  $v['project_role'],
                        'project_content'           =>  $v['project_content'],
                        'project_link'              =>  $v['project_link'],
                        'start_time'                =>  round($v['start_time']/1000),
                        'end_time'                  =>  round($v['end_time']/1000)
                    ];
                    if ($v['id'])
                        $ResumeProjectExperienceList[$k]['id']=$v['id'];
                }
            }
            /*获得证书*/
            $ResumeCertificateModel=new ResumeCertificateModel;
            $CertificateList=[];
            if (!empty($D['certificate'])) {
                foreach ($D['certificate'] as $k => $v) {
                    if (!$v['id'])
                        $CertificateList[]['certificate_name']=$v['certificate_name'];
                }
            }
            /*语言能力*/
            $ResumeLanguageAbilityModel=new ResumeLanguageAbilityModel;
            $LanguageAbilityList=[];
            if (!empty($D['language_ability'])) {
                foreach ($D['language_ability'] as $k => $v) {
                    if (!$v['id'])
                        $LanguageAbilityList[]['language_name']=$v['language_name'];
                }
            }
            /*特长*/
            $ResumeSpecialtyLabelModel=new ResumeSpecialtyLabelModel;
            $SpecialtyLabelList=[];
            if (!empty($D['specialty_label'])) {
                foreach ($D['specialty_label'] as $k => $v) {
                    if (!$v['id'])
                        $SpecialtyLabelList[]['specialty_label']=$v['specialty_label'];
                }
            }
            $PushTaskModel=new PushTaskModel;
            $PushTaskModel->event       =   'SystemWarning';
            // 启动事务
            Db::startTrans();
            try {
                if($UserInfoModel)$UserModel->save();
                $UserInfoModel->uid=$UserModel->id;
                $UserTimerModel->uid=$UserModel->id;
                if($UserInfoModel)$UserInfoModel->save();
                if($UserTimerModel)$UserTimerModel->save();
                $ResumeModel->uid=$UserModel->id;
                $ResumeModel->save();
                $ResumeSelfDescriptionModel->resume_id=$ResumeModel->id;
                $ResumeSelfDescriptionModel->save();
                if (!empty($ResumeEmploymentIntentionList)) {
                    array_walk($ResumeEmploymentIntentionList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeEmploymentIntentionModel->saveAll($ResumeEmploymentIntentionList);
                }
                if (!empty($EducationalExperienceList)) {
                    array_walk($EducationalExperienceList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeEducationalExperienceModel->saveAll($EducationalExperienceList);
                }
                if (!empty($ResumeWorkExperienceList)) {
                    array_walk($ResumeWorkExperienceList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeWorkExperienceModel->saveAll($ResumeWorkExperienceList);
                }
                if (!empty($ResumeTrainingExperienceList)) {
                    array_walk($ResumeTrainingExperienceList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeTrainingExperienceModel->saveAll($ResumeTrainingExperienceList);
                }
                if (!empty($ResumeProjectExperienceList)) {
                    array_walk($ResumeProjectExperienceList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeProjectExperienceModel->saveAll($ResumeProjectExperienceList);
                }
                if (!empty($CertificateList)) {
                    array_walk($CertificateList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeCertificateModel->saveAll($CertificateList);
                }
                if (!empty($LanguageAbilityList)) {
                    array_walk($LanguageAbilityList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeLanguageAbilityModel->saveAll($LanguageAbilityList);
                }
                if (!empty($SpecialtyLabelList)) {
                    array_walk($SpecialtyLabelList,function(&$v,$k)use($ResumeModel){
                        $v['resume_id']=$ResumeModel->id;
                        krsort($v);
                    });
                    $ResumeSpecialtyLabelModel->saveAll($SpecialtyLabelList);
                }
                $PushData=[
                    'tpl'       =>'resume_examine',
                    'level'     =>'审核简历',
                    'range'     =>'后台',
                    'time'      =>date('Y-m-d H:i:s'),
                    'msg'       =>'审核简历ID:'.$ResumeModel->id
                ];
                $PushTaskModel->data        =   json_encode($PushData,JSON_UNESCAPED_UNICODE);
                $PushTaskModel->save();
                // 提交事务
                Db::commit();
                ResumeController::calculationResumeProgress($ResumeModel->id);
                ResumeController::delResumeFile($ResumeModel->id);
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function downloadResumeLog()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'company_id':
                        $where[]=['d.company_id','=',$G['key']];
                        break;
                    case 'resume_id':
                        $where[]=['d.resume_id','=',$G['key']];
                        break;
                    case 'company_name':
                        $where[]=['company.title','like','%'.$G['key'].'%'];
                        break;
                }
            }
            $Data=ResumeDownloadedModel::alias('d')
                ->where($where)
                ->where(['edu.alias'=>'resume/educational_background'])
                ->join('company company','company.id=d.company_id')
                ->join('resume resume','resume.id=d.resume_id')
                ->join('status_alias edu','edu.value=resume.educational_background')
                ->order('d.id desc')
                ->field('d.*,resume.name,resume.sex,resume.age,resume.work_experience_time,edu.title as educational_background,company.title as company_name,company.stitle as scompany_name')->paginate($G['pageSize'])
                ->each(function($item, $key){
                    return $item;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function works()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'resume_id':
                        $where[]=['w.resume_id','=',$G['key']];
                        break;
                }
            }
            if ($G['status']!='all') {
                $where[]=['w.status','=',$G['status']];
            }
            $Data=ResumeWorksModel::alias('w')->where($where)
                ->join('resume resume','resume.id = w.resume_id')
                ->field('w.*,resume.name')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['url']=config('web.imgurl').$v['path'];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function setResumeWorksStatus($id,$status)
    {
        $ResumeWorksModel=ResumeWorksModel::where(['id'=>$id])->find();
        $ResumeWorksModel->status=$status;
        if ($ResumeWorksModel->save()) {
            return $this->ajaxReturn('已保存',0,['update_time'=>date('Y-m-d H:i:s')]);
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function setAdviser($id,$adviser_id)
    {
        $ResumeModel=ResumeModel::where(['id'=>$id])->find();
        $ResumeModel->adviser_id=$adviser_id;
        if ($ResumeModel->save()) {
            return $this->ajaxReturn('已设置');
        }else{
            return $this->ajaxReturn('设置失败，请重试',-100);
        }
    }
    public function setting()
    {
        $Data=ConfigModel::getList([['ctype','in',['xy_resume','xy_company','xy_default_avatar']]]);
        View::assign('Data',$Data);
        View::assign('ctype','xy_resume');
        return View::fetch('setting/resume');
    }
    public function consignment()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'resume_id':
                        $where[]=['rc.resume_id','=',$G['key']];
                        break;
                    case 'uid':
                        $where[]=['resume.uid','=',$G['key']];
                        break;
                    case 'name':
                        $where[]=['resume.name','like','%'.$G['key'].'%'];
                        break;
                }
            }
            $Data=ResumeConsignmentModel::alias('rc')->where($where)
                ->where(['edu.alias'=>'resume/educational_background'])
                ->join('resume resume','resume.id=rc.resume_id')
                ->join('user m','m.id = resume.uid')
                ->join('status_alias edu','edu.value=resume.educational_background')
                ->join('user_info uinfo','uinfo.uid = m.id')
                ->field('rc.*,resume.name,resume.age,resume.sex,resume.work_experience_time,uinfo.nickname,uinfo.headimg,edu.title as educational_background')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['nickname']=base64_decode($v['nickname']);
                    $v['headimg']=config('web.imgurl').$v['headimg'];
                    $v['cancel_time']=$v['cancel_time']?date('Y-m-d H:i:s',$v['cancel_time']):'';
                    $v['start_time']=$v['start_time']?date('Y-m-d',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d',$v['end_time']):'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function cancelConsignment($id)
    {
        $ResumeConsignmentModel=ResumeConsignmentModel::where(['id'=>$id])->find();
        $ResumeConsignmentModel->status=0;
        $ResumeConsignmentModel->cancel_time=time();
        if ($ResumeConsignmentModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function matching($resume_id)
    {
        if (request()->isAjax() && request()->isGet()) {
            $G=request()->get();
            $Resume=ResumeModel::where(['id'=>$resume_id])->field('id,uid')->find();
            $G['uid']=$Resume->uid;
            $G['resume_id']=$resume_id;
            $Data=JobsController::getJobsList($G);
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            $Find=ResumeController::getResumeInfo($resume_id,['is_admin'=>1]);
            $ResumeEmploymentIntention=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$resume_id,'e.default'=>1])
                ->where(['nature_of_work.alias'=>'resume/nature_of_work'])
                ->join('company_industry industry','industry.id=e.industry_id','LEFT')
                ->join('jobs_cate jobs_cate1','jobs_cate1.id=e.jobscate1')
                ->join('jobs_cate jobs_cate2','jobs_cate2.id=e.jobscate2')
                ->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3')
                ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work')
                ->join('area province','province.id = e.job_area1','LEFT')
                ->join('area city','city.id = e.job_area2','LEFT')
                ->join('area area','area.id = e.job_area3','LEFT')
                ->field('e.salary_min,e.salary_max,e.industry_id,e.job_area1,e.job_area2,e.job_area3,e.jobscate3,e.nature_of_work,nature_of_work.title as nature_of_work_title,industry.title as industry,jobs_cate1.title as jobs_cate1,jobs_cate2.title as jobs_cate2,jobs_cate3.title as jobs_cate3,province.title as area_province,city.title as area_city,area.title as area_area')->find();
            View::assign('Resume',$Find);
            View::assign('ResumeEmploymentIntention',$ResumeEmploymentIntention);
            return View::fetch();
        }
    }
    /**
     * 投递简历
     */
    public function deliveryResume($resume_id,$id)
    {
        if (request()->isAjax() && request()->isGet()) {
            $Resume=ResumeModel::where(['id'=>$resume_id])->field('id,uid')->find();
            $G=request()->get();
            $D=[
                'id'        =>  $id,
                'confirm'   =>  empty($G['confirm'])?0:$G['confirm'],
                'uid'       =>  $Resume->uid
            ];
            /*
            *  调用公共投递简历方法
            *  app\common\controller\Resume
            */
            return ResumeController::deliveryResume($D,1);
        }
    }
    public function resume_complaints()
    {
        View::assign('type',6);
        return View::fetch('feedback/index');
    }
}
