<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\Session;
use think\facade\View;
use think\facade\Db;
use think\facade\Validate;
use app\common\controller\JobFair as JobFairController;
use app\common\model\JobFair as JobFairModel;
use app\common\model\JobFairBoothCate as JobFairBoothCateModel;
use app\common\model\JobFairBooth as JobFairBoothModel;
use app\common\model\JobFairCompany as JobFairCompanyModel;
use app\common\model\JobFairContacts as JobFairContactsModel;
use app\common\model\JobFairContent as JobFairContentModel;
use app\common\model\JobFairResume as JobFairResumeModel;
use app\common\model\JobFairVip as JobFairVipModel;
use app\common\controller\Vip as VipController;
use app\bsadmin\model\JobFairBoothStatus as JobFairBoothStatusModel;
use helper\Baidu;
class JobFair extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['title']) {
                $where[]=['job.title','like','%'.$G['title'].'%'];
            }
            if ($G['status']!='all') {
                $where[]=['job.status','=',$G['status']];
            }
            $Data=JobFairModel::alias('job')->where($where)
                ->field('job.*')
                ->order('job.id desc')->paginate($G['pageSize'])
                ->each(function($v){
                    if($v->sign_up_start_time&&$v->sign_up_end_time){
                        if($v->sign_up_start_time<=time()&&$v->sign_up_end_time>=time()){
                            $v->status=1;
                        }else{
                            $v->status=0;
                        }
                    }elseif ($v->sign_up_start_time) {
                        if($v->sign_up_start_time<=time()){
                            $v->status=1;
                        }else{
                            $v->status=0;
                        }
                    }elseif ($v->sign_up_end_time) {
                        if($v->sign_up_end_time>=time()){
                            $v->status=1;
                        }else{
                            $v->status=0;
                        }
                    }
                    if($v->start_time&&$v->end_time){
                        if($v->start_time<=time()&&$v->end_time>=time()){
                            $v->status=2;
                        }else{
                            $v->status=3;
                        }
                    }
                    $v['sign_up_start_time']=$v['sign_up_start_time']?date('Y-m-d H:m:s',$v['sign_up_start_time']):'';
                    $v['sign_up_end_time']=$v['sign_up_end_time']?date('Y-m-d H:m:s',$v['sign_up_end_time']):'';
                    $v['start_time']=$v['start_time']?date('Y-m-d H:m:s',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d H:m:s',$v['end_time']):'';
                    $v['thumb']=$v['thumb']?config('web.imgurl').$v['thumb']:'';
                    $v['banner']=$v['banner']?config('web.imgurl').$v['banner']:'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑文章
     */
    public function edit($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require',
                'content'       => 'require',
                'start_time'    => 'require',
                'end_time'      => 'require',
                'status'        => 'require',
                'thumb'         => 'require',
                'banner'        => 'require',
            ];
            $msg  =   [
                'title.require'         => '标题不能为空', 
                'start_time.require'    => '请选择开始时间', 
                'end_time.require'      => '请选择结束时间', 
                'content.require'       => '详情不能为空', 
                'status.require'        => '请选择状态',  
                'thumb.require'         => '请上传封面', 
                'banner.require'        => '请上传横幅', 
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            if(!$D['online_registration']||!$D['tel_registration']||!$D['offline_registration'])
                return $this->ajaxReturn('请选择一种报名方式',-100);
            $JobFairModel=JobFairModel::where(['id'=>$id])->find();
            $JobFairModel->title                = $D['title'];
            $JobFairModel->thumb                = $D['thumb'];
            $JobFairModel->banner               = $D['banner'];
            $JobFairModel->booth_img            = $D['booth_img'];
            $JobFairModel->status               = $D['status'];
            $JobFairModel->nature               = $D['nature'];
            $JobFairModel->online_registration  = $D['online_registration'];
            $JobFairModel->tel_registration     = $D['tel_registration'];
            $JobFairModel->offline_registration = $D['offline_registration'];
            $JobFairModel->sort                 = $D['sort'];
            $JobFairModel->is_all_sign_up       = $D['is_all_sign_up'];
            $JobFairModel->booth_sum            = $D['booth_sum'];
            if(strtotime($D['sign_up_start_time']))
            $JobFairModel->sign_up_start_time=strtotime($D['sign_up_start_time']);
            if(strtotime($D['sign_up_end_time']))
            $JobFairModel->sign_up_end_time=strtotime($D['sign_up_end_time']);
            if (strtotime($D['start_time']))
                $JobFairModel->start_time= strtotime($D['start_time']);
            if (strtotime($D['end_time']))
                $JobFairModel->end_time= strtotime($D['end_time']);

            if($D['offline_registration']&&(empty($D['job_fair_area'])||empty($D['address'])))
                return $this->ajaxReturn('当使用线下报名时必须地区和详细地址',-100);
            $JobFairContentModel=JobFairContentModel::where(['jid'=>$JobFairModel->id])->find();
            if(!empty($D['job_fair_area'])&&count($D['job_fair_area'])>=3){
                $JobFairContentModel->job_fair_area1=$D['job_fair_area'][0];
                $JobFairContentModel->job_fair_area2=$D['job_fair_area'][1];
                $JobFairContentModel->job_fair_area3=$D['job_fair_area'][2];
            }
            if(!empty($D['address']))
                $JobFairContentModel->address=$D['address'];
            $JobFairContentModel->lng=$D['lng'];
            $JobFairContentModel->lat=$D['lat'];
            $JobFairContentModel->transit=$D['transit'];
            $JobFairContentModel->content=$D['content'];
            $JobFairContentModel->about=$D['about'];
            $Contacts=[];
            if (!empty($D['contacts'])) {
                $JobFairContactsModel=new JobFairContactsModel;
                foreach ($D['contacts'] as $k => $v) {
                    $Contacts[$k]=[
                        'contacts'          =>  $v['contacts'],
                        'contacts_mobile'   =>  $v['contacts_mobile'],
                        'contacts_tel'      =>  $v['contacts_tel'],
                        'contacts_qq'       =>  $v['contacts_qq'],
                        'contacts_wechat'   =>  $v['contacts_wechat'],
                        'contacts_email'    =>  $v['contacts_email'],
                        'remarks'           =>  $v['remarks']
                    ];
                    if($v['id'])
                        $Contacts[$k]['id']=$v['id'];
                }
            }
            if($D['tel_registration']&&empty($Contacts))
                return $this->ajaxReturn('当使用电话报名时必须设置联系人',-100);
            $BoothCate=[];
            $Booth=[];
            if (!empty($D['booth'])) {
                $booth_json=json_decode($D['booth'],true);
                if (!empty($booth_json)){
                    $JobFairBoothModel=new JobFairBoothModel;
                    $JobFairBoothCateModel=new JobFairBoothCateModel;
                    foreach ($booth_json as $k => $v) {
                        $BoothCate[$k]=[
                            'name'              =>  empty($v['name'])?$v['identifier'].'区':$v['name'],
                            'identifier'        =>  $v['identifier'],
                            'sum'               =>  $v['sum'],
                            'price'             =>  $v['price'],
                            'specifications'    =>  $v['specifications']
                        ];
                        if($v['id'])
                            $BoothCate[$k]['id']=$v['id'];
                        $stock_sum=0;
                        foreach ($v['boothCate'] as $key => $booth) {
                            if($booth['id']){
                                $Booth[]=[
                                    'id'                =>  $booth['id'],
                                    'identifier'        =>  $v['identifier'],
                                    'index'             =>  $booth['index'],
                                    'price'             =>  $booth['price'],
                                    'specifications'    =>  $booth['specifications'],
                                    'status'            =>  $booth['status'],
                                ];
                            }else{
                                $Booth[]=[
                                    'identifier'        =>  $v['identifier'],
                                    'index'             =>  $booth['index'],
                                    'price'             =>  $booth['price'],
                                    'specifications'    =>  $booth['specifications'],
                                    'status'            =>  $booth['status'],
                                ];
                            }
                            if($booth['status'])
                                $stock_sum++;
                        }
                        $BoothCate[$k]['stock_sum']=$v['sum']-$stock_sum;
                    }
                }
            }
            if($D['online_registration']&&(empty($BoothCate)||empty($Booth)))
                return $this->ajaxReturn('当使用线上报名时必须设置展位',-100);
            $Vip=[];
            $VipController=VipController::getCate();
            $JobFairVipModel=new JobFairVipModel;
            $VipControllerIndex=0;
            foreach ($VipController as $v) {
                $Vip[$VipControllerIndex]=[
                    'vid'               =>  $v->id,
                    'level'             =>  $v->level,
                    'is_company'        =>  $v->is_company
                ];
                if($D['is_all_sign_up']){
                    $Vip[$VipControllerIndex]['status']=1;
                }else{
                    $Vip[$VipControllerIndex]['status']=in_array($D['vip'],$v->id)?1:0;
                }
                $VipControllerIndex++;
            }
            unset($D);
            unset($rule);
            unset($msg);
            unset($Validate);
            unset($result);
            unset($booth_json);
            unset($VipController);
            unset($VipControllerIndex);
            // 启动事务
            Db::startTrans();
            try {
                $JobFairModel->save();
                $JobFairContentModel->jid=$JobFairModel->id;
                $JobFairContentModel->save();
                if (!empty($Contacts)) {
                    array_walk($Contacts,function(&$v,$k)use($JobFairModel){
                        $v['jid']=$JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairContactsModel->saveAll($Contacts);
                }
                if (!empty($BoothCate)) {
                    array_walk($BoothCate,function(&$v,$k)use($JobFairModel){
                        $v['jid']=$JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairBoothCateModel->saveAll($BoothCate);
                }
                if (!empty($Booth)) {
                    array_walk($Booth,function(&$v,$k)use($JobFairModel){
                        $v['jid']=$JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairBoothModel->saveAll($Booth);
                }
                if (!empty($Vip)) {
                    array_walk($Vip,function(&$v,$k)use($JobFairModel){
                        $v['jid']=$JobFairModel->id;
                        krsort($v);
                    });
                    $JobFairVipModel->saveAll($Vip);
                }
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
        	$VipController=VipController::getCate();
            View::assign('vip',$VipController);
            View::assign('arealist',Cache::get('arealist'));
            $Find=JobFairModel::alias('job')->where(['job.id'=>$id])
                ->join('job_fair_content content','content.jid = job.id')->field('job.*,content.content,content.about,content.job_fair_area1,content.job_fair_area2,content.job_fair_area3,content.address,content.lng,content.lat,content.transit')
                ->withAttr('sign_up_start_time',function($v,$d){
                    return $v?date('Y-m-d H:m:s',$v):'';
                })
                ->withAttr('sign_up_end_time',function($v,$d){
                    return $v?date('Y-m-d H:m:s',$v):'';
                })
                ->withAttr('start_time',function($v,$d){
                    return $v?date('Y-m-d H:m:s',$v):'';
                })
                ->withAttr('end_time',function($v,$d){
                    return $v?date('Y-m-d H:m:s',$v):'';
                })->find();
            if($Find){
            	if($Find->job_fair_area1&&$Find->job_fair_area2&&$Find->job_fair_area3)
            	$Find->job_fair_area=[$Find->job_fair_area1,$Find->job_fair_area2,$Find->job_fair_area3];
            	$Find->vip=JobFairVipModel::where(['jid'=>$Find->id,'status'=>1])->column('vid');
            	$Find->contacts=JobFairContactsModel::where(['jid'=>$Find->id])->select();
            	$Booth=[];
            	$JobFairBoothCateModel=JobFairBoothCateModel::where(['jid'=>$Find->id])->select()->toArray();
            	foreach ($JobFairBoothCateModel as $k => $v) {
            		$Booth[$k]=$v;
            		$Booth[$k]['show']=0;
            		$Booth[$k]['boothCate']=JobFairBoothModel::where(['jid'=>$Find->id,'identifier'=>$v['identifier']])->select()->toArray();
            	}
            	$Find->booth=$Booth;
            }
            View::assign('Find',$Find);
            View::assign('webtitle','编辑【'.$Find->title.'】招聘会');
            return View::fetch('add');
        }
    }
    /**
     * 发布文章
     */
    public function add()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     	=> 'require',
                'content'     	=> 'require',
                'start_time'    => 'require',
                'end_time'     	=> 'require',
                'status'     	=> 'require',
                'thumb'         => 'require',
                'banner'        => 'require',
            ];
            $msg  =   [
                'title.require' 		=> '标题不能为空', 
                'start_time.require'	=> '请选择开始时间', 
                'end_time.require' 		=> '请选择结束时间', 
                'content.require' 		=> '详情不能为空', 
                'status.require' 		=> '请选择状态', 
                'thumb.require'         => '请上传封面', 
                'banner.require'        => '请上传横幅',  
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            if(!$D['online_registration']||!$D['tel_registration']||!$D['offline_registration'])
            	return $this->ajaxReturn('请选择一种报名方式',-100);
            $JobFairModel=new JobFairModel;
            $JobFairModel->title    			= $D['title'];
            $JobFairModel->thumb    			= $D['thumb'];
            $JobFairModel->banner    			= $D['banner'];
            $JobFairModel->booth_img    		= $D['booth_img'];
            $JobFairModel->status    			= $D['status'];
            $JobFairModel->nature    			= $D['nature'];
            $JobFairModel->online_registration  = $D['online_registration'];
            $JobFairModel->tel_registration    	= $D['tel_registration'];
            $JobFairModel->offline_registration = $D['offline_registration'];
            $JobFairModel->sort    				= $D['sort'];
            $JobFairModel->is_all_sign_up    	= $D['is_all_sign_up'];
            $JobFairModel->booth_sum    		= $D['booth_sum'];
            if(strtotime($D['sign_up_start_time']))
            $JobFairModel->sign_up_start_time=strtotime($D['sign_up_start_time']);
            if(strtotime($D['sign_up_end_time']))
            $JobFairModel->sign_up_end_time=strtotime($D['sign_up_end_time']);
            if (strtotime($D['start_time']))
                $JobFairModel->start_time= strtotime($D['start_time']);
            if (strtotime($D['end_time']))
                $JobFairModel->end_time= strtotime($D['end_time']);

            if($D['offline_registration']&&(empty($D['job_fair_area'])||empty($D['address'])))
            	return $this->ajaxReturn('当使用线下报名时必须地区和详细地址',-100);
            $JobFairContentModel=new JobFairContentModel;
            if(!empty($D['job_fair_area'])&&count($D['job_fair_area'])>=3){
	            $JobFairContentModel->job_fair_area1=$D['job_fair_area'][0];
	            $JobFairContentModel->job_fair_area2=$D['job_fair_area'][1];
	            $JobFairContentModel->job_fair_area3=$D['job_fair_area'][2];
            }
            if(!empty($D['address']))
	            $JobFairContentModel->address=$D['address'];
            $JobFairContentModel->lng=$D['lng'];
            $JobFairContentModel->lat=$D['lat'];
            $JobFairContentModel->transit=$D['transit'];
            $JobFairContentModel->content=$D['content'];
            $JobFairContentModel->about=$D['about'];
	        $Contacts=[];
            if (!empty($D['contacts'])) {
            	$JobFairContactsModel=new JobFairContactsModel;
	            foreach ($D['contacts'] as $k => $v) {
	            	$Contacts[$k]=[
		            	'contacts'			=>	$v['contacts'],
						'contacts_mobile'	=>	$v['contacts_mobile'],
						'contacts_tel'		=>	$v['contacts_tel'],
						'contacts_qq'		=>	$v['contacts_qq'],
						'contacts_wechat'	=>	$v['contacts_wechat'],
						'contacts_email'	=>	$v['contacts_email'],
						'remarks'			=>	$v['remarks']
	            	];
	            }
            }
            if($D['tel_registration']&&empty($Contacts))
            	return $this->ajaxReturn('当使用电话报名时必须设置联系人',-100);
	        $BoothCate=[];
	        $Booth=[];
            if (!empty($D['booth'])) {
            	$booth_json=json_decode($D['booth'],true);
            	if (!empty($booth_json)){
	            	$JobFairBoothModel=new JobFairBoothModel;
	            	$JobFairBoothCateModel=new JobFairBoothCateModel;
		            foreach ($booth_json as $k => $v) {
		            	$BoothCate[$k]=[
			            	'name'				=>	empty($v['name'])?$v['identifier'].'区':$v['name'],
							'identifier'		=>	$v['identifier'],
							'sum'				=>	$v['sum'],
                            'price'             =>  $v['price'],
							'specifications'	=>	$v['specifications']
		            	];
		            	$stock_sum=0;
		            	foreach ($v['boothCate'] as $key => $booth) {
		            		$Booth[]=[
			            		'identifier'		=>	$v['identifier'],
			            		'index'				=>	$booth['index'],
								'price'				=>	$booth['price'],
								'specifications'	=>	$booth['specifications'],
								'status'			=>	$booth['status'],
		            		];
		            		if($booth['status'])
		            			$stock_sum++;
		            	}
		            	$BoothCate[$k]['stock_sum']=$v['sum']-$stock_sum;
		            }
	            }
            }
            if($D['online_registration']&&(empty($BoothCate)||empty($Booth)))
            	return $this->ajaxReturn('当使用线上报名时必须设置展位',-100);
	        $Vip=[];
	        $VipController=VipController::getCate();
        	$JobFairVipModel=new JobFairVipModel;
        	$VipControllerIndex=0;
            foreach ($VipController as $v) {
            	$Vip[$VipControllerIndex]=[
	            	'vid'				=>	$v->id,
	            	'level'				=>	$v->level,
					'is_company'		=>	$v->is_company
            	];
            	if($D['is_all_sign_up']){
            		$Vip[$VipControllerIndex]['status']=1;
            	}else{
            		$Vip[$VipControllerIndex]['status']=in_array($D['vip'],$v->id)?1:0;
            	}
            	$VipControllerIndex++;
            }
            unset($D);
            unset($rule);
            unset($msg);
            unset($Validate);
            unset($result);
            unset($booth_json);
            unset($VipController);
            unset($VipControllerIndex);
            // 启动事务
            Db::startTrans();
            try {
                $JobFairModel->save();
                $JobFairContentModel->jid=$JobFairModel->id;
                $JobFairContentModel->save();
	            if (!empty($Contacts)) {
	                array_walk($Contacts,function(&$v,$k)use($JobFairModel){
	                    $v['jid']=$JobFairModel->id;
	                    krsort($v);
	                });
	                $JobFairContactsModel->saveAll($Contacts);
	            }
	            if (!empty($BoothCate)) {
	                array_walk($BoothCate,function(&$v,$k)use($JobFairModel){
	                    $v['jid']=$JobFairModel->id;
	                    krsort($v);
	                });
	                $JobFairBoothCateModel->saveAll($BoothCate);
	            }
	            if (!empty($Booth)) {
	                array_walk($Booth,function(&$v,$k)use($JobFairModel){
	                    $v['jid']=$JobFairModel->id;
	                    krsort($v);
	                });
	                $JobFairBoothModel->saveAll($Booth);
	            }
	            if (!empty($Vip)) {
	                array_walk($Vip,function(&$v,$k)use($JobFairModel){
	                    $v['jid']=$JobFairModel->id;
	                    krsort($v);
	                });
	                $JobFairVipModel->saveAll($Vip);
	            }
                // 提交事务
                Db::commit();
                Baidu::post(config('web.url').'/job-fair/detail/'.$JobsModel->id.'.html');
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            View::assign('vip',VipController::getCate());
            View::assign('arealist',Cache::get('arealist'));
            return View::fetch();
        }
    }
    /**
     * 设置文章状态
     */
    public function setArticleStatus($id,$status)
    {
        $JobFairModel=JobFairModel::find($id);
        $JobFairModel->status=$status;
        if ($JobFairModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function delJobFairContacts($id)
    {
        if(JobFairContactsModel::where(['id'=>$id])->delete()){
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('删除失败，请重试',-100);
        }
    }
    public function delJobFairBooth($id,$is_cate)
    {
        if($is_cate){
            $JobFairBoothCateModel=JobFairBoothCateModel::where(['id'=>$id])->find();
            $JobFairBoothModel1=JobFairBoothModel::where(['jid'=>$JobFairBoothCateModel->jid,'identifier'=>$JobFairBoothCateModel->identifier])->where(['status'=>1])->count();
            $JobFairBoothModel2=JobFairBoothModel::where(['jid'=>$JobFairBoothCateModel->jid,'identifier'=>$JobFairBoothCateModel->identifier])->where(['status'=>2])->count();
            if($JobFairBoothModel1>0||$JobFairBoothModel2>0){
                return $this->ajaxReturn('当前展位区域下有'.$JobFairBoothModel1.'个锁定，'.$JobFairBoothModel2.'个已售无法删除',-200);
            }else{
                // 启动事务
                Db::startTrans();
                try {
                    JobFairBoothCateModel::where(['id'=>$id])->delete();
                    JobFairBoothModel::where(['jid'=>$JobFairBoothCateModel->jid,'identifier'=>$JobFairBoothCateModel->identifier,'status'=>0])->delete();
                    // 提交事务
                    Db::commit();
                    return $this->ajaxReturn();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->ajaxReturn('删除失败或状态不为待售',-200);
                }
            }
        }else{
            $JobFairBoothModel=JobFairBoothModel::where(['id'=>$id])->find();
            // 启动事务
            Db::startTrans();
            try {
                JobFairBoothModel::where(['id'=>$id,'status'=>0])->delete();
                JobFairBoothCateModel::where(['jid'=>$JobFairBoothModel->jid,'identifier'=>$JobFairBoothModel->identifier])->dec('sum')->dec('stock_sum')->update();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('删除失败或状态不为待售',-200);
            }
        }
    }
    public function boothManage()
    {
        if(request()->isAjax()){
            if(request()->isGet()){
                $G=request()->get();
                if(empty($G['jid']))
                    return $this->ajaxReturn('请先选择要管理的招聘会',-200);
                $where=[];
                $where[]=['job.id','=',$G['jid']];
                $Find=JobFairController::getFind($where);
                if($Find){
                    return $this->ajaxReturn('',0,$Find);
                }else{
                    return $this->ajaxReturn('招聘会不存在',-200);
                }
            }
            if (request()->isPost()) {
                $D=request()->post();
                if (empty($D['bid']))
                    return $this->ajaxReturn('未获取到展位信息',-200);
                switch ($D['status']) {
                    case 2:
                        if (empty($D['company_id']))
                            return $this->ajaxReturn('请检索要绑定的企业',-200);
                        return $this->setBoothStatusCompany($D);
                    case 1:
                        return $this->setBoothStatusLock($D);
                    default:
                        return $this->setBoothStatusUnlock($D);
                }
            }
        }else{
            $JobFair=JobFairController::getList();
            View::assign('JobFair',$JobFair->items());
            return View::fetch();
        }
    }
    public function setBoothStatusCompany($D)
    {
        $JobFairBoothModel=JobFairBoothModel::where(['id'=>$D['bid']])->find();
        $JobFairBoothStatusModel=new JobFairBoothStatusModel;
        $JobFairBoothStatusModel->bid=$JobFairBoothModel->id;
        $JobFairBoothStatusModel->status=2;
        $JobFairBoothStatusModel->company_id=$D['company_id'];
        $JobFairBoothStatusModel->old_status=$JobFairBoothModel->status;
        $JobFairBoothStatusModel->old_company_id=$JobFairBoothModel->company_id;
        $JobFairBoothModel->status=2;
        $JobFairBoothModel->company_id=$D['company_id'];
        $JobFairBoothStatusModel->admin_uid=Session::get('AdminUser.uid');
        $JobFairCompanyModel=JobFairCompanyModel::where(['jid'=>$JobFairBoothModel->jid,'company_id'=>$D['company_id']])->find();
        $JobFairModel=null;
        $JobFairCompany=null;
        if (!$JobFairCompanyModel) {
            $JobFairModel=JobFairModel::where(['id'=>$JobFairBoothModel->jid])->find();
            $company_sum=JobFairCompanyModel::where(['jid'=>$JobFairBoothModel->jid])->count();
            $JobFairModel->company_sum=$company_sum+1;
            $JobFairCompany=new JobFairCompanyModel;
            $JobFairCompany->jid=$JobFairBoothModel->jid;
            $JobFairCompany->bid=$JobFairBoothModel->id;
            $JobFairCompany->company_id=$D['company_id'];
        }
         // 启动事务
        Db::startTrans();
        try {
            $JobFairBoothModel->save();
            $JobFairBoothStatusModel->save();
            if($JobFairModel)$JobFairModel->save();
            if($JobFairCompany)$JobFairCompany->save();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function setBoothStatusLock($D)
    {
        $JobFairBoothModel=JobFairBoothModel::where(['id'=>$D['bid']])->find();
        if($JobFairBoothModel->status===0){
            $JobFairBoothModel->status=1;
            $JobFairBoothStatusModel=new JobFairBoothStatusModel;
            $JobFairBoothStatusModel->bid=$JobFairBoothModel->id;
            $JobFairBoothStatusModel->status=1;
            $JobFairBoothStatusModel->old_status=0;
            $JobFairBoothStatusModel->admin_uid=Session::get('AdminUser.uid');
             // 启动事务
            Db::startTrans();
            try {
                $JobFairBoothModel->save();
                $JobFairBoothStatusModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }
        return $this->ajaxReturn();
    }
    public function setBoothStatusUnlock($D)
    {
        $JobFairBoothModel=JobFairBoothModel::where(['id'=>$D['bid']])->find();
        if($JobFairBoothModel->status===1){
            $JobFairBoothModel->status=0;
            $JobFairBoothStatusModel=new JobFairBoothStatusModel;
            $JobFairBoothStatusModel->bid=$JobFairBoothModel->id;
            $JobFairBoothStatusModel->status=0;
            $JobFairBoothStatusModel->old_status=1;
            $JobFairBoothStatusModel->admin_uid=Session::get('AdminUser.uid');
             // 启动事务
            Db::startTrans();
            try {
                $JobFairBoothModel->save();
                $JobFairBoothStatusModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }elseif($JobFairBoothModel->status===2){
            $JobFairBoothModel->status=0;
            $JobFairCompanyModel=JobFairCompanyModel::where(['bid'=>$JobFairBoothModel->id,'company_id'=>$JobFairBoothModel->company_id])->find();
            if($JobFairCompanyModel)
                $JobFairCompanyModel->bid=null;
            $JobFairBoothStatusModel=new JobFairBoothStatusModel;
            $JobFairBoothStatusModel->bid=$JobFairBoothModel->id;
            $JobFairBoothStatusModel->status=0;
            $JobFairBoothStatusModel->old_status=2;
            $JobFairBoothStatusModel->old_company_id=$JobFairBoothModel->company_id;
            $JobFairBoothStatusModel->admin_uid=Session::get('AdminUser.uid');
            $JobFairModel=JobFairModel::where(['id'=>$JobFairBoothModel->jid])->find();
            $is_del=false;
            if (JobFairBoothModel::where(['jid'=>$JobFairBoothModel->jid,'company_id'=>$JobFairBoothModel->company_id,'status'=>2])->count()<2)
                $is_del=true;
            $company_sum=JobFairCompanyModel::where(['jid'=>$JobFairBoothModel->jid])->count();
            $JobFairModel->company_sum=$is_del?$company_sum-1:$company_sum;
            $JobFairBoothModel->company_id=null;
             // 启动事务
            Db::startTrans();
            try {
                $JobFairBoothModel->save();
                $JobFairBoothStatusModel->save();
                if($JobFairCompanyModel)$JobFairCompanyModel->save();
                $JobFairModel->save();
                if($is_del)JobFairCompanyModel::where(['jid'=>$JobFairBoothModel->jid,'company_id'=>$JobFairBoothModel->company_id])->delete();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }
        return $this->ajaxReturn('请刷新页面',-200);
    }
    public function getBoothStatusLog()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=['b.bid'=>$G['bid']];
            $Data=JobFairBoothStatusModel::alias('b')->where($where)
                ->join('company c','c.id=b.company_id','LEFT')
                ->join('company oldc','oldc.id=b.old_company_id','LEFT')
                ->join('admin admin','admin.id=b.admin_uid')
                ->field('b.*,c.logo,c.title,c.stitle,oldc.logo as old_logo,oldc.title as old_title,oldc.stitle as old_stitle,admin.nickname')
                ->order('b.id desc')->paginate(10)
                ->each(function($v){
                    $v['logo']=$v['logo']?config('web.imgurl').$v['logo']:'';
                    $v['old_logo']=$v['old_logo']?config('web.imgurl').$v['old_logo']:'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function resumeManage()
    {
        if(request()->isAjax()){
            if(request()->isGet()){
                $G=request()->get();
                if(empty($G['jid']))
                    return $this->ajaxReturn('请先选择要管理的招聘会',-200);
                $Field=[
                    'job.*',
                    'resume.name,resume.sex,resume.age,resume.educational_background,resume.work_experience_time,resume.refresh_time,resume.progress,resume.headimg_status,resume.privacy',
                    'e.salary_min,e.salary_max',
                    'nature_of_work.title as nature_of_work',
                    'job_status.title as job_status',
                    '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'
                ];
                $where=[];
                $where[]=['job.jid','=',$G['jid']];
                $Data=JobFairResumeModel::alias('job')
                    ->join('resume resume','resume.id=job.resume_id')
                    ->where($where)
                    ->join('user user','user.id=resume.uid')
                    ->join('user_info user_info','user_info.uid=user.id')
                    ->join('resume_self_description self_description','self_description.resume_id=resume.id','LEFT')
                    ->where(['educational_background.alias'=>'resume/educational_background'])
                    ->join('status_alias educational_background','educational_background.value=resume.educational_background')
                    ->where(['job_status.alias'=>'resume/job_status'])
                    ->join('status_alias job_status','job_status.value=resume.job_status')
                    ->join('resume_employment_intention e','e.resume_id=resume.id AND e.default=1','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('company_industry industry','industry.id=e.industry_id','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(implode(',',$Field))
                    ->order('job.id desc')->paginate($G['pageSize'])
                    ->each(function($v){
                        $v['age']=getWorkExpYear($v['age']);
                        $v['work_experience_time']=getWorkExpYear($v['work_experience_time']);
                        $v['friendly_time']=friendly_time($v['refresh_time'],'friendly');
                        $v['headimg']=$v['headimg']?config('web.imgurl').$v['headimg']:'';
                        return $v;
                    });
                if ($Data->items()) {
                    return $this->ajaxReturn('',0,$Data);
                }else{
                    return $this->ajaxReturn('暂无数据~',-100);
                }
            }
            if(request()->post()){
                $D=request()->post();
                if(empty($D['jid']))
                    return $this->ajaxReturn('请先选择要管理的招聘会',-200);
                $JobFairModel=JobFairModel::where(['id'=>$D['jid']])->find();
                if(!$JobFairModel)
                    return $this->ajaxReturn('请先选择要管理的招聘会',-200);
                $JobFairResumeModel=new JobFairResumeModel;
                $resumeList=[];
                foreach ($D['resume_id'] as $k => $v) {
                    $resumeList[]=[
                        'jid'       =>$D['jid'],
                        'resume_id' =>$v
                    ];
                }
                $JobFairModel->resume_sum=DB::raw('resume_sum+'.count($resumeList));
                $JobFairModel->view_people_sum=DB::raw('view_people_sum+'.count($resumeList));
                $JobFairModel->view_sum=DB::raw('view_sum+'.count($resumeList)*2);
                // 启动事务
                Db::startTrans();
                try {
                    $JobFairResumeModel->saveAll($resumeList);
                    $JobFairModel->save();
                    // 提交事务
                    Db::commit();
                    return $this->ajaxReturn();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return $this->ajaxReturn('添加失败',-200);
                }
            }
        }else{
            $JobFair=JobFairController::getList();
            View::assign('JobFair',$JobFair->items());
            return View::fetch();
        }
    }
    public function delResume($id)
    {
        $JobFairResumeModel=JobFairResumeModel::where(['id'=>$id])->find();
        // 启动事务
        Db::startTrans();
        try {
            JobFairResumeModel::where(['id'=>$id])->delete();
            JobFairModel::where(['id'=>$JobFairResumeModel->jid])->dec('resume_sum')->update();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('删除失败',-200);
        }
    }
}
