<?php
namespace app\common\controller;
use think\facade\View;
use think\facade\Session;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;
use helper\Time;
use app\common\variable\MsgCode;
use think\exception\ValidateException;
use app\common\validate\Resume as ResumeValidate;
use app\common\validate\InviteAninterview as InviteAninterviewValidate;
use app\common\model\Resume as ResumeModel;
use app\common\model\ResumeCertificate as ResumeCertificateModel;
use app\common\model\ResumeEducationalExperience as ResumeEducationalExperienceModel;
use app\common\model\ResumeEmploymentIntention as ResumeEmploymentIntentionModel;
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\Jobs as JobsModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\InviteAninterview as InviteAninterviewModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\ResumeDownloaded as ResumeDownloadedModel;
use app\common\model\ResumeCollection as ResumeCollectionModel;
use app\common\model\ResumeBrowse as ResumeBrowseModel;
use app\common\model\CompanyBrowse as CompanyBrowseModel;
use app\common\model\ResumeWorks as ResumeWorksModel;
use app\common\model\ResumeConsignment as ResumeConsignmentModel;
use app\common\model\Company as CompanyModel;
use app\common\model\VipRuleValue as VipRuleValueModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\UserVipRuleLog as UserVipRuleLogModel;
use app\common\model\JobFair as JobFairModel;
use app\common\model\JobFairResume as JobFairResumeModel;
use app\common\controller\JobFair as JobFairController;
use app\common\model\PushTask as PushTaskModel;
use PhpOffice\PhpWord\TemplateProcessor;
use PhpOffice\PhpWord\Shared\Converter;
use helper\Wechat;
class Resume extends Base
{
    /**
     * 创建或完善简历
     */
    public static function saveResume($D)
    {
        /**
         * 简历基本信息验证
         */
        try {
            validate(ResumeValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        if (empty($D['uid']))
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        $uid=$D['uid'];
        if (!$uid)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        $required_field=config('xy_resume.required_field');
        if (in_array('self_description',$required_field)&&empty($D['self_description']))
            return parent::ajaxReturn('自我描述不能为空',MsgCode::$error);
        if (in_array('educational_experience',$required_field)&&empty($D['educational_experience']))
            return parent::ajaxReturn('教育经历不能为空',MsgCode::$error);
        if (in_array('work_experience',$required_field)&&empty($D['work_experience']))
            return parent::ajaxReturn('工作经历不能为空',MsgCode::$error);
        if (in_array('training_experience',$required_field)&&empty($D['training_experience']))
            return parent::ajaxReturn('培训经历不能为空',MsgCode::$error);
        if (in_array('project_experience',$required_field)&&empty($D['project_experience']))
            return parent::ajaxReturn('项目经历不能为空',MsgCode::$error);
        if (in_array('certificate',$required_field)&&empty($D['certificate']))
            return parent::ajaxReturn('证书不能为空',MsgCode::$error);
        if (in_array('language_ability',$required_field)&&empty($D['language_ability']))
            return parent::ajaxReturn('语言能力不能为空',MsgCode::$error);
        if (in_array('specialty_label',$required_field)&&empty($D['specialty_label']))
            return parent::ajaxReturn('特长不能为空',MsgCode::$error);

        $ResumeModel=ResumeModel::where(['uid'=>$uid])->find();
        if (!$ResumeModel){
            $ResumeModel=new ResumeModel;
            $ResumeModel->app_id            =   $D['app_id'];
            $ResumeModel->refresh_time      =   time();
        }
        $ResumeModel->uid                   =   $uid;
        $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'];
        $ResumeModel->political_affiliation =   empty($D['political_affiliation'])?0:$D['political_affiliation'];
        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=htmltostring($D['self_description']);

        $ResumeEmploymentIntentionModel=new ResumeEmploymentIntentionModel;
        $ResumeEmploymentIntentionList=[];
        $ResumeEmploymentIntentionDefault=0;
        if (!empty($D['employment_intention'])) {
            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],
                    'salary_min'                =>  $v['expected_salary'][0],
                    'salary_max'                =>  $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 parent::ajaxReturn('求职意向不能为空',MsgCode::$error);
        if(!$ResumeEmploymentIntentionDefault)
            $ResumeEmploymentIntentionList[0]['default']=1;
        /*教育经历*/
        $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 {
            $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();
            self::calculationResumeProgress($ResumeModel->id);
            Cache::set('updateUser:'.$ResumeModel->uid,true);
            self::delResumeFile($ResumeModel->id);
            return parent::ajaxReturn('保存成功',MsgCode::$success,self::getResumeInfoAll($uid));
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }
    }
    public static function calculationResumeProgress($resume_id)
    {
        $progress=0;
        $ResumeModel=ResumeModel::where(['id'=>$resume_id])->find();
        if ($ResumeModel) {
            $progressData=[
                'progress_info'=>intval(config('xy_resume.progress_info')),
                'employment_intention'=>intval(config('xy_resume.progress_employment_intention')),
                'self_description'=>intval(config('xy_resume.progress_self_description')),
                'educational_experience'=>intval(config('xy_resume.progress_educational_experience')),
                'work_experience'=>intval(config('xy_resume.progress_work_experience')),
                'project_experience'=>intval(config('xy_resume.progress_project_experience')),
                'training_experience'=>intval(config('xy_resume.progress_training_experience')),
                'certificate'=>intval(config('xy_resume.progress_certificate')),
                'language_ability'=>intval(config('xy_resume.progress_language_ability')),
                'specialty_label'=>intval(config('xy_resume.progress_specialty_label')),
            ];
            $progress=$progressData['progress_info']?$progressData['progress_info']:0;
            if ($progressData['employment_intention']) {
                $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeEmploymentIntentionModel)
                    $progress+=$progressData['employment_intention'];
            }
            if ($progressData['self_description']) {
                $ResumeSelfDescriptionModel=ResumeSelfDescriptionModel::where(['resume_id'=>$resume_id])->find();
                if ($ResumeSelfDescriptionModel&&$ResumeSelfDescriptionModel->self_description)
                    $progress+=$progressData['self_description'];
            }
            if($progressData['educational_experience']){
                $ResumeEducationalExperienceModel=ResumeEducationalExperienceModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeEducationalExperienceModel)
                    $progress+=$progressData['educational_experience'];
            }
            if($progressData['work_experience']){
                $ResumeWorkExperienceModel=ResumeWorkExperienceModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeWorkExperienceModel)
                    $progress+=$progressData['work_experience'];
            }
            if($progressData['project_experience']){
                $ResumeProjectExperienceModel=ResumeProjectExperienceModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeProjectExperienceModel)
                    $progress+=$progressData['project_experience'];
            }
            if($progressData['training_experience']){
                $ResumeTrainingExperienceModel=ResumeTrainingExperienceModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeTrainingExperienceModel)
                    $progress+=$progressData['training_experience'];
            }
            if($progressData['certificate']){
                $ResumeCertificateModel=ResumeCertificateModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeCertificateModel)
                    $progress+=$progressData['certificate'];
            }
            if($progressData['language_ability']){
                $ResumeLanguageAbilityModel=ResumeLanguageAbilityModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeLanguageAbilityModel)
                    $progress+=$progressData['language_ability'];
            }
            if($progressData['specialty_label']){
                $ResumeSpecialtyLabelModel=ResumeSpecialtyLabelModel::where(['resume_id'=>$resume_id])->count();
                if ($ResumeSpecialtyLabelModel)
                    $progress+=$progressData['specialty_label'];
            }
            $ResumeModel->progress      = $progress;
            $ResumeModel->save();
        }
    }
    public static function getResumeInfo($id,$D=[])
    {
        $Field=[
            'resume.id,resume.uid,resume.name,resume.sex,resume.age,edu.title as educational_background,resume.work_experience_time,resume.specialities,residence_area.title as residence,native_place_area.title as native_place,resume.is_marry,resume.contact_qq,resume.contact_wechat,resume.update_time,resume.headimg_status,resume.progress,resume.privacy,resume.refresh_time,resume.examine',
            'job_status.title as job_status',
            'pa.title as political_affiliation',
            'self_desc.self_description',
            'user_info.headimg'
        ];
        $where=[['resume.id','=',$id],['resume.privacy','=',1]];
        if(config('xy_resume.resume_view_status')){
            $where[]=['resume.examine','=',1];
        }else{
            $where[]=['resume.examine','in',[0,1]];
        }
        $is_admin=0;
        if (isset($D['is_admin'])&&$D['is_admin']){
            $is_admin=1;
            $where=['resume.id'=>$id];
        }
        $ResumeModel=ResumeModel::alias('resume')
        ->where($where)
        ->where(['job_status.alias'=>'resume/job_status'])
        ->join('status_alias job_status','job_status.value=resume.job_status','LEFT')
        ->join('status_alias pa','pa.value=resume.political_affiliation AND pa.alias=\'resume/political_affiliation\'','LEFT')
        ->join('user user','user.id=resume.uid')
        ->join('user_info user_info','user_info.uid=user.id')
        ->join('resume_self_description self_desc','self_desc.resume_id=resume.id','LEFT')
        ->where(['edu.alias'=>'resume/educational_background'])
        ->join('status_alias edu','edu.value=resume.educational_background','LEFT')
        ->join('area residence_area','residence_area.id = resume.residence','LEFT')
        ->join('area native_place_area','native_place_area.id = resume.native_place','LEFT')
        ->withAttr('refresh_time',function($v){
            return $v?date('Y-m-d',$v):'';
        })
        ->field(implode(',',$Field))->find();
        $Data=[];
        if ($ResumeModel) {
            $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$ResumeModel->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,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')->select();
            $ResumeModel->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
            $Data=$ResumeModel->toArray();
            $Data['imgurl']=config('web.imgurl');
            if (!$is_admin) {
                $name=mb_substr($Data['name'],0,1,'utf-8');
                switch ($Data['sex']) {
                    case 1:
                        $nickname='先生';
                        break;
                    case 2:
                        $nickname='女士';
                        break;
                }
                switch (config('xy_resume.resume_name_view')) {
                    case 1:
                        $Data['name']=$name.$nickname;
                        break;
                    case 2:
                        break;
                    default:
                        if (!$Data['privacy'])
                            $Data['name']=$name.$nickname;
                        break;
                }
            }
            if ($ResumeModel->headimg_status && !$is_admin) {
                $Data['headimg']=config('web.imgurl').config('xy_default_avatar.user');
            }else{
                $Data['headimg']=$ResumeModel->headimg?config('web.imgurl').$ResumeModel->headimg:config('web.imgurl').config('xy_default_avatar.user');
            }
            $Data['age']=getWorkExpYear($ResumeModel->age);
            $Data['work_experience_time']=getWorkExpYear($ResumeModel->work_experience_time);
            $Data['resume_employment_intention']=[];
            foreach ($ResumeEmploymentIntentionModel as $k => $v) {
                $Data['resume_employment_intention'][]=[
                    'nature_of_work'    =>  $v->nature_of_work,
                    'industry'          =>  $v->industry,
                    'industry_id'       =>  $v->industry_id,
                    'jobs_cate1'        =>  $v->jobs_cate1,
                    'jobs_cate2'        =>  $v->jobs_cate2,
                    'jobs_cate3'        =>  $v->jobs_cate3,
                    'area_province'     =>  $v->area_province,
                    'area_city'         =>  $v->area_city,
                    'area_area'         =>  $v->area_area,
                    'job_area1'         =>  $v->job_area1,
                    'job_area2'         =>  $v->job_area2,
                    'job_area3'         =>  $v->job_area3,
                    'salary_min'        =>  $v->salary_min,
                    'salary_max'        =>  $v->salary_max,
                    'jobs_salary_show_type'=>  config('xy_company.jobs_salary_show_type'),
                ];
            }
            $Data['educational_experience']=ResumeEducationalExperienceModel::alias('edu')->where(['edu.resume_id'=>$ResumeModel->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()->toArray();
            $work_experience=ResumeWorkExperienceModel::alias('work')->where(['work.resume_id'=>$ResumeModel->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()->toArray();
            $Data['work_experience']=[];
            foreach ($work_experience as $k => $v) {
                $Data['work_experience'][]=[
                    'company_name'  =>  $v['company_name'],
                    'jobscate1'     =>  $v['jobs_cate1'],
                    'jobscate2'     =>  $v['jobs_cate2'],
                    'jobscate3'     =>  $v['jobs_cate3'],
                    'job_content'   =>  $v['job_content'],
                    'job_title'     =>  $v['job_title'],
                    'start_time'    =>  $v['start_time'],
                    'end_time'      =>  $v['end_time']
                ];
            }
            $Data['training_experience']=ResumeTrainingExperienceModel::where(['resume_id'=>$ResumeModel->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()->toArray();
            $Data['project_experience']=ResumeProjectExperienceModel::where(['resume_id'=>$ResumeModel->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()->toArray();
            $Data['certificate']=ResumeCertificateModel::where(['resume_id'=>$ResumeModel->id])->column('certificate_name');
            $Data['language_ability']=ResumeLanguageAbilityModel::where(['resume_id'=>$ResumeModel->id])->column('language_name');
            $Data['specialty_label']=ResumeSpecialtyLabelModel::where(['resume_id'=>$ResumeModel->id])->column('specialty_label');
            $worksWhere=[];
            if(!$is_admin&&config('xy_resume.resume_works_view_status')){
                $worksWhere['status']=1;
            }
            $Data['works']=ResumeWorksModel::where(['resume_id'=>$ResumeModel->id])->where($worksWhere)->column('path');
            $Data['is_collection']=0;
            if (!empty($D['company_id']))
                $Data['is_collection']=ResumeCollectionModel::where(['company_id'=>$D['company_id'],'resume_id'=>$ResumeModel->id])->count();
            $Data['web_logo']=config('web.imgurl').config('web.logo');
            $Data['shareData']=[
                'type'  =>6,
                'id'    =>$ResumeModel->id,
                'title' =>$Data['name'].' - '.config('web.name'),
                'desc'  =>$Data['self_description'],
                'url'   =>config('web.h5').'/#/pageA/pages/company/resume/resume?id='.$ResumeModel->id
            ];
            if (request()->AppInfo['app_modul']=='mobile'&&request()->is_wx) {
                try {
                    $tinket=Wechat::getTicket();
                    if ($tinket) {
                        $wxShareData=[
                            'noncestr'=>Str::random(16),
                            'jsapi_ticket'=>$tinket,
                            'timestamp'=>time(),
                            'url'=>config('web.h5').'/#/pageA/pages/company/resume/resume?id='.$ResumeModel->id
                        ];
                        ksort($wxShareData);
                        $wxShareData['signature']=sha1(urldecode(http_build_query($wxShareData)));
                        $wxShareData['appid']=config('xy_wechat_mp.appid').'';
                        unset($wxShareData['jsapi_ticket']);
                        $Data['wxShareData']=$wxShareData;
                    }
                } catch (\think\Exception $e) {
                    
                }
            }
        }
        return $Data;
    }
    /**
     * 获取简历所有信息
     */
    public static function getResumeInfoAll($uid)
    {
        $Field=[
            'resume.id,resume.uid,resume.name,resume.sex,resume.age,resume.educational_background,resume.work_experience_time,resume.specialities,resume.residence,resume.native_place,resume.is_marry,resume.contact_qq,resume.contact_wechat,resume.privacy,resume.headimg_status,resume.job_status,resume.political_affiliation,resume.progress,resume.refresh_time',
            'user.mobile',
            'self_desc.self_description'
        ];
        $ResumeModel=ResumeModel::alias('resume')
        ->where(['resume.uid'=>$uid])
        ->join('user user','user.id=resume.uid')
        ->join('resume_self_description self_desc','self_desc.resume_id=resume.id','LEFT')
        ->withAttr('refresh_time',function($v){
            return $v?date('Y-m-d',$v):'';
        })
        ->field(implode(',',$Field))->find();
        $Data=[];
        if ($ResumeModel) {
            $ResumeRefreshSum=ResumeRefreshLogModel::where(['resume_id'=>$ResumeModel->id])->whereTime('create_time','today')->count();
            if(!$ResumeRefreshSum){
                $ResumeRefreshLogModel=new ResumeRefreshLogModel;
                $ResumeRefreshLogModel->resume_id=$ResumeModel->id;
                Db::startTrans();
                try {
                    ResumeModel::where(['id'=>$ResumeModel->id])->update(['refresh_time'=>time()]);
                    $ResumeRefreshLogModel->save();
                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                }
            }
            $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::where(['resume_id'=>$ResumeModel->id])->select();
            $Data=$ResumeModel->toArray();
            $Data['imgurl']=config('web.imgurl');
            $Data['age']=$ResumeModel->age*1000;
            $Data['work_experience_time']=$ResumeModel->work_experience_time*1000;
            $Data['employment_intention']=[];
            foreach ($ResumeEmploymentIntentionModel as $k => $v) {
                $jobscate=[];
                if($v->jobscate1&&$v->jobscate2&&$v->jobscate3)
                    $jobscate=[$v->jobscate1,$v->jobscate2,$v->jobscate3];
                $job_area=[];
                if($v->job_area1&&$v->job_area2&&$v->job_area3)
                    $job_area=[$v->job_area1,$v->job_area2,$v->job_area3];
                $Data['employment_intention'][]=[
                    'id'                =>  $v->id,
                    'nature_of_work'    =>  $v->nature_of_work,
                    'industry_id'       =>  $v->industry_id,
                    'jobscate'          =>  $jobscate,
                    'job_area'          =>  $job_area,
                    'expected_salary'   =>  [$v->salary_min,$v->salary_max],
                    'default'           =>  $v->default,
                    'min_salary'        =>  $v->salary_min,
                    'max_salary'        =>  $v->salary_max
                ];
            }
            $Data['educational_experience']=ResumeEducationalExperienceModel::where(['resume_id'=>$ResumeModel->id])
                ->withAttr('start_time',function($v,$data){
                    return $v*1000;
                })->withAttr('end_time',function($v,$data){
                    return $v*1000;
                })->select()->toArray();
            $work_experience=ResumeWorkExperienceModel::where(['resume_id'=>$ResumeModel->id])
                ->withAttr('start_time',function($v,$data){
                    return $v*1000;
                })->withAttr('end_time',function($v,$data){
                    return $v*1000;
                })->select()->toArray();
            $Data['work_experience']=[];
            foreach ($work_experience as $k => $v) {
                $Data['work_experience'][]=[
                    'id'            =>  $v['id'],
                    'company_name'  =>  $v['company_name'],
                    'jobscate'      =>  [$v['jobscate1'],$v['jobscate2'],$v['jobscate3']],
                    'job_content'   =>  $v['job_content'],
                    'job_title'     =>  $v['job_title'],
                    'start_time'    =>  $v['start_time'],
                    'end_time'      =>  $v['end_time']
                ];
            }
            $Data['training_experience']=ResumeTrainingExperienceModel::where(['resume_id'=>$ResumeModel->id])
                ->withAttr('start_time',function($v,$data){
                    return $v*1000;
                })->withAttr('end_time',function($v,$data){
                    return $v*1000;
                })->select()->toArray();
            $Data['project_experience']=ResumeProjectExperienceModel::where(['resume_id'=>$ResumeModel->id])
                ->withAttr('start_time',function($v,$data){
                    return $v*1000;
                })->withAttr('end_time',function($v,$data){
                    return $v*1000;
                })->select()->toArray();
            $Data['certificate']=ResumeCertificateModel::where(['resume_id'=>$ResumeModel->id])->select()->toArray();
            $Data['language_ability']=ResumeLanguageAbilityModel::where(['resume_id'=>$ResumeModel->id])->select()->toArray();
            $Data['specialty_label']=ResumeSpecialtyLabelModel::where(['resume_id'=>$ResumeModel->id])->select()->toArray();
            $Data['auto_consignment']=ResumeConsignmentModel::where(['resume_id'=>$ResumeModel->id,'status'=>1])->count()?1:0;
            $Data['auto_refresh']=0;
        }
        return $Data;
    }
    public static function getResumeList($D=[])
    {
        $where=[];
        if (!empty($D['key']))
            $where[]=['self_description.self_description','like','%'.$D['key'].'%'];
        if (!empty($D['cid']) && $D['cid'])

        if (!empty($D['cid'])){
            if(is_array($D['cid'])){
                $cate=$D['cid'];
                switch (config('xy_company.search_resume_jobcate')) {
                    case 1:
                        if(intval($cate[1]))
                        $where[]=['e.jobscate2','=',intval($cate[1])];
                        break;
                    case 2:
                        if(intval($cate[2]))
                        $where[]=['e.jobscate3','=',intval($cate[2])];
                        break;
                    default:
                        if(intval($cate[0]))
                        $where[]=['e.jobscate1','=',intval($cate[0])];
                        break;
                }
            }else if(strpos($D['cid'],',')){
                $cate=explode(',',$D['cid']);
                switch (config('xy_company.search_resume_jobcate')) {
                    case 1:
                        if(intval($cate[1]))
                        $where[]=['e.jobscate2','=',intval($cate[1])];
                        break;
                    case 2:
                        if(intval($cate[2]))
                        $where[]=['e.jobscate3','=',intval($cate[2])];
                        break;
                    default:
                        if(intval($cate[0]))
                        $where[]=['e.jobscate1','=',intval($cate[0])];
                        break;
                }
            }else{
                if(intval($D['cid']))
                $where[]=['e.jobscate3','=',intval($D['cid'])];
            }
        }

        if (!empty($D['province']))
            $where[]=['e.job_area1','=',intval($D['province'])];
        if (!empty($D['city']))
            $where[]=['e.job_area2','=',intval($D['city'])];
        if (!empty($D['area']))
            $where[]=['e.job_area3','=',intval($D['area'])];

        if (!empty($D['industry']) && $D['industry'])
            $where[]=['e.industry_id','=',intval($D['industry'])];
        if ((isset($D['salary_min'])&&isset($D['salary_max']))
            &&(is_numeric($D['salary_min'])&&is_numeric($D['salary_max']))) {
            if ($D['salary_min']>0&&$D['salary_max']<=100) {
                $where[]=['e.salary_min','>',0];
                $where[]=['e.salary_min','>=',intval($D['salary_min'])];
                $where[]=['e.salary_max','<=',intval($D['salary_max'])];
            }else{
                $where[]=['e.salary_min','=',0];
                $where[]=['e.salary_max','=',100];
            }
        }elseif(isset($D['salary_min'])&&is_numeric($D['salary_min'])){
            if($D['salary_min']>0){
                $where[]=['e.salary_min','>=',intval($D['salary_min'])];
            }else{
                $where[]=['e.salary_min','=',0];
                $where[]=['e.salary_max','=',100];
            }
        }elseif(isset($D['salary_max'])&&is_numeric($D['salary_min'])){
            $where[]=['e.salary_max','<=',intval($D['salary_max'])];
        }
        if (!empty($D['recommend'])){
            $where[]=['resume.recommend','=',1];
        }
        if (!empty($D['sex']))
            $where[]=['resume.sex','=',intval($D['sex'])];
        if (!empty($D['educational_background']))
            $where[]=['resume.educational_background','=',intval($D['educational_background'])];
        if (!empty($D['political_affiliation']))
            $where[]=['resume.political_affiliation','=',$D['political_affiliation']];
        if (!empty($D['nature_of_work']))
            $where[]=['e.nature_of_work','=',intval($D['nature_of_work'])];
        if (!empty($D['age'])) {
            switch ($D['age']) {
                case 20:
                    $where[]=['resume.age','>=',time()-3600*24*365*20];
                    break;
                case 25:
                    $where[]=['resume.age','<=',time()-3600*24*365*20];
                    $where[]=['resume.age','>=',time()-3600*24*365*25];
                    break;
                case 35:
                    $where[]=['resume.age','<=',time()-3600*24*365*25];
                    $where[]=['resume.age','>=',time()-3600*24*365*35];
                    break;
                case 45:
                    $where[]=['resume.age','<=',time()-3600*24*365*35];
                    $where[]=['resume.age','>=',time()-3600*24*365*45];
                    break;
                case 46:
                    $where[]=['resume.age','<=',time()-3600*24*365*45];
                    break;
            }
        }
        if (!empty($D['exp_level'])&&$D['exp_level']!=0) {
            $time=time();
            $yearTime=3600*24*365;
            switch ($D['exp_level']) {
                case 1:
                    $where[]=['resume.work_experience_time','between',[$time-$yearTime*4,$time-$yearTime*1]];
                    break;
                case 3:
                    $where[]=['resume.work_experience_time','between',[$time-$yearTime*6,$time-$yearTime*3]];
                    break;
                case 5:
                    $where[]=['resume.work_experience_time','between',[$time-$yearTime*11,$time-$yearTime*5]];
                    break;
                case 10:
                    $where[]=['resume.work_experience_time','<=',$time-$yearTime*10];
                    break;
            }
        }
        $sort='resume.refresh_time desc,resume.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='resume.update_time desc,resume.id desc';
                    break;
                case 'recommend':
                    $sort='resume.progress desc,resume.refresh_time desc,resume.id desc';
                    break;
            }
        }
        $length=15;
        if (!empty($D['length']))
            $length=intval($D['length']);
        $Field=[
            'resume.id,resume.uid,resume.name,resume.sex,resume.age,resume.educational_background,resume.work_experience_time,resume.refresh_time,resume.progress,resume.headimg_status,resume.privacy,resume.create_time',
            'e.salary_min,e.salary_max',
            'nature_of_work.title as nature_of_work',
            'job_status.title as job_status',
            'jobs_cate.title as job_title',
            'industry.title as industry',
            'province.title as job_province,city.title as job_city,area.title as job_area',
            'educational_background.title as educational_background',
            'self_description.self_description',
            'user_info.headimg'
        ];
        if (isset(request()->sub_industry))
            $where[]=['e.industry_id','=',request()->sub_industry];
        if (isset(request()->sub_province))
            $where[]=['e.job_area1','=',request()->sub_province];
        if (isset(request()->sub_city))
            $where[]=['e.job_area2','=',request()->sub_city];
        if (isset(request()->sub_area))
            $where[]=['e.job_area3','=',request()->sub_area];
        if(config('xy_resume.resume_view_status')){
            $where[]=['resume.examine','=',1];
        }else{
            $where[]=['resume.examine','in',[0,1]];
        }
        if(config('xy_resume.resume_role_type'))
            $where[]=['user_info.role_type','=',0];
        $ResumeModel=ResumeModel::alias('resume')
            ->where(['user.status'=>1,'resume.privacy'=>1])
            ->where($where);
            if (isset($D['update_time'])) {
                switch ($D['update_time']) {
                    case 1:
                        $ResumeModel->whereDay('resume.refresh_time','today');
                        break;
                    case 2:
                        $ResumeModel->whereDay('resume.refresh_time',date('Y-m-d',time()-(3600*24*3)));
                        break;
                    case 3:
                        $ResumeModel->whereDay('resume.refresh_time',date('Y-m-d',time()-(3600*24*7)));
                        break;
                }
            }
        if(!empty($D['uid'])){
            $ResumeModel->where('resume.uid', 'NOTIN', function ($query)use($D) {
                $query->name('company_blacklist')->where(['uid'=>$D['uid']])->field('to_uid');
            });
            $ResumeModel->where('resume.uid', 'NOTIN', function ($query)use($D) {
                $query->name('resume_blacklist')->where(['to_uid'=>$D['uid']])->field('uid');
            });
        }
        list($todayStart,$todayEnd)=Time::today();
        $Data=$ResumeModel->where(['educational_background.alias'=>'resume/educational_background'])
            ->where(['job_status.alias'=>'resume/job_status'])
            ->join('user user','user.id=resume.uid')
            ->join('user_info user_info','user_info.uid=user.id')
            ->join('status_alias job_status','job_status.value=resume.job_status','LEFT')
            ->join('resume_self_description self_description','self_description.resume_id=resume.id','LEFT')
            ->join('status_alias educational_background','educational_background.value=resume.educational_background','LEFT')
            ->join('resume_employment_intention e','e.resume_id=resume.id AND e.default=1','LEFT')
            ->join('jobs_cate jobs_cate','jobs_cate.id=e.jobscate3','LEFT')
            ->join('company_industry industry','industry.id=e.industry_id','LEFT')
            ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work AND nature_of_work.alias=\'resume/nature_of_work\'','LEFT')
            ->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')
            ->order($sort)
            ->field(implode(',',$Field))->paginate($length)
            ->each(function($item, $key)use($D,$todayStart,$todayEnd){
                $name=mb_substr($item['name'],0,1,'utf-8');
                switch ($item['sex']) {
                    case 1:
                        $nickname='先生';
                        break;
                    case 2:
                        $nickname='女士';
                        break;
                }
                switch (config('xy_resume.resume_name_view')) {
                    case 1:
                        $item['name']=$name.$nickname;
                        break;
                    case 2:
                        break;
                    default:
                        if (!$item['privacy'])
                            $item['name']=$name.$nickname;
                        break;
                }
                $item['age']=getWorkExpYear($item['age']);
                $item['work_experience_time']=getWorkExpYear($item['work_experience_time']);
                $item['friendly_time']=friendly_time($item['refresh_time'],'friendly');
                $item['specialty_label']=ResumeSpecialtyLabelModel::where(['resume_id'=>$item['id']])->column('specialty_label');
                if ($item['headimg_status']) {
                    $item['headimg']=config('web.imgurl').config('xy_default_avatar.user');
                }else{
                    $item['headimg']=$item['headimg']?config('web.imgurl').$item['headimg']:config('web.imgurl').config('xy_default_avatar.user');
                }
                $item['is_collection']=0;
                if (!empty($D['company_id']))
                    $item['is_collection']=ResumeCollectionModel::where(['company_id'=>$D['company_id'],'resume_id'=>$item->id])->count();
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
                $item->employment_intention=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$item->id])->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3')->column('jobs_cate3.title');
                $item->is_today_create=(strtotime($item->create_time)>$todayStart&&strtotime($item->create_time)<$todayEnd)?1:0;
                $item->is_today=($item->refresh_time>$todayStart&&$item->refresh_time<$todayEnd)?1:0;
                return $item;
            });
        return $Data;
    }
    public static function getSelect($D=[])
    {
        $where=[];
        if (!empty($D['key']))
            $where[]=['self_description.self_description','like','%'.$D['key'].'%'];

        if (!empty($D['province']))
            $where[]=['e.job_area1','=',intval($D['province'])];
        if (!empty($D['city']))
            $where[]=['e.job_area2','=',intval($D['city'])];
        if (!empty($D['area']))
            $where[]=['e.job_area3','=',intval($D['area'])];
        
        if (!empty($D['industry']) && $D['industry'])
            $where[]=['e.industry_id','=',intval($D['industry'])];
        if ((isset($D['salary_min'])&&isset($D['salary_max']))
            &&(is_numeric($D['salary_min'])&&is_numeric($D['salary_max']))) {
            if ($D['salary_min']>0&&$D['salary_max']<=100) {
                $where[]=['e.salary_min','>',0];
                $where[]=['e.salary_min','>=',intval($D['salary_min'])];
                $where[]=['e.salary_max','<=',intval($D['salary_max'])];
            }else{
                $where[]=['e.salary_min','=',0];
                $where[]=['e.salary_max','=',100];
            }
        }elseif(isset($D['salary_min'])&&is_numeric($D['salary_min'])){
            if($D['salary_min']>0){
                $where[]=['e.salary_min','>=',intval($D['salary_min'])];
            }else{
                $where[]=['e.salary_min','=',0];
                $where[]=['e.salary_max','=',100];
            }
        }elseif(isset($D['salary_max'])&&is_numeric($D['salary_min'])){
            $where[]=['e.salary_max','<=',intval($D['salary_max'])];
        }
        if (!empty($D['nature_of_work']))
            $where[]=['e.nature_of_work','=',intval($D['nature_of_work'])];
        if (!empty($D['sex']))
            $where[]=['resume.sex','=',intval($D['sex'])];
        if (!empty($D['educational_background']))
            $where[]=['resume.educational_background','=',intval($D['educational_background'])];
        if (!empty($D['political_affiliation']))
            $where[]=['resume.political_affiliation','=',$D['political_affiliation']];
        if (!empty($D['age'])) {
            switch ($D['age']) {
                case 20:
                    $where[]=['resume.age','>=',time()-3600*24*365*20];
                    break;
                case 25:
                    $where[]=['resume.age','<=',time()-3600*24*365*20];
                    $where[]=['resume.age','>=',time()-3600*24*365*25];
                    break;
                case 35:
                    $where[]=['resume.age','<=',time()-3600*24*365*25];
                    $where[]=['resume.age','>=',time()-3600*24*365*35];
                    break;
                case 45:
                    $where[]=['resume.age','<=',time()-3600*24*365*35];
                    $where[]=['resume.age','>=',time()-3600*24*365*45];
                    break;
                case 46:
                    $where[]=['resume.age','<=',time()-3600*24*365*45];
                    break;
            }
        }
        if (!empty($D['exp_level'])&&$D['exp_level']!=0) {
            $time=time();
            $yearTime=3600*24*365;
            switch ($D['exp_level']) {
                case 1:
                    $where[]=['resume.work_experience_time','between',[$time-$yearTime*4,$time-$yearTime*1]];
                    break;
                case 3:
                    $where[]=['resume.work_experience_time','between',[$time-$yearTime*6,$time-$yearTime*3]];
                    break;
                case 5:
                    $where[]=['resume.work_experience_time','between',[$time-$yearTime*11,$time-$yearTime*5]];
                    break;
                case 10:
                    $where[]=['resume.work_experience_time','<=',$time-$yearTime*10];
                    break;
            }
        }
        $sort='resume.refresh_time desc,resume.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='resume.update_time desc,resume.id desc';
                    break;
                case 'recommend':
                    $sort='resume.recommend desc,resume.progress desc,resume.refresh_time desc,resume.id desc';
                    break;
            }
        }
        $Field=[
            'resume.id,resume.uid,resume.name,resume.sex,resume.age,resume.educational_background,resume.work_experience_time,resume.refresh_time,resume.progress,resume.headimg_status,resume.create_time',
            'e.salary_min,e.salary_max',
            'nature_of_work.title as nature_of_work',
            'job_status.title as job_status',
            'industry.title as industry',
            'jobs_cate3.title as jobs_cate3,jobs_cate3.title as job_title',
            'area.title as job_area',
            'educational_background.title as educational_background',
            'self_description.self_description',
            'user_info.headimg'
        ];
        if (isset(request()->sub_industry))
            $where[]=['e.industry_id','=',request()->sub_industry];
        if (isset(request()->sub_province))
            $where[]=['e.job_area1','=',request()->sub_province];
        if (isset(request()->sub_city))
            $where[]=['e.job_area2','=',request()->sub_city];
        if (isset(request()->sub_area))
            $where[]=['e.job_area3','=',request()->sub_area];
        if(config('xy_resume.resume_view_status')){
            $where[]=['resume.examine','=',1];
        }else{
            $where[]=['resume.examine','in',[0,1]];
        }
        if(config('xy_resume.resume_role_type'))
            $where[]=['user_info.role_type','=',0];
        $ResumeModel=ResumeModel::alias('resume')
            ->where(['user.status'=>1,'resume.privacy'=>1])
            ->where($where);
            if (isset($D['update_time'])) {
                switch ($D['update_time']) {
                    case 1:
                        $ResumeModel->whereDay('resume.refresh_time','today');
                        break;
                    case 2:
                        $ResumeModel->whereDay('resume.refresh_time',date('Y-m-d',time()-(3600*24*3)));
                        break;
                    case 3:
                        $ResumeModel->whereDay('resume.refresh_time',date('Y-m-d',time()-(3600*24*7)));
                        break;
                }
            }
        if(!empty($D['uid'])){
            $ResumeModel->where('resume.uid', 'NOTIN', function ($query)use($D) {
                $query->name('company_blacklist')->where(['uid'=>$D['uid']])->field('to_uid');
            });
            $ResumeModel->where('resume.uid', 'NOTIN', function ($query)use($D) {
                $query->name('resume_blacklist')->where(['to_uid'=>$D['uid']])->field('uid');
            });
        }
        $Data=$ResumeModel->where(['educational_background.alias'=>'resume/educational_background'])
            ->where(['job_status.alias'=>'resume/job_status'])
            ->join('user user','user.id=resume.uid')
            ->join('user_info user_info','user_info.uid=user.id')
            ->join('resume_employment_intention e','e.resume_id=resume.id AND e.default=1','LEFT')
            ->join('company_industry industry','industry.id=e.industry_id','LEFT')
            ->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3','LEFT')
            ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work AND nature_of_work.alias=\'resume/nature_of_work\'','LEFT')
            ->join('area area','area.id = e.job_area2','LEFT')
            ->join('resume_self_description self_description','self_description.resume_id=resume.id','LEFT')
            ->join('status_alias educational_background','educational_background.value=resume.educational_background')
            ->join('status_alias job_status','job_status.value=resume.job_status')
            ->order($sort)
            ->field(implode(',',$Field))->limit($D['length'])
            ->withAttr('name',function($v,$data){
                return mb_substr($v,0,1,'utf-8');
            })
            ->withAttr('age',function($v,$data){
                return getWorkExpYear($v);
            })
            ->withAttr('work_experience_time',function($v,$data){
                return getWorkExpYear($v);
            })
            ->withAttr('refresh_time',function($v,$data){
                return friendly_time($v,'friendly');
            })
            ->withAttr('job_area',function($v,$data){
                return $v?$v:'地区不限';
            })
            ->withAttr('headimg',function($v,$data){
                if ($data['headimg_status']) {
                    return config('web.imgurl').config('xy_default_avatar.user');
                }else{
                    return $v?config('web.imgurl').$v:config('web.imgurl').config('xy_default_avatar.user');
                }
            })->select();
        if ($Data) {
            list($todayStart,$todayEnd)=Time::today();
            foreach ($Data as $item) {
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
                $item->employment_intention=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$item->id])->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3')->column('jobs_cate3.title');
                $item->is_today_create=(strtotime($item->create_time)>$todayStart&&strtotime($item->create_time)<$todayEnd)?1:0;
                $item->is_today=($item->refresh_time>$todayStart&&$item->refresh_time<$todayEnd)?1:0;
            }
        }
        return $Data;
    }
    public static function updateResumeJobStatus($D)
    {
        $ResumeModel=ResumeModel::where(['id'=>$D['resume_id'],'uid'=>$D['uid']])->field('id,job_status')->find();
        if ($ResumeModel) {
            $ResumeModel->job_status=$D['job_status'];
            if($ResumeModel->save()){
                return parent::ajaxReturn('',MsgCode::$success);
            }else{
                return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
            }
        }else{
            return parent::ajaxReturn('请先创建简历',MsgCode::$error);
        }
    }
    public static function setResumeRefreshTime($D)
    {
        $ResumeModel=ResumeModel::where(['uid'=>$D['uid'],'id'=>$D['resume_id']])->field('id,refresh_time')->find();
        if (!$ResumeModel)
            return parent::ajaxReturn('简历不存在，请刷新重试',MsgCode::$error);
        $resume_free_refresh_sum=config('xy_resume.resume_free_refresh_sum');
        if($resume_free_refresh_sum){
            $ResumeRefreshSum=ResumeRefreshLogModel::where(['resume_id'=>$ResumeModel->id])->whereTime('create_time','today')->count();
            if($ResumeRefreshSum>=$resume_free_refresh_sum)
                return parent::ajaxReturn('每日免费刷新已达上限，'.$resume_free_refresh_sum.'次',MsgCode::$error);
        }
        $refresh_time=time()-$ResumeModel->refresh_time;
        $resume_refresh_interval=config('xy_resume.resume_refresh_interval');
        if ($refresh_time<$resume_refresh_interval*60)
            return parent::ajaxReturn('刷新冷却中，请'.($resume_refresh_interval*60-$refresh_time).'秒后再试',MsgCode::$error);
        $ResumeModel->refresh_time=time();
        $ResumeRefreshLogModel=new ResumeRefreshLogModel;
        $ResumeRefreshLogModel->resume_id=$ResumeModel->id;
        Db::startTrans();
        try {
            $ResumeModel->save();
            $ResumeRefreshLogModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('刷新成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }
    }
    public static function setAutoConsignment($D)
    {
        $ResumeModel=ResumeModel::where(['uid'=>$D['uid'],'id'=>$D['resume_id']])->field('id,refresh_time')->find();
        if (!$ResumeModel)
            return parent::ajaxReturn('简历不存在，请刷新重试',MsgCode::$error);
        $ResumeConsignmentModel=ResumeConsignmentModel::where(['resume_id'=>$ResumeModel->id,'status'=>1])->find();
        if ($ResumeConsignmentModel){
            $ResumeConsignmentModel->status=0;
            $ResumeConsignmentModel->cancel_time=time();
        }else{
           $ResumeConsignmentModel=new ResumeConsignmentModel;
           $ResumeConsignmentModel->resume_id=$ResumeModel->id; 
           $ResumeConsignmentModel->sum=0; 
           $ResumeConsignmentModel->start_time=time(); 
           $ResumeConsignmentModel->end_time=time()+3600*24*3; 
        }

        Db::startTrans();
        try {
            $ResumeConsignmentModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('刷新成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }
    }
    public static function getCreateDocxResumeInfo($id)
    {
        $Field=[
            'resume.id,resume.name,resume.sex,resume.age,edu.title as educational_background,resume.work_experience_time,resume.specialities,residence_area.title as residence,native_place_area.title as native_place,resume.is_marry,resume.contact_qq,resume.contact_wechat,resume.update_time,resume.headimg_status,job_status.title as job_status',
            'self_desc.self_description',
            'user.mobile,user.email',
            'user_info.headimg'
        ];
        $where=['resume.id'=>$id];
        $ResumeModel=ResumeModel::alias('resume')
        ->where($where)
        ->join('user user','user.id=resume.uid')
        ->join('user_info user_info','user_info.uid=user.id')
        ->join('resume_self_description self_desc','self_desc.resume_id=resume.id','LEFT')
        ->where(['edu.alias'=>'resume/educational_background'])
        ->join('status_alias edu','edu.value=resume.educational_background')
        ->join('area residence_area','residence_area.id = resume.residence','LEFT')
        ->join('area native_place_area','native_place_area.id = resume.native_place','LEFT')
        ->where(['job_status.alias'=>'resume/job_status'])
        ->join('status_alias job_status','job_status.value=resume.job_status')
        ->field(implode(',',$Field))->find();
        $Data=[];
        if ($ResumeModel) {
            $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$ResumeModel->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,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 job_province,city.title as job_city,area.title as job_area')->select();
            $Data=$ResumeModel->toArray();
            $Data['headimg']=$ResumeModel->headimg?config('web.imgurl').$ResumeModel->headimg:config('web.imgurl').config('xy_default_avatar.user');
            $Data['age']=getWorkExpYear($ResumeModel->age);
            $Data['work_experience_time']=getWorkExpYear($ResumeModel->work_experience_time);
            foreach ($ResumeEmploymentIntentionModel as $k => $v) {
                $Data['resume_employment_intention'][]=[
                    'nature_of_work'    =>  $v->nature_of_work,
                    'industry_id'       =>  $v->industry_id,
                    'jobscate1'         =>  $v->jobs_cate1,
                    'jobscate2'         =>  $v->jobs_cate2,
                    'jobscate3'         =>  $v->jobs_cate3,
                    'job_area'          =>  $v->job_area,
                    'expected_salary'   =>  [$v->salary_min,$v->salary_max],
                    'min_salary'        =>  $v->salary_min,
                    'max_salary'        =>  $v->salary_max
                ];
            }
            $Data['educational_experience']=ResumeEducationalExperienceModel::alias('edu')->where(['edu.resume_id'=>$ResumeModel->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()->toArray();
            $work_experience=ResumeWorkExperienceModel::alias('work')->where(['work.resume_id'=>$ResumeModel->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()->toArray();
            $Data['work_experience']=[];
            foreach ($work_experience as $k => $v) {
                $Data['work_experience'][]=[
                    'company_name'  =>  $v['company_name'],
                    'jobscate1'     =>  $v['jobs_cate1'],
                    'jobscate2'     =>  $v['jobs_cate2'],
                    'jobscate3'     =>  $v['jobs_cate3'],
                    'job_content'   =>  $v['job_content'],
                    'job_title'     =>  $v['job_title'],
                    'start_time'    =>  $v['start_time'],
                    'end_time'      =>  $v['end_time']
                ];
            }
            $Data['training_experience']=ResumeTrainingExperienceModel::where(['resume_id'=>$ResumeModel->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()->toArray();
            $Data['project_experience']=ResumeProjectExperienceModel::where(['resume_id'=>$ResumeModel->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()->toArray();
            $Data['certificate']=ResumeCertificateModel::where(['resume_id'=>$ResumeModel->id])->column('certificate_name');
            $Data['language_ability']=ResumeLanguageAbilityModel::where(['resume_id'=>$ResumeModel->id])->column('language_name');
            $Data['specialty_label']=ResumeSpecialtyLabelModel::where(['resume_id'=>$ResumeModel->id])->column('specialty_label');
            $Data['works']=ResumeWorksModel::where(['resume_id'=>$ResumeModel->id,'status'=>1])->field('path as url')
                    ->withAttr('url',function($v,$data){
                        return config('web.imgurl').$v;
                    })->column('path');
        }
        return $Data;
    }
    /**
     * 删除简历经历
     */
    public static function delExperience($D)
    {
        if (empty($D['type']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[MsgCode::$error]',MsgCode::$error);
        if (empty($D['id']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        $uid=$D['uid'];
        if (!$uid)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        $Model=null;
        $Data=null;
        switch ($D['type']) {
            case 'employment_intention':
                return self::delJobHuntingIntention($D);
                break;
            case 'educational_experience':
                $Model=new ResumeEducationalExperienceModel;
                $Data=$Model->alias('e')->where(['e.id'=>$D['id']])->join('resume resume','resume.id=e.resume_id')->where(['resume.uid'=>$uid])->field('e.id')->find();
                break;
            case 'work_experience':
                $Model=new ResumeWorkExperienceModel;
                $Data=$Model->alias('w')->where(['w.id'=>$D['id']])->join('resume resume','resume.id=w.resume_id')->where(['resume.uid'=>$uid])->field('w.id')->find();
                break;
            case 'training_experience':
                $Model=new ResumeTrainingExperienceModel;
                $Data=$Model->alias('t')->where(['t.id'=>$D['id']])->join('resume resume','resume.id=t.resume_id')->where(['resume.uid'=>$uid])->field('t.id')->find();
                break;
            case 'project_experience':
                $Model=new ResumeProjectExperienceModel;
                $Data=$Model->alias('p')->where(['p.id'=>$D['id']])->join('resume resume','resume.id=p.resume_id')->where(['resume.uid'=>$uid])->field('p.id')->find();
                break;
            case 'certificate':
                $Model=new ResumeCertificateModel;
                $Data=$Model->alias('c')->where(['c.id'=>$D['id']])->join('resume resume','resume.id=c.resume_id')->where(['resume.uid'=>$uid])->field('c.id')->find();
                break;
            case 'language_ability':
                $Model=new ResumeLanguageAbilityModel;
                $Data=$Model->alias('l')->where(['l.id'=>$D['id']])->join('resume resume','resume.id=l.resume_id')->where(['resume.uid'=>$uid])->field('l.id')->find();
                break;
            case 'specialty_label':
                $Model=new ResumeSpecialtyLabelModel;
                $Data=$Model->alias('s')->where(['s.id'=>$D['id']])->join('resume resume','resume.id=s.resume_id')->where(['resume.uid'=>$uid])->field('s.id')->find();
                break;
        }
        if ($Data) {
            if ($Model::destroy($Data->id)) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('删除失败，请刷新重试',MsgCode::$error);
        }else return parent::ajaxReturn('数据不存在',MsgCode::$error);
    }
    /**
     * 投递简历
     */
    public static function deliveryResume($D,$is_consignment=0)
    {
        if (!$D['id'])
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        $uid=$D['uid'];
        if (!$uid)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        $ResumeModel=ResumeModel::alias('resume')->where(['resume.uid'=>$uid])
        ->where(['educational_background.alias'=>'resume/educational_background'])
        ->join('user_info user_info','user_info.uid=resume.uid')
        ->join('status_alias educational_background','educational_background.value=resume.educational_background')
        ->field('resume.*,educational_background.title as educational_background_title,user_info.role_type')->find();
        if ($ResumeModel) {
            if (empty($D['im'])) {
                if($ResumeModel->role_type)
                    return parent::ajaxReturn('请切换为求职者进行投递',MsgCode::$error);
                if(config('xy_resume.resume_view_status')&&!$ResumeModel->examine)
                    return parent::ajaxReturn('简历审核中，请等待审核通过',MsgCode::$error);
                $delivery_resume_today_sum=config('xy_resume.delivery_resume_today_sum');
                if($delivery_resume_today_sum){
                    $delivery_resume_sum=JobsDeliveryResumeModel::where(['uid'=>$uid])->whereDay('create_time')->count();
                    if($delivery_resume_sum>=$delivery_resume_today_sum)
                        return parent::ajaxReturn('已达每日投递上限，'.$delivery_resume_today_sum.'次',MsgCode::$error);
                }
                $delivery_resume_sum_30m=config('xy_resume.delivery_resume_sum_30m');
                if($delivery_resume_sum_30m){
                    $delivery_resume_sum=JobsDeliveryResumeModel::where(['uid'=>$uid])->whereTime('create_time','between',[time()-1800,time()])->count();
                    if($delivery_resume_sum>=$delivery_resume_sum_30m)
                        return parent::ajaxReturn('30分钟内允许投递'.$delivery_resume_sum_30m.'次',MsgCode::$error);
                }
                $delivery_resume_progress=config('xy_resume.delivery_resume_progress');
                if($delivery_resume_progress&&$delivery_resume_progress>$ResumeModel->progress)
                    return parent::ajaxReturn('简历完整度须达到'.$delivery_resume_progress.'%',MsgCode::$resume);
            }
            $JobsModel=JobsModel::alias('jobs')->where(['jobs.id'=>$D['id'],'jobs.status'=>1])
            ->join('company company','company.id=jobs.company_id')
            ->field('jobs.*,company.uid')->find();
            if ($JobsModel) {
                if($JobsModel->uid==$uid)
                    return parent::ajaxReturn('您不能投递自己发布的职位哦',MsgCode::$error);
                $br=isset($D['html'])&&$D['html']?'</br>':"\n";
                $confirmText='';
                if($ResumeModel->educational_background<$JobsModel->education_level)
                    $confirmText='你的学历未达到要求是否继续投递？'.$br;
                $work_experience=getWorkExpYear($ResumeModel->work_experience_time);
                if($work_experience<$JobsModel->exp_level)
                    $confirmText.='你的工作经验未达到要求是否继续投递？'.$br;
                if (!$D['confirm']&&$confirmText) return parent::ajaxReturn($confirmText,MsgCode::$confirm);
                $JobsDeliveryResumeModel=JobsDeliveryResumeModel::where(['uid'=>$uid,'jobs_id'=>$JobsModel->id])->find();
                if ($JobsDeliveryResumeModel){
                    if (empty($D['im'])){
                    return parent::ajaxReturn('您已投递过该职位了，请勿重复投递',MsgCode::$error);
                    }else{
                    return parent::ajaxReturn('该用户已投递或已加入待处理',MsgCode::$error);
                    }
                }
                $JobsDeliveryResumeModel=new JobsDeliveryResumeModel;
                $JobsDeliveryResumeModel->company_id    =   $JobsModel->company_id;
                $JobsDeliveryResumeModel->uid           =   $uid;
                $JobsDeliveryResumeModel->resume_id     =   $ResumeModel->id;
                $JobsDeliveryResumeModel->jobs_id       =   $JobsModel->id;
                $JobsDeliveryResumeModel->app_id        =   request()->ApiInfo['app_id'];
                $JobFairResumeModel=null;
                $ResumeSumModel=null;
                if(!empty($D['job_fair_id'])){
                    $JobFairModel=JobFairController::getFind(['job.id'=>$D['job_fair_id']]);
                    if(!$JobFairModel)
                        return parent::ajaxReturn('招聘会不存在',MsgCode::$error);
                    if($JobFairModel->status!==2)
                        return parent::ajaxReturn('招聘会未开启，请留意开启时间',MsgCode::$error);
                    $JobsDeliveryResumeModel->job_fair_id=$JobFairModel->id;
                    if(!JobFairResumeModel::where(['jid'=>$JobFairModel->id,'resume_id'=>$ResumeModel->id])->count()){
                        $JobFairResumeModel=new JobFairResumeModel;
                        $JobFairResumeModel->jid=$JobFairModel->id;
                        $JobFairResumeModel->resume_id=$ResumeModel->id;
                        $ResumeSumModel=JobFairModel::where(['id'=>$JobFairModel->id])->inc('resume_sum');
                    }
                }
                $JobsDeliveryResumeModel->is_consignment=   $is_consignment;
                $ResumeConsignmentModel=null;
                if ($is_consignment) {
                    $ResumeConsignmentModel=ResumeConsignmentModel::where(['resume_id'=>$ResumeModel->id])->find();
                    $ResumeConsignmentModel->sum=Db::raw('sum+1');
                }
                $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$ResumeModel->id,'e.default'=>1])
                ->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('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('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();
                if($ResumeEmploymentIntentionModel){
                    if ($ResumeEmploymentIntentionModel->salary_min>0) {
                        $JobsModel->salary=$ResumeEmploymentIntentionModel->salary_min.'~'.$ResumeEmploymentIntentionModel->salary_max;
                    }else{
                        $JobsModel->salary='面议';
                    }
                    $JobsModel->industry=$ResumeEmploymentIntentionModel->industry;
                    $JobsModel->jobs_cate1=$ResumeEmploymentIntentionModel->jobs_cate1;
                    $JobsModel->jobs_cate2=$ResumeEmploymentIntentionModel->jobs_cate2;
                    $JobsModel->jobs_cate3=$ResumeEmploymentIntentionModel->jobs_cate3;
                    $JobsModel->area_province=$ResumeEmploymentIntentionModel->area_province;
                    $JobsModel->area_city=$ResumeEmploymentIntentionModel->area_city;
                    $JobsModel->area_area=$ResumeEmploymentIntentionModel->area_area;
                }
                $JobsModel->name=$ResumeModel->name;
                $JobsModel->work_experience=$work_experience>0?$work_experience.'年':'无';
                $JobsModel->educational_background=$ResumeModel->educational_background_title;
                $PushTaskModel=new PushTaskModel;
                $PushTaskModel->event       =   'DeliveryResume';
                $PushTaskModel->uid         =   $JobsModel->uid;
                $PushTaskModel->data        =   json_encode($JobsModel,JSON_UNESCAPED_UNICODE);
                Db::startTrans();
                try {
                    JobsModel::where(['id'=>$JobsModel->id])->inc('delivery_resume')->update();
                    $JobsDeliveryResumeModel->save();
                    if($ResumeConsignmentModel)$ResumeConsignmentModel->save();
                    if($JobFairResumeModel)$JobFairResumeModel->save();
                    if($ResumeSumModel)$ResumeSumModel->update();
                    $PushTaskModel->save();
                    // 提交事务
                    Db::commit();
                    if (empty($D['im'])){
                    return parent::ajaxReturn('投递成功');
                    }else{
                    return parent::ajaxReturn('已加入');
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    if (empty($D['im'])){
                    return parent::ajaxReturn('投递失败，请重试',MsgCode::$error);
                    }else{
                    return parent::ajaxReturn('加入失败，请重试',MsgCode::$error);
                    }
                }
            }else return parent::ajaxReturn('该职位已停止招聘或不存在',MsgCode::$error);
        }else return parent::ajaxReturn('请先完善简历，在进行投递。',MsgCode::$resume);
    }
    /**
     * 设置投递的简历状态-不合适
     */
    public static function setResumeInappropriate($D)
    {
        if (!$D['id'])
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        $uid=$D['uid'];
        if (!$uid)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        if (!$D['company_id'])
            return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        $JobsDeliveryResumeModel=JobsDeliveryResumeModel::where(['company_id'=>$D['company_id'],'id'=>$D['id']])->find();
        if ($JobsDeliveryResumeModel) {
            $JobsDeliveryResumeModel->status=2;
            if ($JobsDeliveryResumeModel->save()) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('设置失败，请刷新重试',MsgCode::$error);
        }else return parent::ajaxReturn('数据不存在',MsgCode::$error);
    }
    /**
     * 设置投递的简历状态-已查看
     */
    public static function setDeliveryResumeViewed($D)
    {
        if (!$D['id'])
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        $uid=$D['uid'];
        if (!$uid)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        if (!$D['company_id'])
            return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        $JobsDeliveryResumeModel=JobsDeliveryResumeModel::where(['company_id'=>$D['company_id'],'id'=>$D['id']])->find();
        if ($JobsDeliveryResumeModel) {
            if($JobsDeliveryResumeModel->status)
                return parent::ajaxReturn();
            $JobsDeliveryResumeModel->status=1;
            if ($JobsDeliveryResumeModel->save()) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('查看失败',MsgCode::$error);
        }else return parent::ajaxReturn('数据不存在',MsgCode::$error);
    }
    /**
     * 邀请面试
     */
    public static function inviteAnInterview($D)
    {
        /**
         * 邀请面试联系信息验证
         */
        try {
            validate(InviteAninterviewValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        $JobsDeliveryResumeModel=JobsDeliveryResumeModel::where(['company_id'=>$D['company_id'],'id'=>$D['id']])->find();
        if ($JobsDeliveryResumeModel) {
            $JobsModel=JobsModel::alias('jobs')->where(['jobs.id'=>$JobsDeliveryResumeModel->jobs_id])
            ->join('company company','company.id=jobs.company_id')
            ->field('jobs.title,company.uid,company.title as company_name')->find();
            $invite_aninterview=UserVipRuleModel::alias('rule')
                ->where(['rule.uid'=>$JobsModel->uid,'rule.status'=>1])
                ->join(config('databse.prefix').'vip vip','vip.id=rule.vid')
                ->join('vip_rule_value value','value.id=rule.rid')
                ->whereTime('rule.expiry_time','>',time())->order('rule.level desc')->where(['vip.is_company'=>1,'value.alias'=>'invite-aninterview'])->sum('rule.surplus_value');
            if($invite_aninterview<=0)
                return parent::ajaxReturn('邀请面试次数不足，请充值',MsgCode::$vip);
            $JobsDeliveryResumeModel->status=3;
            $InviteAninterviewModel=new InviteAninterviewModel;
            $InviteAninterviewModel->delivery_id        =   $JobsDeliveryResumeModel->id;
            $InviteAninterviewModel->company_id         =   $JobsDeliveryResumeModel->company_id;
            $InviteAninterviewModel->uid                =   $JobsDeliveryResumeModel->uid;
            $InviteAninterviewModel->resume_id          =   $JobsDeliveryResumeModel->resume_id;
            $InviteAninterviewModel->jobs_id            =   $JobsDeliveryResumeModel->jobs_id;
            $InviteAninterviewModel->contacts           =   $D['contacts'];
            $InviteAninterviewModel->contacts_tel       =   $D['contacts_tel'];
            $InviteAninterviewModel->contacts_mobile    =   $D['contacts_mobile'];
            $InviteAninterviewModel->contacts_email     =   $D['contacts_email'];
            $InviteAninterviewModel->address            =   $D['address'];
            $InviteAninterviewModel->interview_date     =   round($D['interview_date']/1000);
            $InviteAninterviewModel->interview_start_time=  strtotime(date('Y-m-d',$D['interview_date']/1000).' '.$D['interview_start_time'].':00');
            $InviteAninterviewModel->interview_end_time =   strtotime(date('Y-m-d',$D['interview_date']/1000).' '.$D['interview_end_time'].':00');
            $InviteAninterviewModel->remarks            =   $D['remarks'];
            $PushTaskData=[
                'jobs_name'         =>  $JobsModel->title,
                'company_name'      =>  $JobsModel->company_name,
                'time'              =>  date('Y-m-d',$InviteAninterviewModel->interview_date).' '.date('H:i',$InviteAninterviewModel->interview_start_time).'~'.date('H:i',$InviteAninterviewModel->interview_end_time),
                'address'           =>  $InviteAninterviewModel->address,
                'contacts'          =>  $InviteAninterviewModel->contacts,
                'contacts_mobile'   =>  $InviteAninterviewModel->contacts_mobile,
                'remarks'           =>  $InviteAninterviewModel->remarks,
            ];
            $PushTaskModel=new PushTaskModel;
            $PushTaskModel->event       =   'InviteAnInterview';
            $PushTaskModel->uid         =   $JobsDeliveryResumeModel->uid;
            $PushTaskModel->data        =   json_encode($PushTaskData,JSON_UNESCAPED_UNICODE);

            $UserVipRuleLogModel=new UserVipRuleLogModel;
            $UserVipRuleLogModel->uid       =$JobsModel->uid;
            $UserVipRuleLogModel->title     =$JobsModel->title.'职位邀请面试';
            $UserVipRuleLogModel->value     =1;
            $UserVipModel=UserVipModel::where(['uid'=>$JobsModel->uid])->find();
            $UserVipModel->update_vip=1;
            $UserVipRuleModel=UserVipRuleModel::alias('rule')
            ->where(['rule.uid'=>$UserVipModel->uid,'rule.status'=>1])
            ->join(config('databse.prefix').'vip vip','vip.id=rule.vid')
            ->join('vip_rule_value value','value.id=rule.rid')
            ->whereTime('rule.expiry_time','>',time())->where(['vip.is_company'=>1,'value.alias'=>'invite-aninterview'])
            ->field('rule.id,rule.surplus_value')
            ->order('rule.expiry_time asc,rule.surplus_value asc,rule.level asc')
            ->find();
            $UserVipRuleModel->surplus_value=Db::raw('surplus_value-1');
            // 启动事务
            Db::startTrans();
            try {
                $InviteAninterviewModel->save();
                $JobsDeliveryResumeModel->save();
                $PushTaskModel->save();
                $UserVipRuleLogModel->save();
                $UserVipRuleModel->save();
                // 提交事务
                Db::commit();
                return parent::ajaxReturn('邀请已发送');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return parent::ajaxReturn('邀请失败，请刷新重试',MsgCode::$error);
            }
        }else return parent::ajaxReturn('数据不存在',MsgCode::$error);
    }
    public static function getDownloadsFile($D)
    {
        $ResumeDownloadedModel=ResumeDownloadedModel::where(['id'=>$D['id'],'company_id'=>$D['company_id'],'status'=>1])->find();
        if ($ResumeDownloadedModel) {
            $ResumeModel=ResumeModel::where(['id'=>$ResumeDownloadedModel->resume_id])->field('id,name,file_name')->find();
            $path=config('xy_resume.resume_docx_path');
            $file_path=$path.$ResumeModel->file_name.'.docx';
            if (!file_exists($file_path)){
                $createResumeDocxRet=self::createResumeDocx($ResumeModel->id,$ResumeModel->file_name);
                if($createResumeDocxRet!==true)
                    return $createResumeDocxRet;
            }
            return download($file_path, $ResumeModel->name.'的简历.docx'); 
        }else{
            return '';
        }
    }
    public static function getDownloadsInfo($D)
    {
        if (!$D['uid'])
            return parent::ajaxReturn('请先登录',MsgCode::$error);
        if (!$D['resume_id'])
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        if (!$D['company_id'])
            return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        $CompanyModel=CompanyModel::where(['id'=>$D['company_id']])->field('id,uid,attestation')->find();
        if (!$CompanyModel) {
            return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        }else{
            switch (config('xy_resume.company_download_resume')) {
                case 1:
                    if ($CompanyModel->attestation!=3)
                        return parent::ajaxReturn('请先完成企业认证',MsgCode::$error);
                    break;
                case 2:
                    if (JobsModel::where(['company_id'=>$CompanyModel->id])->count()<=0)
                        return parent::ajaxReturn('请先发布职位后在下载',MsgCode::$error);
                    break;
            }
        }
        $ResumeModel=ResumeModel::where(['id'=>$D['resume_id']])->find();
        $download_resume_sum_30m=config('xy_company.download_resume_sum_30m');
        if($download_resume_sum_30m){
            $download_resume_sum=ResumeDownloadedModel::where(['company_id'=>$CompanyModel->id])->whereTime('create_time',[time()-1800,time()])->count();
            if($download_resume_sum>=$download_resume_sum_30m)
            return parent::ajaxReturn('下载过于频繁，请稍后再试',MsgCode::$error);
        }
        $ResumeDownloadedModel=ResumeDownloadedModel::where(['resume_id'=>$ResumeModel->id,'company_id'=>$CompanyModel->id])->find();
        $Data=[];
        $Data['price']=config('xy_resume.one_resume_download_price');
        $Data['score_status']=config('xy_resume.one_resume_download_score_status');
        $Data['download_status']=config('xy_resume.one_resume_download_status');
        $Data['rule_value']=config('xy_resume.download_resume_rule_value');
        $VipRuleValueModel=VipRuleValueModel::where(['alias'=>'download-resume'])->field('id,title,unit')->find();

        $Data['download_rule_title']=$VipRuleValueModel->title;
        $Data['download_rule_nuit']=$VipRuleValueModel->unit;
        $Data['download_value']=UserVipRuleModel::where(['uid'=>$D['uid'],'rid'=>$VipRuleValueModel->id,'status'=>1])->whereTime('expiry_time','>',time())->sum('surplus_value');
        if ($ResumeDownloadedModel) {
            $Data['id']=$ResumeDownloadedModel->id;
            if ($ResumeDownloadedModel->status) {
                $Data['type']='download';
            }else{
                $Data['type']='pay';
            }
            return parent::ajaxReturn('获取下载信息成功',MsgCode::$success,$Data);
        }else{
            $today_down_resume=UserVipRuleModel::alias('rule')
            ->where(['rule.uid'=>$CompanyModel->uid,'rule.status'=>1])
            ->join(config('databse.prefix').'vip vip','vip.id=rule.vid')
            ->join('vip_rule_value value','value.id=rule.rid')
            ->whereTime('rule.expiry_time','>',time())->order('rule.level desc')->field('rule.level,value.unit,rule.surplus_value')->where(['vip.is_company'=>1,'value.alias'=>'today-down-resume'])->find();
            if($today_down_resume&&ResumeDownloadedModel::where(['company_id'=>$CompanyModel->id])->whereDay('create_time')->count()>=$today_down_resume->surplus_value){
                return parent::ajaxReturn('每日下载简历上限：'.$today_down_resume->surplus_value.$today_down_resume->unit,MsgCode::$error);
            }
            $ResumeDownloadedModel=new ResumeDownloadedModel;
            $ResumeDownloadedModel->resume_id       = $ResumeModel->id;
            $ResumeDownloadedModel->company_id      = $CompanyModel->id;
            if ($ResumeDownloadedModel->save()) {
                $Data['id']=$ResumeDownloadedModel->id;
                $Data['type']='pay';
                return parent::ajaxReturn('获取下载信息成功',MsgCode::$success,$Data);
            }else return parent::ajaxReturn('获取下载信息失败，请重试',MsgCode::$error);
        }
    }
    public static function createResumeDocx($resume_id,$file_name)
    {
        $path=config('xy_resume.resume_docx_path');
        if (!file_exists($path))
            mkdir($path, 0777, true);
        if ($file_name) {
            $file_path=$path.$file_name.'.docx';
            if (file_exists($file_path)) return true;
        }else{
            $file_name=md5(Str::random(4).'&XYCMS&'.$resume_id.'&xycms&'.Str::random(4));
            $file_path=$path.$file_name.'.docx';
            $ResumeModel=ResumeModel::where(['id'=>$resume_id])->field('id,file_name')->find();
            $ResumeModel->file_name=$file_name;
            $ResumeModel->save();
        }
        if (!config('xy_resume.download_resume_tpl'))
            return '未设置简历模板文件';
        if (!file_exists(config('xy_resume.download_resume_tpl')))
            return '简历模板文件不存在';

        $Resume=self::getCreateDocxResumeInfo($resume_id);
        $tmp=new TemplateProcessor(config('xy_resume.download_resume_tpl'));
        foreach ($Resume as $k => $v) {
            if (is_array($v)) {
                $arr=[
                    'educational_experience',
                    'project_experience',
                    'work_experience'
                ];
                if (in_array($k, $arr)) {
                    $tmp->setValue($k.'_block','');
                    $tmp->setValue('/'.$k.'_block','');
                    $tmp->cloneRow($k,count($v));
                    foreach ($v as $ke => $va) {
                        $tmp->setValue($k."#".($ke+1),'');
                        foreach ($va as $key => $val) {
                        $tmp->setValue($k.'.'.$key."#".($ke+1),$val);
                        }
                    }
                }
            }else{
                if ($k==='headimg') {
                    $tmp->setImageValue($k,['path'=>$v,'width'=>160,'height'=>200]);
                }else{
                    $tmp->setValue($k,$v);
                }
            }
        }
        $tmp->saveAs($file_path);
        return file_exists($file_path)?true:'生成简历文件失败，请重试';
    }
    public static function delResumeFile($resume_id)
    {
        $ResumeModel=ResumeModel::where(['id'=>$resume_id])->field('file_name')->find();
        if ($ResumeModel) {
            if ($ResumeModel->file_name) {
                $path=config('xy_resume.resume_docx_path');
                $file_path=$path.$ResumeModel->file_name.'.docx';
                if (file_exists($file_path))
                    @unlink($file_path);
            }

        }
    }
    public static function getCompanyDownloadList($company_id,$where=[])
    {
        $ResumeDownloadedModel=ResumeDownloadedModel::alias('d')->where(['d.company_id'=>$company_id])
            ->where($where)
            ->whereNull('d.company_delete_time')
            ->where(['edu.alias'=>'resume/educational_background'])
            ->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')->paginate(15)
            ->each(function($item, $key)use($company_id){
                return $item;
            });
        return $ResumeDownloadedModel;
    }
    public static function getResumeCollectionList($company_id,$where=[])
    {
        $ResumeCollectionModel=ResumeCollectionModel::alias('c')->where(['c.company_id'=>$company_id])
            ->where($where)
            ->where(['edu.alias'=>'resume/educational_background'])
            ->join('resume resume','resume.id=c.resume_id')
            ->join('status_alias edu','edu.value=resume.educational_background')
            ->order('c.id desc')
            ->field('c.*,resume.name,resume.sex,resume.age,resume.work_experience_time,edu.title as educational_background')->paginate(15)
            ->each(function($item, $key)use($company_id){
                return $item;
            });
        return $ResumeCollectionModel;
    }
    public static function getResumeBrowseList($company_id,$where=[])
    {
        $ResumeBrowseModel=ResumeBrowseModel::alias('b')->where(['b.company_id'=>$company_id])
            ->where($where)
            ->whereNull('b.company_delete_time')
            ->where(['edu.alias'=>'resume/educational_background'])
            ->join('resume resume','resume.id=b.resume_id')
            ->join('status_alias edu','edu.value=resume.educational_background')
            ->order('b.id desc')
            ->field('b.*,resume.name,resume.sex,resume.age,resume.work_experience_time,edu.title as educational_background')->paginate(15)
            ->each(function($item, $key){
                return $item;
            });
        return $ResumeBrowseModel;
    }
    public static function getComapnyBrowseList($resume_id,$where=[])
    {
        $CompanyBrowseModel=CompanyBrowseModel::alias('b')->where(['b.resume_id'=>$resume_id])
            ->where($where)
            ->whereNull('b.delete_time')
            ->join('company company','company.id=b.company_id')
            ->order('b.id desc')
            ->field('b.*,company.title as company_name,b.create_time as update_time')->paginate(15)
            ->each(function($item, $key){
                return $item;
            });
        return $CompanyBrowseModel;
    }
    public static function delDownloadResume($D)
    {
        $where[]=['id','=',$D['id']];
        if ($D['role_type']) {
            $where[]=['company_id','=',$D['company_id']];
        }else{
            $where[]=['resume_id','=',$D['resume_id']];
        }
        $ResumeDownloadedModel=ResumeDownloadedModel::where($where)->find();
        if ($ResumeDownloadedModel) {
            if ($D['role_type']){
                $ResumeDownloadedModel->company_delete_time=time();
            }else{
                $ResumeDownloadedModel->personal_delete_time=time();
            }
            if ($ResumeDownloadedModel->save()) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('记录不存在，请刷新重试',MsgCode::$error);
    }
    public static function toggleResumeCollection($D)
    {
        $ResumeCollectionModel=ResumeCollectionModel::where(['resume_id'=>$D['id'],'company_id'=>$D['company_id']])->find();
        if ($ResumeCollectionModel) {
            if ($ResumeCollectionModel->delete()) {
                return parent::ajaxReturn('已取消关注');
            }else return parent::ajaxReturn('取消关注失败，请重试',MsgCode::$error);
        }else{
            $ResumeCollectionModel=new ResumeCollectionModel;
            $ResumeCollectionModel->resume_id=$D['id'];
            $ResumeCollectionModel->company_id=$D['company_id'];
            if ($ResumeCollectionModel->save()) {
                return parent::ajaxReturn('已关注');
            }else return parent::ajaxReturn('关注失败，请重试',MsgCode::$error);
        }
    }
    public static function delCollectedResume($D)
    {
        $where[]=['id','=',$D['id']];
        $where[]=['company_id','=',$D['company_id']];
        $ResumeCollectionModel=ResumeCollectionModel::where($where)->find();
        if ($ResumeCollectionModel) {
            if ($ResumeCollectionModel->delete()) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('记录不存在，请刷新重试',MsgCode::$error);
    }
    public static function delBrowseResume($D)
    {
        $where[]=['id','=',$D['id']];
        if ($D['role_type']) {
            $where[]=['company_id','=',$D['company_id']];
        }else{
            $where[]=['resume_id','=',$D['resume_id']];
        }
        $ResumeBrowseModel=ResumeBrowseModel::where($where)->find();
        if ($ResumeBrowseModel) {
            if ($D['role_type']){
                $ResumeBrowseModel->company_delete_time=time();
            }else{
                $ResumeBrowseModel->personal_delete_time=time();
            }
            if ($ResumeBrowseModel->save()) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('记录不存在，请刷新重试',MsgCode::$error);
    }
    public static function statistics($D)
    {
        if ($D['role_type'] && $D['company_id']) {
            $resume_sum=JobsDeliveryResumeModel::where(['company_id'=>$D['company_id']])->count();
            $not_resume_sum=JobsDeliveryResumeModel::where(['company_id'=>$D['company_id'],'status'=>0])->count();
            return parent::ajaxReturn('',MsgCode::$success,[
                'resume_sum'            =>  $resume_sum, 
                'not_resume_sum'        =>  $not_resume_sum,
                'resume_efficiency'     =>  ($resume_sum-$not_resume_sum)>0?round(($resume_sum-$not_resume_sum)/$resume_sum*100):0
            ]);
        }
        return parent::ajaxReturn('',MsgCode::$error);
    }
    public static function setResumePrivacy($D)
    {
        $ResumeModel=ResumeModel::where(['id'=>$D['resume_id']])->find();
        if ($ResumeModel) {
            $ResumeModel->privacy=$D['status'];
            if ($ResumeModel->save()) {
                return parent::ajaxReturn('已保存',MsgCode::$success);
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('请先创建简历',MsgCode::$error);
    }
    public static function setResumeHeadimgStatus($D)
    {
        $ResumeModel=ResumeModel::where(['id'=>$D['resume_id']])->find();
        if ($ResumeModel) {
            $ResumeModel->headimg_status=$D['status'];
            if ($ResumeModel->save()) {
                return parent::ajaxReturn('已保存',MsgCode::$success);
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('请先创建简历',MsgCode::$error);
    }
    /**
     * 保存作品照片
     */
    public static function saveResumeWorks($D)
    {
        $ResumeWorksModel=new ResumeWorksModel;
        $ResumeWorksList=[];
        if (!empty($D['works'])) {
            foreach ($D['works'] as $k => $v) {
                $ResumeWorksList[$k]=[
                    'resume_id'             =>  $D['resume_id'],
                    'title'                 =>  $v['title'],
                    'path'                  =>  $v['path'],
                ];
                if ($v['id'])
                    $ResumeWorksList[$k]['id']=$v['id'];
            }
        }
        if (!empty($ResumeWorksList)) {
            if($ResumeWorksModel->saveAll($ResumeWorksList)){
                return parent::ajaxReturn('保存成功');
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('数据为空，保存失败',MsgCode::$error);
    }
    /**
     * 保存作品照片备注
     */
    public static function saveResumeWorksTitle($D)
    {
        if (empty($D['id']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        $resume_id=$D['resume_id'];
        if (!$resume_id)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        $Model=ResumeWorksModel::where(['id'=>$D['id'],'resume_id'=>$resume_id])->find();
        $Model->title=$D['title'];
        if ($Model->save()) {
            return parent::ajaxReturn();
        }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
    }
    /**
     * 删除作品照片照片
     */
    public static function delResumeWorks($D)
    {
        if (empty($D['id']))
            return parent::ajaxReturn('数据校验失败，请刷新重试[-101]',MsgCode::$error);
        $resume_id=$D['resume_id'];
        if (!$resume_id)
            return parent::ajaxReturn('请先登录',MsgCode::$login);
        $Model=new ResumeWorksModel;
        $Data=$Model->where(['id'=>$D['id'],'resume_id'=>$resume_id])->field('id')->find();
        if ($Data) {
            if ($Model::destroy($Data->id)) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('删除失败，请刷新重试',MsgCode::$error);
        }else return parent::ajaxReturn('数据不存在',MsgCode::$error);
    }
    /**
     * [getJobHuntingIntention 获取求职意向]
     * @param  [type] $D [description]
     * @return [type]    [description]
     */
    public static function getJobHuntingIntention($D)
    {
        if (!$D['resume_id'])
            return parent::ajaxReturn('请先创建简历',MsgCode::$error);
        $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::alias('e')->where(['e.resume_id'=>$D['resume_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','LEFT')
            ->join('jobs_cate jobs_cate2','jobs_cate2.id=e.jobscate2','LEFT')
            ->join('jobs_cate jobs_cate3','jobs_cate3.id=e.jobscate3','LEFT')
            ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work','LEFT')
            ->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.*,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')->select();
        if ($ResumeEmploymentIntentionModel) {
            return parent::ajaxReturn('',MsgCode::$success,$ResumeEmploymentIntentionModel);
        }else{
            return parent::ajaxReturn('不存在求职意向',MsgCode::$error);
        }
    }
    /**
     * [getJobHuntingIntentionFind 获取求职意向]
     * @param  [type] $D [description]
     * @return [type]    [description]
     */
    public static function getJobHuntingIntentionFind($D)
    {
        if (!$D['resume_id'])
            return parent::ajaxReturn('请先创建简历',MsgCode::$error);
        $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::alias('e')->where(['e.id'=>$D['id'],'e.resume_id'=>$D['resume_id']])
            ->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('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.*,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();
        if($ResumeEmploymentIntentionModel){
            $ResumeEmploymentIntentionModel->expected_salary=[
                $ResumeEmploymentIntentionModel->salary_min,
                $ResumeEmploymentIntentionModel->salary_max
            ];
            $ResumeEmploymentIntentionModel->job_area=[];
            if($ResumeEmploymentIntentionModel->job_area1
                &&$ResumeEmploymentIntentionModel->job_area2
                &&$ResumeEmploymentIntentionModel->job_area3){
                $ResumeEmploymentIntentionModel->job_area=[
                    $ResumeEmploymentIntentionModel->job_area1,
                    $ResumeEmploymentIntentionModel->job_area2,
                    $ResumeEmploymentIntentionModel->job_area3
                ];
            }
            $ResumeEmploymentIntentionModel->jobscate=[
                $ResumeEmploymentIntentionModel->jobscate1,
                $ResumeEmploymentIntentionModel->jobscate2,
                $ResumeEmploymentIntentionModel->jobscate3
            ];
        }
        if ($ResumeEmploymentIntentionModel) {
            return parent::ajaxReturn('',MsgCode::$success,$ResumeEmploymentIntentionModel);
        }else{
            return parent::ajaxReturn('不存在求职意向',MsgCode::$error);
        }
    }
    /**
     * [saveJobHuntingIntention 保存求职意向]
     * @param  [type] $D [description]
     * @return [type]    [description]
     */
    public static function saveJobHuntingIntention($D)
    {
        $is_edit=false;
        if(isset($D['id']) && $D['id'])
            $is_edit=true;
        if (!$D['resume_id'])
            return parent::ajaxReturn('请先创建简历',MsgCode::$error);
        if (empty($D['jobscate']) && count($D['jobscate'])<3)
            return parent::ajaxReturn('请选择职位分类',MsgCode::$error);
        if ($is_edit)
            $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::where(['id'=>$D['id'],'resume_id'=>$D['resume_id']])->Find();
        $count=ResumeEmploymentIntentionModel::where(['resume_id'=>$D['resume_id'],'default'=>1])->count();
        if (!$is_edit || ($is_edit && !$ResumeEmploymentIntentionModel)){
            if (ResumeEmploymentIntentionModel::where(['resume_id'=>$D['resume_id']])->count()>=3)
                return parent::ajaxReturn('求职意向已达上限',MsgCode::$error);
            $ResumeEmploymentIntentionModel=new ResumeEmploymentIntentionModel;
            $ResumeEmploymentIntentionModel->resume_id  =   $D['resume_id'];
            $ResumeEmploymentIntentionModel->default        =   $count<=0?1:0;
        }
        $ResumeEmploymentIntentionModel->nature_of_work =   $D['nature_of_work'];
        $ResumeEmploymentIntentionModel->industry_id    =   $D['industry_id'];
        $ResumeEmploymentIntentionModel->jobscate1      =   $D['jobscate'][0];
        $ResumeEmploymentIntentionModel->jobscate2      =   $D['jobscate'][1];
        $ResumeEmploymentIntentionModel->jobscate3      =   $D['jobscate'][2];
        if(!empty($D['job_area'])&&count($D['job_area'])>=3){
        $ResumeEmploymentIntentionModel->job_area1      =   $D['job_area'][0];
        $ResumeEmploymentIntentionModel->job_area2      =   $D['job_area'][1];
        $ResumeEmploymentIntentionModel->job_area3      =   $D['job_area'][2];
        }
        if(!empty($D['expected_salary'])&&count($D['expected_salary'])>=2){
            $ResumeEmploymentIntentionModel->salary_min     =   $D['expected_salary'][0];
            $ResumeEmploymentIntentionModel->salary_max     =   $D['expected_salary'][1];
        }

        if ($ResumeEmploymentIntentionModel->save()) {
            return parent::ajaxReturn('保存成功',MsgCode::$success);
        }else{
            return parent::ajaxReturn('保存失败',MsgCode::$error);
        }
    }
    public static function delJobHuntingIntention($D)
    {
        if (ResumeEmploymentIntentionModel::where(['resume_id'=>$D['resume_id']])->count()<=1)
            return parent::ajaxReturn('最低需保留一项求职意向',MsgCode::$error);
        $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::where(['id'=>$D['id'],'resume_id'=>$D['resume_id']]);
        if($ResumeEmploymentIntentionModel->delete()){
            $count=ResumeEmploymentIntentionModel::where(['resume_id'=>$D['resume_id'],'default'=>1])->count();
            if($count<=0){
                $ResumeEmploymentIntentionModel=ResumeEmploymentIntentionModel::where(['resume_id'=>$D['resume_id']])->find();
                $ResumeEmploymentIntentionModel->default=1;
                $ResumeEmploymentIntentionModel->save();
            }
            return parent::ajaxReturn('已删除',MsgCode::$success);
        }else{
            return parent::ajaxReturn('删除失败',MsgCode::$error);
        }
    }
    public static function getContactsData($D)
    {
        $view_jobs_type=false;
        switch (config('xy_resume.view_resume_type')) {
            case 1:
                if(!$D['uid'])
                    return parent::ajaxReturn('请先登录',MsgCode::$login);
                break;
            case 2:
                if(!$D['uid'])
                    return parent::ajaxReturn('请先登录',MsgCode::$login);
                if(!$D['role_type'])
                    return parent::ajaxReturn('当前不是企业身份，是否切换？',MsgCode::$roleTypeCompany);
                if(!$D['company_id'])
                    return parent::ajaxReturn('您还未完善企业信息，是否现在去完善？',MsgCode::$company);
                $ResumeDownloadModel=ResumeDownloadedModel::where(['resume_id'=>$D['id'],'company_id'=>$D['company_id'],'status'=>1])->count();
                if(!$ResumeDownloadModel)
                    return parent::ajaxReturn('您还未下载简历，是否现在下载？',MsgCode::$confirm);
                break;
            default:
                $view_jobs_type=true;
                break;
        }
        $UserModel=ResumeModel::alias('resume')->where(['resume.id'=>$D['id']])
        ->join('user user','user.id=resume.uid')
        ->field('resume.name,user.mobile')->find();
        if($UserModel){
            return parent::ajaxReturn('',MsgCode::$success,$UserModel);
        }else{
            return parent::ajaxReturn('获取联系方式失败',MsgCode::$error);
        }
    }
    public static function getSearchResume($D)
    {
        $where=[];
        if(is_numeric($D['key'])){
            $where[]=['id','=',$D['key']];
        }else{
            $where[]=['name','like','%'.$D['key'].'%'];
        }
        $ResumeModel=ResumeModel::where($where)->where('uid', 'NOTIN', function ($query)use($D) {
                $query->name('company_blacklist')->where(['uid'=>$D['uid']])->field('to_uid');
            })->field('id,uid,name')->limit(10)->select();
        if($ResumeModel){
            return parent::ajaxReturn('',MsgCode::$success,$ResumeModel);
        }else{
            return parent::ajaxReturn('暂无数据',MsgCode::$error);
        }
    }
}
