<?php
namespace app\common\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Db;
use app\common\variable\MsgCode;
use app\common\validate\Jobs as JobsValidate;
use app\common\validate\JobsContact as JobsContactValidate;
use think\exception\ValidateException;
use app\common\model\Jobs as JobsModel;
use app\common\model\JobsDesc as JobsDescModel;
use app\common\model\JobsContacts as JobsContactsModel;
use app\common\model\Company as CompanyModel;
use app\common\model\CompanyContent as CompanyContentModel;
use app\common\model\StatusAlias as StatusAliasModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\JobsBrowse as JobsBrowseModel;
use app\common\model\ResumeSpecialtyLabel as ResumeSpecialtyLabelModel;
use app\common\model\JobsCollection as JobsCollectionModel;
use app\common\model\JobsRefreshAuto as JobsRefreshAutoModel;
use app\common\model\UserVipRuleLog as UserVipRuleLogModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\PushTask as PushTaskModel;
use app\common\controller\Posters as PostersController;
use helper\Geohash;
use gaode\Gaode;
use gaode\request\Geocode;
/**
 * 
 */
class Jobs extends Base
{
    public static function releaseJobs($D)
    {
        /**
         * 公司基本信息验证
         */
        try {
            validate(JobsValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        /**
         * 公司拓展信息验证
         */
        if (!$D['contacts_type']) {
            try {
                validate(JobsContactValidate::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);
        $CompanyModel=CompanyModel::where(['uid'=>$uid])->field('id,uid,attestation')->find();
        if (!$CompanyModel)
            return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        if (config('xy_company.is_forceattestation')&&$CompanyModel->attestation!=3)
            return parent::ajaxReturn('请先完成企业认证',MsgCode::$error);
        $jobs_sum=JobsModel::where(['company_id'=>$CompanyModel->id])->count();
        $release_jobs_sum=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,rule.surplus_value')->where(['vip.is_company'=>1,'value.alias'=>'release-jobs'])->find();
        if(!$release_jobs_sum)
            return parent::ajaxReturn('当前职位发布已达到上限',MsgCode::$vip);
        if ($release_jobs_sum&&$release_jobs_sum->surplus_value<=$jobs_sum)
            return parent::ajaxReturn('当前职位发布已达到上限：'.$release_jobs_sum->surplus_value,MsgCode::$vip);
        /**
         * 职位基本信息
         */
        $JobsModel=new JobsModel;
        $JobsModel->app_id              =   $D['app_id'];
        $JobsModel->company_id          =   $CompanyModel->id;
        $JobsModel->title               =   trimall($D['title']);
        $JobsModel->jobs_type           =   $D['jobs_type'];
        $JobsModel->jobs_area1          =   $D['jobs_area'][0];
        $JobsModel->jobs_area2          =   $D['jobs_area'][1];
        $JobsModel->jobs_area3          =   $D['jobs_area'][2];
        $JobsModel->jobs_cate1          =   $D['jobs_cid'][0];
        $JobsModel->jobs_cate2          =   $D['jobs_cid'][1];
        $JobsModel->jobs_cate3          =   $D['jobs_cid'][2];
        $JobsModel->salary_min          =   $D['salary'][0];
        $JobsModel->salary_max          =   $D['salary'][1];
        $JobsModel->salary_year         =   empty($D['salary_year'])?12:$D['salary_year'];
        $JobsModel->education_level     =   $D['education_level'];
        $JobsModel->exp_level           =   $D['exp_level'];
        $JobsModel->number_of_recruiters=   intval($D['number_of_recruiters'],0);
        $JobsModel->refresh_time        =   time();
        if (!empty($D['jobs_welfare'])) {
            $JobsModel->jobs_welfare        =   implode(",", $D['jobs_welfare']);
        }
        $JobsDescModel=new JobsDescModel;
        $JobsDescModel->jobs_desc=$D['jobs_desc'];
        /**
         * 职位联系人信息
         */
        $JobsContactsModel=new JobsContactsModel;
        $JobsContactsModel->contacts             =   trimall($D['contacts']);
        $JobsContactsModel->contacts_mobile      =   $D['contacts_mobile'];
        $JobsContactsModel->contacts_tel         =   $D['contacts_tel'];
        $JobsContactsModel->contacts_email       =   $D['contacts_email'];
        $JobsContactsModel->contacts_address     =   trimall($D['contacts_address']);
        $JobsContactsModel->contacts_type        =   $D['contacts_type'];
        $CompanyContentModel=CompanyContentModel::where(['cid'=>$CompanyModel->id])->find();
        $JobsContactsModel->contacts_lng=$CompanyContentModel->contacts_lng;
        $JobsContactsModel->contacts_lat=$CompanyContentModel->contacts_lat;
        $JobsContactsModel->contacts_geohash=$CompanyContentModel->contacts_geohash;
        if (!$JobsContactsModel->contacts_type) {
            if(config('xy_map.server_status')){
                $ProvinceModel=AreaModel::where(['id'=>$JobsModel->jobs_area1])->find();
                $CityModel=AreaModel::where(['id'=>$JobsModel->jobs_area2])->find();
                $AreaModel=AreaModel::where(['id'=>$JobsModel->jobs_area3])->find();
                try {
                    $Gaode=new Gaode;
                    $Geocode=new Geocode($Gaode->_config);
                    $Geocode->province=$ProvinceModel->title;
                    $Geocode->city=$CityModel->title;
                    $Geocode->area=$AreaModel->title;
                    $Geocode->address=$JobsContactsModel->contacts_address;
                    $ret=$Geocode->geo();
                    $location=explode(',',$ret->location);
                    $JobsContactsModel->contacts_lng=$location[0];
                    $JobsContactsModel->contacts_lat=$location[1];
                    $JobsContactsModel->contacts_geohash=$Geohash->encode($location[1],$location[0]);
                } catch (Exception $e) {
                }
            }
        }
        $AdminPushTaskModel=new PushTaskModel;
        $AdminPushTaskModel->event       =   'SystemWarning';
      
        // 启动事务
        Db::startTrans();
        try {
            $JobsModel->save();
            $JobsDescModel->jobs_id=$JobsModel->id;
            $JobsDescModel->save();
            $JobsContactsModel->jobs_id=$JobsModel->id;
            $JobsContactsModel->save();
            $PushData=[
                'tpl'       =>'jobs_examine',
                'level'     =>'职位审核',
                'range'     =>'后台',
                'time'      =>date('Y-m-d H:i:s'),
                'msg'       =>'职位ID:'.$JobsModel->id
            ];
            $AdminPushTaskModel->data        =   json_encode($PushData,JSON_UNESCAPED_UNICODE);
            $AdminPushTaskModel->save();
            // 提交事务
            Db::commit();
            Cache::set('updateUser:'.$CompanyModel->uid,true);
            return parent::ajaxReturn('发布成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('发布失败，请重试',MsgCode::$error);
        }
    }
    public static function saveJobs($D)
    {
        /**
         * 公司基本信息验证
         */
        try {
            validate(JobsValidate::class)->check($D);
        } catch (ValidateException $e) {
            return parent::ajaxReturn($e->getError(),MsgCode::$error);
        }
        /**
         * 公司拓展信息验证
         */
        if (!$D['contacts_type']) {
            try {
                validate(JobsContactValidate::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);
        $CompanyModel=CompanyModel::where(['uid'=>$uid])->field('id')->find();
        if (!$CompanyModel)
            return parent::ajaxReturn('请先完善企业信息',MsgCode::$error);
        /**
         * 职位基本信息
         */
        $JobsModel=JobsModel::where(['id'=>$D['id'],'company_id'=>$CompanyModel->id])->find();
        if (!$JobsModel)
            return parent::ajaxReturn('该职位不存在',MsgCode::$error);
        $JobsModel->title               =   trimall($D['title']);
        $JobsModel->jobs_type           =   $D['jobs_type'];
        $JobsModel->jobs_area1          =   $D['jobs_area'][0];
        $JobsModel->jobs_area2          =   $D['jobs_area'][1];
        $JobsModel->jobs_area3          =   $D['jobs_area'][2];
        $JobsModel->jobs_cate1          =   $D['jobs_cid'][0];
        $JobsModel->jobs_cate2          =   $D['jobs_cid'][1];
        $JobsModel->jobs_cate3          =   $D['jobs_cid'][2];
        $JobsModel->salary_min          =   $D['salary'][0];
        $JobsModel->salary_max          =   $D['salary'][1];
        $JobsModel->salary_year         =   empty($D['salary_year'])?12:$D['salary_year'];
        $JobsModel->education_level     =   $D['education_level'];
        $JobsModel->exp_level           =   $D['exp_level'];
        $JobsModel->number_of_recruiters=   intval($D['number_of_recruiters'],0);
        if (!empty($D['jobs_welfare'])) {
            $JobsModel->jobs_welfare        =   implode(",", $D['jobs_welfare']);
        }else{
            $JobsModel->jobs_welfare        =   '';
        }
        $AdminPushTaskModel=null;
        if (config('xy_company.edit_jobs_status')){
            $JobsModel->examine=0;
            $AdminPushTaskModel=new PushTaskModel;
            $AdminPushTaskModel->event       =   'SystemWarning';
            $PushData=[
                'tpl'       =>'jobs_examine',
                'level'     =>'职位审核',
                'range'     =>'后台',
                'time'      =>date('Y-m-d H:i:s'),
                'msg'       =>'职位ID:'.$JobsModel->id
            ];
            $AdminPushTaskModel->data        =   json_encode($PushData,JSON_UNESCAPED_UNICODE);
        }
        $JobsDescModel=JobsDescModel::where(['jobs_id'=>$JobsModel->id])->find();
        if(!$JobsDescModel){
            $JobsDescModel=new JobsDescModel;
            $JobsDescModel->jobs_id=$JobsModel->id;
        }
        $JobsDescModel->jobs_desc=$D['jobs_desc'];
        /**
         * 职位联系人信息
         */
        $JobsContactsModel=JobsContactsModel::where(['jobs_id'=>$JobsModel->id])->find();
        $JobsContactsModel->contacts             =   trimall($D['contacts']);
        $JobsContactsModel->contacts_mobile      =   $D['contacts_mobile'];
        $JobsContactsModel->contacts_tel         =   $D['contacts_tel'];
        $JobsContactsModel->contacts_email       =   $D['contacts_email'];
        $JobsContactsModel->contacts_address     =   trimall($D['contacts_address']);
        $JobsContactsModel->contacts_type        =   $D['contacts_type'];
        $CompanyContentModel=CompanyContentModel::where(['cid'=>$CompanyModel->id])->find();
        $JobsContactsModel->contacts_lng=$CompanyContentModel->contacts_lng;
        $JobsContactsModel->contacts_lat=$CompanyContentModel->contacts_lat;
        $JobsContactsModel->contacts_geohash=$CompanyContentModel->contacts_geohash;
        if (!$JobsContactsModel->contacts_type) {
            if(config('xy_map.server_status')){
                $ProvinceModel=AreaModel::where(['id'=>$JobsModel->jobs_area1])->find();
                $CityModel=AreaModel::where(['id'=>$JobsModel->jobs_area2])->find();
                $AreaModel=AreaModel::where(['id'=>$JobsModel->jobs_area3])->find();
                try {
                    $Gaode=new Gaode;
                    $Geocode=new Geocode($Gaode->_config);
                    $Geocode->province=$ProvinceModel->title;
                    $Geocode->city=$CityModel->title;
                    $Geocode->area=$AreaModel->title;
                    $Geocode->address=$JobsContactsModel->contacts_address;
                    $ret=$Geocode->geo();
                    $location=explode(',',$ret->location);
                    $JobsContactsModel->contacts_lng=$location[0];
                    $JobsContactsModel->contacts_lat=$location[1];
                    $JobsContactsModel->contacts_geohash=$Geohash->encode($location[1],$location[0]);
                } catch (Exception $e) {
                }
            }
        }
      
        // 启动事务
        Db::startTrans();
        try {
            $JobsModel->save();
            $JobsContactsModel->save();
            $JobsDescModel->save();
            if($AdminPushTaskModel)$AdminPushTaskModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('保存成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }
    }
    public static function getJobsInfo($id,$D=[])
    {
        $Field=[
            'jobs.*',
            'desc.jobs_desc',
            'contacts.jobs_id,contacts.contacts,contacts.contacts_mobile,contacts.contacts_tel,contacts.contacts_email,contacts.contacts_address,contacts.contacts_lng,contacts.contacts_lat,contacts.contacts_lng,contacts.contacts_type',
            'company.uid,company.title as company_name,company.stitle as company_sname,company.logo as company_logo,company.attestation',
            'education.title as education_level',
            'exp_level.title as exp_level',
            'user_timer.online_time',
            'province.title as jobs_province,city.title as jobs_city,area.title as jobs_area',
            'jobs_cate.title as jobs_cate_text',
            'nature.title as nature,finance.title as finance,size_type.title as size_type,industry.title as industry',
        ];
        $where=['jobs.id'=>$id];
        if(empty($D['is_admin'])){
            $where=[['jobs.id','=',$id],['jobs.status','=',1]];
            if(config('xy_company.jobs_view_status')){
                $where[]=['jobs.examine','=',1];
            }else{
                $where[]=['jobs.examine','in',[0,1]];
            }
            if(config('xy_company.is_forceattestation'))
            $where[]=['company.attestation','=',3];
        }
        $JobsModel=JobsModel::alias('jobs')
        ->where($where)
        ->whereNull('jobs.delete_time')
        ->where(['education.alias'=>'jobs/education_level'])
        ->where(['exp_level.alias'=>'jobs/exp_level'])
        ->where(['nature.alias'=>'company/nature'])
        ->where(['finance.alias'=>'company/finance'])
        ->where(['size_type.alias'=>'company/size_type'])
        ->join('company company','company.id=jobs.company_id')
        ->join('jobs_cate jobs_cate','jobs_cate.id=jobs.jobs_cate3')
        ->join('user_timer user_timer','user_timer.uid = company.uid','LEFT')
        ->join('jobs_desc desc','desc.jobs_id=jobs.id','LEFT')
        ->join('jobs_contacts contacts','contacts.jobs_id=jobs.id','LEFT')
        ->join('status_alias education','education.value=jobs.education_level')
        ->join('status_alias exp_level','exp_level.value=jobs.exp_level','LEFT')
        ->join('status_alias nature','nature.value=company.nature')
        ->join('status_alias finance','finance.value=company.finance')
        ->join('status_alias size_type','size_type.value=company.size_type')
        ->join('company_industry industry','industry.id = company.industry_id')
        ->join('area province','province.id = jobs.jobs_area1','LEFT')
        ->join('area city','city.id = jobs.jobs_area2','LEFT')
        ->join('area area','area.id = jobs.jobs_area3','LEFT')
        ->withAttr('jobs_welfare',function($v,$d){
            $welfare=StatusAliasModel::where([['alias','=','company/corporate_welfare'],['value','in',arrtoint(explode(",", $v))]])->column('title');
            return $welfare;
        })
        ->withAttr('company_logo',function($v,$d){
            return $v?config('web.imgurl').$v:config('web.imgurl').config('xy_default_avatar.company_logo');
        })
        ->withAttr('jobs_desc',function($v,$d)use($D){
            if (isset($D['html']) && $D['html']) {
                return str_replace("\n",'<br/>',$v);
            }else{
                return $v;
            }
        })
        ->withAttr('refresh_time',function($v,$d){
            return friendly_time($v,'friendly');
        })
        ->withAttr('online_time',function($v,$d){
            return friendly_time($v,'friendly');
        })
        ->field(implode(',',$Field))->find();
        if ($JobsModel) {
            $company_content=CompanyContentModel::alias('content')->where(['content.cid'=>$JobsModel->company_id])
            ->join('area province','province.id = content.contacts_area2','LEFT')
            ->join('area city','city.id = content.contacts_area1','LEFT')
            ->join('area area','area.id = content.contacts_area3','LEFT')
            ->field('content.contacts,content.contacts_mobile,content.contacts_tel,content.contacts_email,content.contacts_address,content.contacts_lng,content.contacts_lat,province.title as company_province,city.title as company_city,area.title as company_area')
            ->find();
            if ($JobsModel->contacts_type) {
                $JobsModel->contacts_province   =$company_content->company_province;
                $JobsModel->contacts_city       =$company_content->company_city;
                $JobsModel->contacts_area       =$company_content->company_area;
                $JobsModel->contacts            =$company_content->contacts;
                $JobsModel->contacts_mobile     =$company_content->contacts_mobile;
                $JobsModel->contacts_tel        =$company_content->contacts_tel;
                $JobsModel->contacts_email      =$company_content->contacts_email;
                $JobsModel->contacts_address    =$company_content->contacts_address;
                $JobsModel->contacts_lon        =$company_content->contacts_lng;
                $JobsModel->contacts_lat        =$company_content->contacts_lat;
            }
            $JobsModel->company_province=$company_content->company_province;
            $JobsModel->company_city=$company_content->company_city;
            $JobsModel->company_area=$company_content->company_area;
            $JobsModel->company_address    =$company_content->contacts_address;
            $JobsModel->contacts_mobile=substr_replace($JobsModel->contacts_mobile,'****',3,4);
            $JobsModel->delivery_resume=JobsDeliveryResumeModel::where(['jobs_id'=>$JobsModel->id])->count();
            $JobsModel->is_delivery=0;
            $JobsModel->count_jobs=JobsModel::where(['company_id'=>$JobsModel->company_id,'status'=>1])->count();
            $resume_sum=JobsDeliveryResumeModel::where(['company_id'=>$JobsModel->company_id])->count();
            $not_resume_sum=JobsDeliveryResumeModel::where(['company_id'=>$JobsModel->company_id,'status'=>0])->count();
            $JobsModel->resume_efficiency=($resume_sum-$not_resume_sum)>0?round(($resume_sum-$not_resume_sum)/$resume_sum*100):0;
            if (!empty($D['uid'])) 
                $JobsModel->is_delivery=JobsDeliveryResumeModel::where(['jobs_id'=>$JobsModel->id,'uid'=>$D['uid']])->count();
            if (!empty($D['resume_id']))
                $JobsModel->is_collection=JobsCollectionModel::where(['jobs_id'=>$JobsModel->id,'resume_id'=>$D['resume_id']])->count();
            $PostersModel=new \StdClass;
            $PostersModel->size=140;
            $JobsModel->qr_code=PostersController::CreateJobsQRCode($JobsModel,$PostersModel);
            $JobsModel->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
        }
        return $JobsModel;
    }
    public static function getJobsInfoAll($D)
    {
        $Field=[
            'jobs.*',
            'desc.jobs_desc',
            'contacts.*'
        ];
        $JobsModel=JobsModel::alias('jobs')
        ->where(['jobs.id'=>$D['id'],'company_id'=>$D['company_id']])
        ->whereNull('jobs.delete_time')
        ->join('jobs_desc desc','desc.jobs_id=jobs.id','LEFT')
        ->join('jobs_contacts contacts','contacts.jobs_id=jobs.id','LEFT')
        ->field(implode(',',$Field))->find();
        $Data=[];
        if ($JobsModel) {
            $Data=$JobsModel->toArray();
            $Data['jobs_welfare']=$JobsModel->jobs_welfare?arrtoint(explode(",", $JobsModel->jobs_welfare)):[];
            $Data['jobs_cid']=[];
            $Data['jobs_cid'][]=$JobsModel->jobs_cate1;
            $Data['jobs_cid'][]=$JobsModel->jobs_cate2;
            $Data['jobs_cid'][]=$JobsModel->jobs_cate3;
            $Data['jobs_area']=[];
            $Data['jobs_area'][0]=$JobsModel->jobs_area1;
            $Data['jobs_area'][1]=$JobsModel->jobs_area2;
            $Data['jobs_area'][2]=$JobsModel->jobs_area3;
            $Data['salary']=[];
            $Data['salary'][]=$JobsModel->salary_min;
            $Data['salary'][]=$JobsModel->salary_max;
        }
        return $Data;
    }
    public static function getJobsList($D=[])
    {
        $where=[];
        if (!empty($D['key']))
            $where[]=['jobs.title','like','%'.$D['key'].'%'];
        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[]=['jobs.jobs_cate2','=',intval($cate[1])];
                        break;
                    case 2:
                        if(intval($cate[2]))
                        $where[]=['jobs.jobs_cate3','=',intval($cate[2])];
                        break;
                    default:
                        if(intval($cate[0]))
                        $where[]=['jobs.jobs_cate1','=',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[]=['jobs.jobs_cate2','=',intval($cate[1])];
                        break;
                    case 2:
                        if(intval($cate[2]))
                        $where[]=['jobs.jobs_cate3','=',intval($cate[2])];
                        break;
                    default:
                        if(intval($cate[0]))
                        $where[]=['jobs.jobs_cate1','=',intval($cate[0])];
                        break;
                }
            }else{
                if(intval($D['cid']))
                $where[]=['jobs.jobs_cate3','=',intval($D['cid'])];
            }
        }
        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[]=['jobs.salary_min','>',0];
                $where[]=['jobs.salary_min','>=',intval($D['salary_min'])];
                $where[]=['jobs.salary_max','<=',intval($D['salary_max'])];
            }else{
                $where[]=['jobs.salary_min','=',0];
                $where[]=['jobs.salary_max','=',100];
            }
        }elseif(isset($D['salary_min'])&&is_numeric($D['salary_min'])){
            if($D['salary_min']>0){
                $where[]=['jobs.salary_min','>=',intval($D['salary_min'])];
            }else{
                $where[]=['jobs.salary_min','=',0];
                $where[]=['jobs.salary_max','=',100];
            }
        }elseif(isset($D['salary_max'])&&is_numeric($D['salary_min'])){
            $where[]=['jobs.salary_max','<=',intval($D['salary_max'])];
        }
        if (!empty($D['company_id']))
            $where[]=['jobs.company_id','=',intval($D['company_id'])];
        if (!empty($D['notin'])){
            $notin=explode(',',$D['notin']);
            if (!empty($notin)) 
            $where[]=['jobs.id','notin',$notin];
        }
        if (!empty($D['province']))
            $where[]=['jobs.jobs_area1','=',intval($D['province'])];
        if (!empty($D['city']))
            $where[]=['jobs.jobs_area2','=',intval($D['city'])];
        if (!empty($D['area']))
            $where[]=['jobs.jobs_area3','=',intval($D['area'])];
        
        if (!empty($D['industry']) && $D['industry'])
            $where[]=['c.industry_id','=',intval($D['industry'])];
        if (!empty($D['size_type']) && $D['size_type'])
            $where[]=['c.size_type','=',intval($D['size_type'])];
        if (isset($D['jobs_type'])&&$D['jobs_type']!='')
            $where[]=['jobs.jobs_type','=',intval($D['jobs_type'])];
        if (isset($D['education_level'])&&$D['education_level']!='')
            $where[]=['jobs.education_level','=',intval($D['education_level'])];
        if (isset($D['exp_level'])&&$D['exp_level']!='')
            $where[]=['jobs.exp_level','=',intval($D['exp_level'])];
        if (!empty($D['finance']) && $D['finance'])
            $where[]=['c.finance','=',intval($D['finance'])];
        if (!empty($D['is_famous']) && $D['is_famous']!=0)
            $where[]=['c.is_famous','=',intval($D['is_famous'])];
        if (!empty($D['urgent']) && $D['urgent']!='all')
            $where[]=['jobs.urgent','=',intval($D['urgent'])];
        $Geohash=null;
        if((!empty($D['lng'])&&!empty($D['lat']))
            ||(isset(request()->lng)&&isset(request()->lat))){
            $Geohash=new Geohash;
            if (!empty($D['lng'])&&!empty($D['lat'])) {
            $Geohash->lng=$D['lng'];
            $Geohash->lat=$D['lat'];
            $hash=$Geohash->encode($D['lat'],$D['lng']);
            }else{
            $Geohash->lng=request()->lng;
            $Geohash->lat=request()->lat;
            $hash=$Geohash->encode(request()->lat,request()->lng);
            }
            $range=6;
            if (!empty($D['range'])) {
                switch(strtolower($D['range'])){
                    case '1km':
                        $range=6;
                        break;
                    case '3km':
                        $range=5;
                        break;
                }
            }
            if($hash)
            $where[]=['contacts.contacts_geohash','like',substr($hash,0,$range).'%'];
        }
        $sort='jobs.urgent desc,jobs.top desc,jobs.refresh_time desc,jobs.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='jobs.urgent desc,jobs.refresh_time desc,jobs.top desc,jobs.id desc';
                    break;
                case 'recommend':
                    $sort='jobs.urgent desc,jobs.top desc,jobs.recommend desc,jobs.refresh_time desc,jobs.id desc';
                    break;
                case 'rand':
                    $sort='jobs.urgent desc,jobs.refresh_time desc,jobs.id rand()';
                    break;
            }
        }
        $Field=[
            'jobs.id,jobs.title,jobs.update_time,jobs.create_time,jobs.salary_min,jobs.salary_max,jobs.salary_year,jobs.jobs_welfare,jobs.company_id,jobs.refresh_time,jobs.view,jobs.top,jobs.recommend,jobs.urgent',
            'c.title as company_name,c.stitle as scompany_name,c.logo,c.attestation',
            'contacts.contacts_lng,contacts.contacts_lat',
            'industry.title as industry',
            'province.title as jobs_province',
            'city.title as jobs_city',
            'area.title as jobs_area',
            'size_type.title as size_type',
            'education.title as education',
            'exp_level.title as exp_level'
        ];

        if (isset(request()->sub_industry))
            $where[]=['c.industry_id','=',request()->sub_industry];
        if (isset(request()->sub_province))
            $where[]=['jobs.jobs_area1','=',request()->sub_province];
        if (isset(request()->sub_city))
            $where[]=['jobs.jobs_area2','=',request()->sub_city];
        if (isset(request()->sub_area))
            $where[]=['jobs.jobs_area3','=',request()->sub_area];
        if(config('xy_company.jobs_view_status')){
            $where[]=['jobs.examine','=',1];
        }else{
            $where[]=['jobs.examine','in',[0,1]];
        }
        if(config('xy_company.is_forceattestation'))
            $where[]=['c.attestation','=',3];
        $JobsModel=JobsModel::alias('jobs')
            ->where(['jobs.status'=>1])
            ->whereNull('jobs.delete_time')
            ->where($where);
            if (isset($D['update_time'])) {
                switch ($D['update_time']) {
                    case 1:
                        $JobsModel->whereDay('jobs.refresh_time','today');
                        break;
                    case 2:
                        $JobsModel->whereDay('jobs.refresh_time',date('Y-m-d',time()-(3600*24*3)));
                        break;
                    case 3:
                        $JobsModel->whereDay('jobs.refresh_time',date('Y-m-d',time()-(3600*24*7)));
                        break;
                }
            }
        if(!empty($D['uid'])){
            $JobsModel->where('c.uid', 'NOTIN', function ($query)use($D) {
                $query->name('resume_blacklist')->where(['uid'=>$D['uid']])->field('to_uid');
            });
            $JobsModel->where('c.uid', 'NOTIN', function ($query)use($D) {
                $query->name('company_blacklist')->where(['to_uid'=>$D['uid']])->field('uid');
            });
        }
        $Data=$JobsModel->where(['size_type.alias'=>'company/size_type'])
            ->where(['education.alias'=>'jobs/education_level'])
            ->where(['exp_level.alias'=>'jobs/exp_level'])
            ->join('company c','c.id=jobs.company_id')
            ->join('jobs_contacts contacts','contacts.jobs_id=jobs.id')
            ->join('company_industry industry','industry.id=c.industry_id')
            ->join('status_alias size_type','size_type.value=c.size_type')
            ->join('status_alias education','education.value=jobs.education_level')
            ->join('status_alias exp_level','exp_level.value=jobs.exp_level')
            ->join('area province','province.id = jobs.jobs_area1')
            ->join('area city','city.id = jobs.jobs_area2')
            ->join('area area','area.id = jobs.jobs_area3')
            ->order($sort)
            ->field(implode(',',$Field))->paginate(15)
            ->each(function($item, $key)use($D,$Geohash){
                $item->friendly_create_time=friendly_time($item['refresh_time'],'friendly');
                $item->welfare=$item['jobs_welfare']?StatusAliasModel::where(['alias'=>'company/corporate_welfare'])->where('value','in',explode(',',$item['jobs_welfare']))->column('title'):[];
                $item->is_delivery=JobsDeliveryResumeModel::where(['jobs_id'=>$item['id'],'uid'=>$D['uid']])->count();
                if (!empty($D['resume_id']))
                    $item->is_collection=JobsCollectionModel::where(['jobs_id'=>$item['id'],'resume_id'=>$D['resume_id']])->count();
                $item->logo=$item['logo']?config('web.imgurl').$item['logo']:config('web.imgurl').config('xy_default_avatar.company_logo');
                if ($Geohash!==null)
                    $item->distance=$Geohash->getDistance($item->contacts_lat,$item->contacts_lng,$Geohash->lat,$Geohash->lng);
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
            });
        return $Data;
    }
    public static function getSelect($D=[])
    {
        $where=[];
        if (!empty($D['key']))
            $where[]=['jobs.title','like','%'.$D['key'].'%'];
        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[]=['jobs.jobs_cate2','=',intval($cate[1])];
                        break;
                    case 2:
                        if(intval($cate[2]))
                        $where[]=['jobs.jobs_cate3','=',intval($cate[2])];
                        break;
                    default:
                        if(intval($cate[0]))
                        $where[]=['jobs.jobs_cate1','=',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[]=['jobs.jobs_cate2','=',intval($cate[1])];
                        break;
                    case 2:
                        if(intval($cate[2]))
                        $where[]=['jobs.jobs_cate3','=',intval($cate[2])];
                        break;
                    default:
                        if(intval($cate[0]))
                        $where[]=['jobs.jobs_cate1','=',intval($cate[0])];
                        break;
                }
            }else{
                if(intval($D['cid']))
                $where[]=['jobs.jobs_cate3','=',intval($D['cid'])];
            }
        }
        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[]=['jobs.salary_min','>',0];
                $where[]=['jobs.salary_min','>=',intval($D['salary_min'])];
                $where[]=['jobs.salary_max','<=',intval($D['salary_max'])];
            }else{
                $where[]=['jobs.salary_min','=',0];
                $where[]=['jobs.salary_max','=',100];
            }
        }elseif(isset($D['salary_min'])&&is_numeric($D['salary_min'])){
            if($D['salary_min']>0){
                $where[]=['jobs.salary_min','>=',intval($D['salary_min'])];
            }else{
                $where[]=['jobs.salary_min','=',0];
                $where[]=['jobs.salary_max','=',100];
            }
        }elseif(isset($D['salary_max'])&&is_numeric($D['salary_min'])){
            $where[]=['jobs.salary_max','<=',intval($D['salary_max'])];
        }
        if (!empty($D['company_id']))
            $where[]=['jobs.company_id','=',intval($D['company_id'])];
        if (!empty($D['city']))
            $where[]=['jobs.jobs_area2','=',intval($D['city'])];
        if (!empty($D['industry']) && $D['industry'])
            $where[]=['c.industry_id','=',intval($D['industry'])];
        if (!empty($D['size_type']) && $D['size_type'])
            $where[]=['c.size_type','=',intval($D['size_type'])];
        if (isset($D['jobs_type'])&&$D['jobs_type']!='')
            $where[]=['jobs.jobs_type','=',intval($D['jobs_type'])];
        if (isset($D['education_level'])&&$D['education_level']!='')
            $where[]=['jobs.education_level','=',intval($D['education_level'])];
        if (isset($D['exp_level'])&&$D['exp_level']!='')
            $where[]=['jobs.exp_level','=',intval($D['exp_level'])];
        if (!empty($D['finance']) && $D['finance'])
            $where[]=['c.finance','=',intval($D['finance'])];
        if (!empty($D['is_famous']) && $D['is_famous']!=0)
            $where[]=['c.is_famous','=',intval($D['is_famous'])];
        if (!empty($D['is_high_salary'])){
            if(config('xy_company.high_salary')){
                $where[]=['jobs.salary_min','>',config('xy_company.high_salary')];
            }else{
                $where[]=['jobs.salary_min','>',10];
            }
        }
        if (!empty($D['is_hot'])){
            if(config('xy_company.jobs_hot')){
                $where[]=['jobs.delivery_resume','>',config('xy_company.jobs_hot')];
            }else{
                $where[]=['jobs.delivery_resume','>',10];
            }
        }
        if (!empty($D['is_recommend']))
            $where[]=['jobs.recommend','=',1];
        $sort='jobs.urgent desc,jobs.top desc,jobs.refresh_time desc,jobs.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='jobs.urgent desc,jobs.refresh_time desc,jobs.top desc,jobs.id desc';
                    break;
                case 'recommend':
                    $sort='jobs.urgent desc,jobs.top desc,jobs.recommend desc,jobs.refresh_time desc,jobs.id desc';
                    break;
                case 'rand':
                    $sort='jobs.urgent desc,jobs.refresh_time desc,jobs.id rand()';
                    break;
            }
        }
        $Field=[
            'jobs.id,jobs.id as is_delivery,jobs.id as is_collection,jobs.title,jobs.update_time,jobs.refresh_time,jobs.salary_min,jobs.salary_max,jobs.salary_year,jobs.jobs_welfare,jobs.company_id,jobs.view,jobs.top,jobs.recommend,jobs.urgent',
            'c.title as company_name,c.stitle as scompany_name,c.logo,c.attestation',
            'industry.title as industry',
            'city.title as jobs_city',
            'size_type.title as size_type',
            'education.title as education',
            'exp_level.title as exp_level'
        ];
        if (isset(request()->sub_industry))
            $where[]=['c.industry_id','=',request()->sub_industry];
        if (isset(request()->sub_province))
            $where[]=['jobs.jobs_area1','=',request()->sub_province];
        if (isset(request()->sub_city))
            $where[]=['jobs.jobs_area2','=',request()->sub_city];
        if (isset(request()->sub_area))
            $where[]=['jobs.jobs_area3','=',request()->sub_area];
        if(config('xy_company.jobs_view_status')){
            $where[]=['jobs.examine','=',1];
        }else{
            $where[]=['jobs.examine','in',[0,1]];
        }
        if(config('xy_company.is_forceattestation'))
            $where[]=['c.attestation','=',3];
        $JobsModel=JobsModel::alias('jobs')
            ->where(['jobs.status'=>1])
            ->whereNull('jobs.delete_time')
            ->where($where);
            if (isset($D['update_time'])) {
                switch ($D['update_time']) {
                    case 1:
                        $JobsModel->whereDay('jobs.refresh_time','today');
                        break;
                    case 2:
                        $JobsModel->whereDay('jobs.refresh_time',date('Y-m-d',time()-(3600*24*3)));
                        break;
                    case 3:
                        $JobsModel->whereDay('jobs.refresh_time',date('Y-m-d',time()-(3600*24*7)));
                        break;
                }
            }
        if(!empty($D['uid'])){
            $JobsModel->where('c.uid', 'NOTIN', function ($query)use($D) {
                $query->name('resume_blacklist')->where(['uid'=>$D['uid']])->field('to_uid');
            });
            $JobsModel->where('c.uid', 'NOTIN', function ($query)use($D) {
                $query->name('company_blacklist')->where(['to_uid'=>$D['uid']])->field('uid');
            });
        }
        $Data=$JobsModel->where(['size_type.alias'=>'company/size_type'])
            ->where(['education.alias'=>'jobs/education_level'])
            ->where(['exp_level.alias'=>'jobs/exp_level'])
            ->join('company c','c.id=jobs.company_id')
            ->join('company_industry industry','industry.id=c.industry_id')
            ->join('status_alias size_type','size_type.value=c.size_type')
            ->join('status_alias education','education.value=jobs.education_level')
            ->join('status_alias exp_level','exp_level.value=jobs.exp_level')
            ->join('area city','city.id = jobs.jobs_area2')
            ->order($sort)
            ->field(implode(',',$Field))->limit($D['length'])
            ->withAttr('refresh_time',function($v,$data){
                return friendly_time($v,'friendly');
            })
            ->withAttr('jobs_welfare',function($v,$data){
                return $v?StatusAliasModel::where(['alias'=>'company/corporate_welfare'])->where('value','in',explode(',',$v))->column('title'):[];
            })
            ->withAttr('is_delivery',function($v,$data)use($D){
                return JobsDeliveryResumeModel::where(['jobs_id'=>$v,'uid'=>$D['uid']])->count();
            })
            ->withAttr('is_collection',function($v,$data)use($D){
                if (!empty($D['resume_id'])){
                    return JobsCollectionModel::where(['jobs_id'=>$v,'resume_id'=>$D['resume_id']])->count();
                }else{
                    return 0;
                }
            })
            ->withAttr('logo',function($v,$data){
                return $v?config('web.imgurl').$v:config('web.imgurl').config('xy_default_avatar.company_logo');
            })->select();
        if ($Data) {
            foreach ($Data as $item) {
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
            }
        }
        return $Data;
    }
    public static function getCompanyJobsList($company_id,$where=[])
    {
        $JobsModel=JobsModel::alias('jobs')->where(['jobs.company_id'=>$company_id])
            ->where($where)
            ->where(['education.alias'=>'jobs/education_level'])
            ->where(['exp_level.alias'=>'jobs/exp_level'])
            ->whereNull('jobs.delete_time')
            ->join('area city','city.id = jobs.jobs_area2')
            ->join('status_alias education','education.value=jobs.education_level')
            ->join('status_alias exp_level','exp_level.value=jobs.exp_level')
            ->order('jobs.id desc')
            ->field('jobs.*,city.title as jobs_city,education.title as education,exp_level.title as exp_level')->paginate(15)
            ->each(function($item, $key){
                $item['refresh_time']=friendly_time($item['refresh_time'],'friendly');
                $item['top_time']=$item->top_time?date('m-d H:i',$item->top_time):'';
                $item['recommend_time']=$item->recommend_time?date('m-d H:i',$item->recommend_time):'';
                $item['urgent_time']=$item->urgent_time?date('m-d H:i',$item->urgent_time):'';
                $item['resume_to_be_processed']=JobsDeliveryResumeModel::where(['jobs_id'=>$item['id'],'status'=>0])->count();
                $item['auto_refresh']=JobsRefreshAutoModel::where(['jobs_id'=>$item['id'],'status'=>1])->withAttr('start_time',function($v,$data){
                        return date('Y-m-d H:i:s',$v);
                    })->withAttr('end_time',function($v,$data){
                        return date('Y-m-d H:i:s',$v);
                    })->withAttr('next_time',function($v,$data){
                        return date('H:i:s',$v);
                    })->find();
                $item->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
                return $item;
            });
        return $JobsModel;
    }
    public static function getPersonalJobsBrowse($resume_id)
    {
        $JobsBrowseModel=JobsBrowseModel::alias('p')->where(['p.resume_id'=>$resume_id])
            ->join('jobs jobs','jobs.id=p.jobs_id')
            ->join('company company','company.id=jobs.company_id')
            ->order('p.id desc')
            ->field('p.id,jobs.title,p.jobs_id,p.create_time as update_time,company.id as company_id,company.title as company_name')->paginate(15)
            ->each(function($item, $key){
                return $item;
            });
        return $JobsBrowseModel;
    }
    public static function getCompanyJobsBrowse($D)
    {
        $Field=[
            'p.id,jobs.title as jobs_title,p.jobs_id,p.resume_id,p.create_time,resume.name',
            'resume.id,resume.name,resume.sex,resume.age,resume.educational_background,resume.work_experience_time,resume.progress,resume.headimg_status',
            'e.salary_min,e.salary_max',
            'nature_of_work.title as nature_of_work',
            'job_status.title as job_status',
            'industry.title as industry',
            'city.title as job_city',
            'educational_background.title as educational_background',
            'self_description.self_description',
            'user_info.headimg'
        ];
        $sort='resume.refresh_time desc,p.id desc';
        if (!empty($D['prop'])){
            switch ($D['prop']) {
                case 'update_time':
                    $sort='p.create_time desc,p.id desc';
                    break;
                case 'recommend':
                    $sort='resume.progress desc,resume.refresh_time desc,resume.id desc';
                    break;
            }
        }
        $where=[];
        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['educational_background']))
            $where[]=['resume.educational_background','=',intval($D['educational_background'])];
        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;
            }
        }
        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(config('xy_resume.resume_view_status'))
            $where[]=['resume.examine','=',1];
        $where[]=['resume.privacy','=',1];
        if(config('xy_resume.resume_role_type'))
            $where[]=['user_info.role_type','=',0];
        $JobsBrowseModel=JobsBrowseModel::alias('p')->where(['p.company_id'=>$D['company_id']])->where($where);

        if(!empty($D['uid'])){
            $JobsBrowseModel->where('resume.uid', 'NOTIN', function ($query)use($D) {
                $query->name('company_blacklist')->where(['uid'=>$D['uid']])->field('to_uid');
            });
            $JobsBrowseModel->where('resume.uid', 'NOTIN', function ($query)use($D) {
                $query->name('resume_blacklist')->where(['to_uid'=>$D['uid']])->field('uid');
            });
        }
        $JobsBrowse=$JobsBrowseModel->join('jobs jobs','jobs.id=p.jobs_id')
            ->join('company company','company.id=p.company_id')
            ->join('resume resume','resume.id=p.resume_id')
            ->where(['educational_background.alias'=>'resume/educational_background'])
            ->where(['nature_of_work.alias'=>'resume/nature_of_work'])
            ->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')
            ->join('resume_self_description self_description','self_description.resume_id=resume.id')
            ->join('company_industry industry','industry.id=e.industry_id','LEFT')
            ->join('status_alias educational_background','educational_background.value=resume.educational_background')
            ->join('status_alias nature_of_work','nature_of_work.value=e.nature_of_work')
            ->join('status_alias job_status','job_status.value=resume.job_status')
            ->join('area city','city.id = e.job_area2','LEFT')
            ->order($sort)
            ->field(implode(',',$Field))->paginate(15)
            ->each(function($item, $key){
                $name=mb_substr($item['name'],0,1,'utf-8');
                switch ($item['sex']) {
                    case 1:
                        $nickname='先生';
                        break;
                    case 2:
                        $nickname='女士';
                        break;
                }
                $item['name']=$name.$nickname;
                $item['age']=getWorkExpYear($item['age']);
                $item['work_experience_time']=getWorkExpYear($item['work_experience_time']);
                $item['friendly_time']=friendly_time($item['create_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->jobs_salary_show_type=config('xy_company.jobs_salary_show_type');
                return $item;
            });
        return $JobsBrowse;
    }
    public static function setJobsStatus($D)
    {
        $JobsModel=JobsModel::where(['id'=>$D['id'],'company_id'=>$D['company_id']])->find();
        if ($JobsModel) {
            $JobsModel->status=$D['status'];
            if ($D['status']==2)
                $JobsModel->delete_time=time();
            if ($JobsModel->save()) {
                return parent::ajaxReturn();
            }else return parent::ajaxReturn('保存失败，请重试',MsgCode::$error);
        }else return parent::ajaxReturn('职位不存在，请刷新重试',MsgCode::$error);
    }
    public static function setJobsRefreshTime($D)
    {
        $JobsModel=JobsModel::where(['id'=>$D['id'],'company_id'=>$D['company_id']])->find();
            $JobsModel=JobsModel::alias('jobs')->where(['jobs.id'=>$D['id'],'jobs.company_id'=>$D['company_id']])
            ->join('company company','company.id=jobs.company_id')
            ->field('jobs.id,jobs.title,jobs.status,jobs.refresh_time,company.uid')->find();
        if (!$JobsModel)
            return parent::ajaxReturn('职位不存在，请刷新重试',MsgCode::$error);
        if ($JobsModel->status!==1)
            return parent::ajaxReturn('职位未开启，请先开启在刷新',MsgCode::$error);
        $refresh_time=time()-$JobsModel->refresh_time;
        $jobs_refresh_interval=config('xy_company.jobs_refresh_interval');
        if ($refresh_time<$jobs_refresh_interval*60)
            return parent::ajaxReturn('刷新冷却中，请'.($jobs_refresh_interval*60-$refresh_time).'秒后再试',MsgCode::$error);
        $refresh_sum=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'=>'refresh-sum'])->sum('rule.surplus_value');
        if($refresh_sum<=0)
            return parent::ajaxReturn('刷新次数不足',MsgCode::$vip);
        $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'=>'refresh-sum'])
        ->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');
        $JobsModel->refresh_time=time();
        // 启动事务
        Db::startTrans();
        try {
            $JobsModel->save();
            $UserVipModel->save();
            $UserVipRuleLogModel->save();
            $UserVipRuleModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('刷新成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('刷新失败，请刷新重试',MsgCode::$error);
        }
    }
    public static function setCompanyJobsRefreshTime($D)
    {
        $refresh_sum=UserVipRuleModel::alias('rule')
            ->where(['rule.uid'=>$D['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'=>'refresh-sum'])->sum('rule.surplus_value');
        if($refresh_sum<=0)
            return parent::ajaxReturn('刷新次数不足',MsgCode::$vip);
        $JobsModel=new JobsModel;
        $JobsModelData=JobsModel::where(['company_id'=>$D['company_id'],'status'=>1])->field('id,refresh_time')->limit($refresh_sum)->select()->toArray();
        if (!$JobsModelData)
            return parent::ajaxReturn('无可刷新的职位',MsgCode::$error);
        $RefreshID=[];
        foreach ($JobsModelData as $k => $v) {
            $refresh_time=time()-$v['refresh_time'];
            $jobs_refresh_interval=config('xy_company.jobs_refresh_interval');
            if ($refresh_time>$jobs_refresh_interval*60){
                $JobsModelData[$k]['refresh_time']=time();
                $RefreshID[]=$v['id'];
            }else{
                unset($JobsModelData[$k]);
            }
        }
        if(empty($JobsModelData))
            return parent::ajaxReturn('无可刷新的职位',MsgCode::$error);
        $UserVipRuleLogModel=new UserVipRuleLogModel;
        $UserVipRuleLogModel->uid       =$D['uid'];
        $UserVipRuleLogModel->title     ='刷新ID('.implode(',',$RefreshID).')职位';
        $UserVipRuleLogModel->value     =1;
        $UserVipModel=UserVipModel::where(['uid'=>$D['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'=>'refresh-sum'])
        ->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-'.count($JobsModelData));
        $JobsModel->refresh_time=time();
        // 启动事务
        Db::startTrans();
        try {
            $JobsModel->saveAll($JobsModelData);
            $UserVipModel->save();
            $UserVipRuleLogModel->save();
            $UserVipRuleModel->save();
            // 提交事务
            Db::commit();
            return parent::ajaxReturn('刷新成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return parent::ajaxReturn('刷新失败，请刷新重试',MsgCode::$error);
        }
    }
    public static function toggleJobsCollection($D)
    {
        $JobsCollectionModel=JobsCollectionModel::where(['resume_id'=>$D['resume_id'],'jobs_id'=>$D['jobs_id']])->find();
        if ($JobsCollectionModel) {
            if ($JobsCollectionModel->delete()) {
                return parent::ajaxReturn('已取消收藏');
            }else return parent::ajaxReturn('取消收藏失败，请重试',MsgCode::$error);
        }else{
            $JobsCollectionModel=new JobsCollectionModel;
            $JobsCollectionModel->resume_id=$D['resume_id'];
            $JobsCollectionModel->jobs_id=$D['jobs_id'];
            if ($JobsCollectionModel->save()) {
                return parent::ajaxReturn('已收藏');
            }else return parent::ajaxReturn('收藏失败，请重试',MsgCode::$error);
        }
    }
    public static function getContactsData($D)
    {
        $view_jobs_type=false;
        switch (config('xy_company.view_jobs_type')) {
            case 1:
                if(!$D['uid'])
                    return parent::ajaxReturn('请先登录',MsgCode::$login);
                break;
            case 2:
                if(!$D['uid'])
                    return parent::ajaxReturn('请先登录',MsgCode::$login);
                if(!$D['resume_id'])
                    return parent::ajaxReturn('您还未创建简历，是否现在去创建？',MsgCode::$resume);
                break;
            case 3:
                if(!$D['uid'])
                    return parent::ajaxReturn('请先登录',MsgCode::$login);
                if(!$D['resume_id'])
                    return parent::ajaxReturn('您还未创建简历，是否现在去创建？',MsgCode::$resume);
                $JobsDeliveryResumeModel=JobsDeliveryResumeModel::where(['jobs_id'=>$D['id'],'resume_id'=>$D['resume_id']])->count();
                if(!$JobsDeliveryResumeModel)
                    return parent::ajaxReturn('您还未投递简历，是否现在投递？',MsgCode::$confirm);
                break;
            default:
                $view_jobs_type=true;
                break;
        }
        $JobsModel=JobsModel::alias('jobs')->where(['jobs.id'=>$D['id']])
        ->join('jobs_contacts contacts','contacts.jobs_id=jobs.id')
        ->join('area province','province.id = jobs.jobs_area1','LEFT')
        ->join('area city','city.id = jobs.jobs_area2','LEFT')
        ->join('area area','area.id = jobs.jobs_area3','LEFT')
        ->field('jobs.company_id,contacts.*,province.title as jobs_province,city.title as jobs_city,area.title as jobs_area')->find();
        if($JobsModel){
            $company_content=CompanyContentModel::alias('content')->where(['content.cid'=>$JobsModel->company_id])->field('content.contacts,content.contacts_mobile,content.contacts_tel,content.contacts_email,content.contacts_address,content.contacts_lng,content.contacts_lat,province.title as jobs_province,city.title as jobs_city,area.title as jobs_area')
            ->join('area province','province.id = content.contacts_area1')
            ->join('area city','city.id = content.contacts_area2')
            ->join('area area','area.id = content.contacts_area3')
            ->find();
            if ($JobsModel->contacts_type) {
                $JobsModel->contacts        =$company_content->contacts;
                $JobsModel->contacts_mobile =$company_content->contacts_mobile;
                $JobsModel->contacts_tel    =$company_content->contacts_tel;
                $JobsModel->contacts_email  =$company_content->contacts_email;
                $JobsModel->contacts_address=$company_content->contacts_address;
                $JobsModel->jobs_province   =$company_content->jobs_province;
                $JobsModel->jobs_city       =$company_content->jobs_city;
                $JobsModel->jobs_area       =$company_content->jobs_area;
            }
            $JobsModel->contacts_lon=$company_content->contacts_lng;
            $JobsModel->contacts_lat=$company_content->contacts_lat;
            return parent::ajaxReturn('',MsgCode::$success,$JobsModel);
        }else{
            return parent::ajaxReturn('获取联系方式失败',MsgCode::$error);
        }
    }
}