<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Cache;
use think\facade\Session;
use think\facade\Db;
use think\helper\Str;
use helper\Time;
use helper\Baidu;
use think\facade\Validate;
use app\common\validate\User as UserValidate;
use app\common\validate\UserName as UserNameValidate;
use app\common\validate\Company as CompanyValidate;
use app\common\validate\CompanyContent as CompanyContentValidate;
use think\exception\ValidateException;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\UserTimer as UserTimerModel;
use app\common\model\UserVip as UserVipModel;
use app\common\model\UserScore as UserScoreModel;
use app\common\model\Vip as VipModel;
use app\common\model\VipRule as VipRuleModel;
use app\common\model\UserVipRule as UserVipRuleModel;
use app\common\model\Jobs as JobsModel;
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\CompanyIndustry as CompanyIndustryModel;
use app\common\model\CompanyDemeanor as CompanyDemeanorModel;
use app\common\model\CompanyAttestation as CompanyAttestationModel;
use app\bsadmin\model\Config as ConfigModel;
use app\bsadmin\model\Admin as AdminModel;
use app\common\controller\Vip as VipController;
use app\common\model\CrmCustomer as CrmCustomerModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
class Company extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=$this->getSearchCompanyWhere();
            $Data=CompanyModel::alias('company')->where($where)
                ->join('user user','user.id = company.uid')
                ->join('user_info user_info','user_info.uid = company.uid','LEFT')
                ->join('user_vip user_vip','user_vip.uid = company.uid','LEFT')
                ->join('vip vip','vip.level = user_vip.company_vip_level AND vip.is_company=1','LEFT')
                ->join('company_content content','content.cid = company.id')
                ->join('api_app app','app.app_id = company.app_id','LEFT')
                ->field('company.*,user.mobile,user_info.nickname,user_info.headimg,vip.title as vip_title,user_vip.company_vip_time,app.app_name')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['nickname']=$v['nickname']?base64_decode($v['nickname']):'';
                    $v['headimg']=$v['headimg']?config('web.imgurl').$v['headimg']:'';
                    $v['app_name']=$v['app_name']?$v['app_name']:'后台添加';
                    $v['refresh_time']=$v['refresh_time']?date('Y-m-d H:i',$v['refresh_time']):'';
                    $v['company_vip_time']=$v['company_vip_time']&&$v['company_vip_time']>time()?date('Y-m-d',$v['company_vip_time']):'';
                    $v['jobs_count']=JobsModel::where(['company_id'=>$v->id])->count();
                    $v['company_info']=0;
                    $v['data']=[];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            $AdminModelObj=AdminModel::where(['status'=>1]);
            if(config('xy_crm.admin_role_id'))
                $AdminModelObj->whereIn('role_id',config('xy_crm.admin_role_id'));
            $AdminModel=$AdminModelObj->field('id,headimg,nickname,adviser_default')->select();
            View::assign('admin',$AdminModel);
            $attestation=StatusAliasModel::getCate('company/attestation');
            View::assign('attestation',$attestation);
            $nature=StatusAliasModel::getCate('company/nature');
            View::assign('nature',$nature);
            $finance=StatusAliasModel::getCate('company/finance');
            View::assign('finance',$finance);
            $size_type=StatusAliasModel::getCate('company/size_type');
            View::assign('size_type',$size_type);
            $corporate_welfare=StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare',$corporate_welfare);
            $industry=CompanyIndustryModel::getCate();
            View::assign('industry',$industry);
            $VipController=VipController::getCate();
            View::assign('vip',$VipController);
            return View::fetch();
        }
    }
    public function getSearchCompanyWhere()
    {
        $G=request()->get();
        $where=[];
        if ($G['key']) {
            switch($G['search_type']){
                case 'id':
                    $where[]=['company.id','=',$G['key']];
                    break;
                case 'uid':
                    $where[]=['user.id','=',$G['key']];
                    break;
                case 'uscc':
                    $where[]=['company.uscc','=',$G['key']];
                    break;
                case 'company_name':
                    $where[]=['company.title','like','%'.$G['key'].'%'];
                    break;
                case 'contacts_mobile':
                    $where[]=['content.contacts_mobile','=',$G['key']];
                    break;
                case 'contacts_email':
                    $where[]=['content.contacts_email','=',$G['key']];
                    break;
            }
        }
        if ($G['attestation']!='all') {
            $where[]=['company.attestation','=',$G['attestation']];
        }
        if (!empty($G['adviser_id'])) {
            $where[]=['company.adviser_id','=',$G['adviser_id']];
        }
        if (isset($G['vip_level'])&&$G['vip_level']!='all') {
            $where[]=['user_vip.company_vip_level','=',$G['vip_level']];
        }
        return $where;
    }
    public function exportCompany()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=$this->getSearchCompanyWhere();
            $Field=[
                'company.id,company.uid,company.title,company.stitle,company.logo,company.uscc,company.attestation,company.registered_capital,company.registered_capital_type,company.corporate_welfare,company.view,company.create_time',
                'nature.title as nature,finance.title as finance,size_type.title as size_type',
                'user_timer.online_time,user_timer.login_time',
                'industry.title as industry',
                'city.title as contacts_city,province.title as contacts_province,area.title as contacts_area',
                'content.contacts,content.contacts_mobile,content.contacts_wechat,content.contacts_tel,content.contacts_email,content.contacts_address,content.company_website,content.company_introduction,content.company_descript,content.template_id,content.contacts_lng,content.contacts_lat',
                'executives.executives,executives.executives_headimg,executives.executives_job_title,executives.executives_desc',
                'attestation.title as attestation',
                'app.app_name'
            ];
            $Data=CompanyModel::alias('company')->where($where)
                ->where(['nature.alias'=>'company/nature'])
                ->where(['finance.alias'=>'company/finance'])
                ->where(['size_type.alias'=>'company/size_type'])
                ->where(['attestation.alias'=>'company/attestation'])
                ->join('user user','user.id = company.uid')
                ->join('user_timer user_timer','user_timer.uid = company.uid','LEFT')
                ->join('company_industry industry','industry.id = company.industry_id')
                ->join('company_content content','content.cid = company.id','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('status_alias attestation','attestation.value=company.attestation')
                ->join('area province','province.id = content.contacts_area2')
                ->join('area city','city.id = content.contacts_area1')
                ->join('area area','area.id = content.contacts_area3')
                ->join('company_executives executives','executives.cid = company.id','LEFT')
                ->join('api_app app','app.app_id = company.app_id','LEFT')
                ->field(implode(",",$Field))
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['login_time']=$v->login_time?date('Y-m-d H:i:s',$v->login_time):'';
                    $v['app_name']=$v['app_name']?$v['app_name']:'后台添加';
                    $v['jobs_count']=JobsModel::where(['company_id'=>$v->id])->count();
                    return $v;
                });
            if ($Data->items()) {
                $title = [
                    ['title'=>'ID','key'=>'id'],
                    ['title'=>'UID','key'=>'uid'],
                    ['title'=>'企业名称','key'=>'title'],
                    ['title'=>'企业简称','key'=>'stitle'],
                    ['title'=>'统一社会信用代码','key'=>'uscc'],
                    ['title'=>'企业性质','key'=>'nature'],
                    ['title'=>'所属行业','key'=>'industry'],
                    ['title'=>'所在地区','key'=>'area'],
                    ['title'=>'企业规模','key'=>'size_type'],
                    ['title'=>'注册资金','key'=>'registered_capital'],
                    ['title'=>'注册来源','key'=>'app_name'],
                    ['title'=>'发布职位数','key'=>'jobs_count'],
                    ['title'=>'联系人','key'=>'contacts'],
                    ['title'=>'联系电话','key'=>'contacts_mobile'],
                    ['title'=>'固定电话','key'=>'contacts_tel'],
                    ['title'=>'联系邮箱','key'=>'contacts_email'],
                    ['title'=>'审核状态','key'=>'attestation'],
                    ['title'=>'注册时间','key'=>'create_time'],
                    ['title'=>'最后登录时间','key'=>'login_time']
                ];
                $spreadsheet = new Spreadsheet;
                $sheet = $spreadsheet->getActiveSheet();
             
                //表头
                //设置单元格内容
                $titCol = 'A';
                foreach ($title as $key => $v) {
                    // 单元格内容写入
                    $sheet->setCellValue($titCol . '1', $v['title']);
                    $titCol++;
                }
                $row=2;
                foreach($Data->items() as $item){
                    $dataCol='A';
                    foreach ($title as $key => $v) {
                        switch ($v['key']) {
                            case 'area':
                                $sheet->setCellValue($dataCol.$row, $item->contacts_province.$item->contacts_city.$item->contacts_area);
                                break;
                            case 'registered_capital':
                                $registered_capital='万人民币';
                                if($item->registered_capital_type)
                                    $registered_capital='万美元';
                                $sheet->setCellValue('J'.$row, $item->registered_capital.$registered_capital);
                                break;
                            
                            default:
                                $sheet->setCellValue($dataCol.$row, $item[$v['key']]);
                                break;
                        }
                        $dataCol++;
                    }
                    $row++;
                }
                $filename='output/company/'.Session::get('AdminUser.uid').'_'.date('YmdHis').Str::random(4).'.xlsx';
                if (!file_exists(dirname($filename)))
                    mkdir(dirname($filename), 0777, true);
                $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
                $writer->save($filename);
                return $this->ajaxReturn('生成~',0,['url'=>'/'.$filename]);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }
    }
    public function importCompany()
    {
        $VipController=VipController::getCate();
        View::assign('vip',$VipController);
        $arealist=Cache::get('arealist');
        View::assign('arealist',$arealist);
        $attestation=StatusAliasModel::getCate('company/attestation');
        View::assign('attestation',$attestation);
        $nature=StatusAliasModel::getCate('company/nature');
        View::assign('nature',$nature);
        $finance=StatusAliasModel::getCate('company/finance');
        View::assign('finance',$finance);
        $size_type=StatusAliasModel::getCate('company/size_type');
        View::assign('size_type',$size_type);
        $corporate_welfare=StatusAliasModel::getCate('company/corporate_welfare');
        View::assign('corporate_welfare',$corporate_welfare);
        $industry=CompanyIndustryModel::getCate();
        View::assign('industry',$industry);
        return View::fetch();
    }
    /**
     * 获取企业信息
     */
    public function getCompanyInfo($id)
    {
        $Find=CompanyModel::getCompanyInfoAll($id);
        if ($Find) {
            return $this->ajaxReturn('',0,$Find);
        }else{
            return $this->ajaxReturn('无此企业数据',-100);
        }
    }
    public function setIsFamous($id,$status)
    {
        $CompanyModel=CompanyModel::find($id);
        $CompanyModel->is_famous=$status;
        if ($CompanyModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function refreshCompany($id)
    {
        $CompanyModel=CompanyModel::where(['id'=>$id])->find();
        $CompanyModel->refresh_time=time();
        if($CompanyModel->save()){
            return $this->ajaxReturn('已刷新',0,['refresh_time'=>date('Y-m-d H:i',$CompanyModel->refresh_time)]);
        }else{
            return $this->ajaxReturn('刷新失败，请重试',-100);
        }
    }
    /**
     * 添加企业
     */
    public function addCompany()
    {
        if (request()->isAjax()) {
            $D=request()->post();
            /**
             * 公司基本信息验证
             */
            try {
                validate(CompanyValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(),-100);
            }
            /**
             * 公司拓展信息验证
             */
            try {
                validate(CompanyContentValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(),-100);
            }
            /**
             * 用户
             */
            $UserModel=UserModel::where(['mobile'=>$D['mobile']])->find();
            $UserInfoModel=null;
            $UserVipModel=null;
            $UserTimerModel=null;
            if($UserModel){
                if(CompanyModel::where(['uid'=>$UserModel->id])->count())
                    return $this->ajaxReturn('该手机号已绑定企业主体',-100);
                $UserInfoModel=UserInfoModel::where(['uid'=>$UserModel->id])->find();
                $UserVipModel=UserVipModel::where(['uid'=>$UserModel->id])->find();
            }else{
                try {
                    validate(UserNameValidate::class)->check($D);
                } catch (ValidateException $e) {
                    return $this->ajaxReturn($e->getError(),-100);
                }
                $passHash=Str::random(4);
                $UserModel=new UserModel;
                $UserModel->mobile=$D['mobile'];
                if(!empty($D['email']))
                $UserModel->email=$D['email'];
                $UserModel->password_hash=$passHash;
                if($D['password']){
                    $UserModel->password=UserModel::getPassword($passHash,$D['password']);
                }else{
                    $UserModel->password=UserModel::getPassword($passHash,$D['mobile']);
                }
                /**
                 * 用户信息
                 */
                $UserInfoModel=new UserInfoModel;
                $UserInfoModel->nickname=base64_encode('XY_'.substr_replace($D['mobile'],'****',3,4));
                $UserInfoModel->headimg=config('xy_default_avatar.user');
                $UserInfoModel->role_type=1;
                $UserTimerModel=new UserTimerModel;
                $UserTimerModel->online_time=time();
                $UserTimerModel->online_ip=request()->ip();
                $UserTimerModel->online_devices=substr(request()->header('user-agent'),0,200);
                $UserTimerModel->login_time=time();
                $UserTimerModel->login_ip=request()->ip();
                $UserTimerModel->login_devices=substr(request()->header('user-agent'),0,200);
                $UserTimerModel->register_time=time();
                $UserTimerModel->register_ip=request()->ip();
                $UserTimerModel->register_devices=substr(request()->header('user-agent'),0,200);
                $UserVipModel=new UserVipModel;
            }
            /**
             * 公司基本信息
             */
            $CompanyModel=new CompanyModel;
            $CompanyModel->title            =   $D['title'];
            $CompanyModel->stitle           =   $D['stitle'];
            $CompanyModel->business_license =   $D['business_license'];
            $CompanyModel->logo             =   $D['logo'];
            $CompanyModel->attestation      =   $D['attestation'];
            $CompanyModel->nature           =   $D['nature'];
            $CompanyModel->industry_id      =   $D['industry_id'];
            $CompanyModel->region_id        =   $D['region_id'];
            $CompanyModel->size_type        =   $D['size_type'];
            $CompanyModel->registered_capital=   $D['registered_capital'];
            $CompanyModel->registered_capital_type=   $D['registered_capital_type'];
            if(!empty($D['corporate_welfare']))
            $CompanyModel->corporate_welfare=   implode(",", $D['corporate_welfare']);
            /**
             * 公司拓展信息
             */
            $CompanyContentModel=new CompanyContentModel;
            $CompanyContentModel->contacts             =   trimall($D['contacts']);
            $CompanyContentModel->contacts_mobile      =   $D['contacts_mobile'];
            $CompanyContentModel->contacts_tel         =   $D['contacts_tel'];
            $CompanyContentModel->contacts_email       =   $D['contacts_email'];
            $CompanyContentModel->contacts_area1       =   $D['contacts_area'][1];
            $CompanyContentModel->contacts_area2       =   $D['contacts_area'][0];
            $CompanyContentModel->contacts_area3       =   $D['contacts_area'][2];
            $CompanyContentModel->contacts_address     =   $D['contacts_address'];
            $CompanyContentModel->company_website      =   $D['company_website'];
            $CompanyContentModel->company_introduction =   $D['company_introduction'];
            $CompanyContentModel->company_descript     =   $D['company_descript'];
            $CompanyContentModel->template_id          =   $D['template_id'];
            $AdminUser=Session::get('AdminUser');
            $CrmCustomerModel=null;
            if(config('xy_crm.admin_role_id')&&in_array($AdminUser['rid'],config('xy_crm.admin_role_id'))){
                $CompanyModel->adviser_id=$AdminUser['uid'];
                $CrmCustomerModel=new CrmCustomerModel;
                $CrmCustomerModel->customer=$CompanyContentModel->contacts;
                $CrmCustomerModel->customer_mobile=$UserModel->mobile;
                $CrmCustomerModel->customer_email=$UserModel->email;
            }

            $UserScoreModel=null;
            $VipModel=null;
            if (!empty($D['vip_level'])) {
                $VipModel=VipModel::where(['level'=>$D['vip_level'],'is_company'=>1])->where('level','>',0)->find();
                if($VipModel){
                    $VipRuleModel=VipRuleModel::alias('rule')->where(['rule.vid'=>$VipModel->id,'rv.status'=>1,'rv.type'=>'input'])
                        ->join('vip_rule_value rv','rv.id=rule.rid')
                        ->field('rule.vid,rule.rid,rule.value,rv.alias')->select()->toArray();
                    $UserVipModel->update_vip=1;
                    $UserVipRuleList=[];
                    if ($VipRuleModel) {
                        list($expiry_time, $end) = Time::today();
                        $UserVipRuleModel=new UserVipRuleModel;
                        foreach ($VipRuleModel as $k => $v) {
                            switch ($v['alias']) {
                                case 'time-limit':
                                    $surplus_value=Time::daysToSecond($v['value'])+3600*24;
                                    $expiry_time=$expiry_time+$surplus_value;
                                    if ($VipModel->is_company) {
                                        if ($UserVipModel->company_vip_time>time()) {
                                            $UserVipModel->company_vip_time=Db::raw('company_vip_time+'.$surplus_value);
                                        }else{
                                            $UserVipModel->company_vip_time=$expiry_time;

                                        }
                                    }else{
                                        if ($UserVipModel->personal_vip_time>time()) {
                                            $UserVipModel->personal_vip_time=Db::raw('personal_vip_time+'.$surplus_value);
                                        }else{
                                            $UserVipModel->personal_vip_time=$expiry_time;

                                        }
                                    }
                                    break;
                                case 'bonus-points':
                                    $UserInfoModel->score=Db::raw('score+'.$v['value']);
                                    $UserScoreModel=new UserScoreModel;
                                    $UserScoreModel->tid    =   0;
                                    $UserScoreModel->score  =   $v['value'];
                                    $UserScoreModel->desc   =   '开通'.$VipModel->title.'套餐赠送'.$v['value'].'积分';
                                    break;
                                default:
                                    $v['level']=$VipModel->level;
                                    $v['surplus_value']=$v['value'];
                                    $UserVipRuleList[]=$v;
                                    break;
                            }
                        }
                    }
                }
            }
          
            // 启动事务
            Db::startTrans();
            try {
                if($UserInfoModel)$UserModel->save();
                $CompanyModel->uid=$UserModel->id;
                $CompanyModel->save();
                $CompanyContentModel->cid=$CompanyModel->id;
                $CompanyContentModel->save();
                if($VipModel)
                VipModel::where(['id'=>$VipModel->id])->inc('sold')->update();
                if (!empty($UserVipRuleList)){
                    array_walk($UserVipRuleList,function(&$v,$k)use($expiry_time,$UserModel){
                        $v['uid']=$UserModel->id;
                        $v['expiry_time']=$expiry_time;
                        krsort($v);
                    });
                    $UserVipRuleModel->saveAll($UserVipRuleList);
                }
                if ($UserVipModel) {
                    $UserVipModel->uid=$UserModel->id;
                    $UserVipModel->save();
                }
                if($UserInfoModel){
                    $UserInfoModel->uid=$UserModel->id;
                    $UserInfoModel->save();
                }
                if($UserTimerModel){
                    $UserTimerModel->uid=$UserModel->id;
                    $UserTimerModel->save();
                }
                if ($UserScoreModel){
                    $UserScoreModel->uid=$UserModel->id;
                    $UserScoreModel->save();
                }
                if ($CrmCustomerModel) {
                    $CrmCustomerModel->company_id=$CompanyModel->id;
                    $CrmCustomerModel->save();
                }
                // 提交事务
                Db::commit();
                Baidu::post(config('web.url').'/company/'.$CompanyModel->id.'.html');
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $VipController=VipController::getCate();
            View::assign('vip',$VipController);
            $arealist=Cache::get('arealist');
            View::assign('arealist',$arealist);
            $attestation=StatusAliasModel::getCate('company/attestation');
            View::assign('attestation',$attestation);
            $nature=StatusAliasModel::getCate('company/nature');
            View::assign('nature',$nature);
            $finance=StatusAliasModel::getCate('company/finance');
            View::assign('finance',$finance);
            $size_type=StatusAliasModel::getCate('company/size_type');
            View::assign('size_type',$size_type);
            $corporate_welfare=StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare',$corporate_welfare);
            $industry=CompanyIndustryModel::getCate();
            View::assign('industry',$industry);
            return View::fetch();
        }
    }
    /**
     * 编辑企业
     */
    public function editCompany($id)
    {
        if (request()->isAjax()) {
            $D=request()->post();
            /**
             * 公司基本信息验证
             */
            try {
                validate(CompanyValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(),-100);
            }
            /**
             * 公司拓展信息验证
             */
            try {
                validate(CompanyContentValidate::class)->check($D);
            } catch (ValidateException $e) {
                return $this->ajaxReturn($e->getError(),-100);
            }
            /**
             * 公司基本信息
             */
            $CompanyModel=CompanyModel::find($id);
            $CompanyModel->title            =   $D['title'];
            $CompanyModel->stitle           =   $D['stitle'];
            $CompanyModel->business_license =   $D['business_license'];
            $CompanyModel->logo             =   $D['logo'];
            $CompanyModel->attestation      =   $D['attestation'];
            $CompanyModel->nature           =   $D['nature'];
            $CompanyModel->industry_id      =   $D['industry_id'];
            $CompanyModel->region_id        =   $D['region_id'];
            $CompanyModel->size_type        =   $D['size_type'];
            $CompanyModel->registered_capital=   $D['registered_capital'];
            $CompanyModel->registered_capital_type=   $D['registered_capital_type'];
            if(!empty($D['corporate_welfare']))
            $CompanyModel->corporate_welfare=   empty($D['corporate_welfare'])?'':implode(",", $D['corporate_welfare']);
            /**
             * 公司拓展信息
             */
            $CompanyContentModel=CompanyContentModel::where(['cid'=>$CompanyModel->id])->find();
            $CompanyContentModel->contacts             =   trimall($D['contacts']);
            $CompanyContentModel->contacts_mobile      =   $D['contacts_mobile'];
            $CompanyContentModel->contacts_tel         =   $D['contacts_tel'];
            $CompanyContentModel->contacts_email       =   $D['contacts_email'];
            $CompanyContentModel->contacts_area1       =   $D['contacts_area'][1];
            $CompanyContentModel->contacts_area2       =   $D['contacts_area'][0];
            $CompanyContentModel->contacts_area3       =   $D['contacts_area'][2];
            $CompanyContentModel->contacts_address     =   $D['contacts_address'];
            $CompanyContentModel->company_website      =   $D['company_website'];
            $CompanyContentModel->company_introduction =   $D['company_introduction'];
            $CompanyContentModel->company_descript     =   $D['company_descript'];
            $CompanyContentModel->template_id          =   $D['template_id'];
            $UserInfoModel=null;
            $UserScoreModel=null;
            $VipModel=null;
            $UserVipModel=UserVipModel::where(['uid'=>$CompanyModel->uid])->find();
            if (!empty($D['vip_level'])&&(int) $D['vip_level']!==$UserVipModel->company_vip_level) {
                $VipModel=VipModel::where(['level'=>$D['vip_level'],'is_company'=>1])->where('level','>',0)->find();
                if($VipModel){
                    $VipRuleModel=VipRuleModel::alias('rule')->where(['rule.vid'=>$VipModel->id,'rv.status'=>1,'rv.type'=>'input'])
                        ->join('vip_rule_value rv','rv.id=rule.rid')
                        ->field('rule.vid,rule.rid,rule.value,rv.alias')->select()->toArray();
                    $UserInfoModel=UserInfoModel::where(['uid'=>$CompanyModel->uid])->find();
                    if (!$UserVipModel) {
                        $UserVipModel=new UserVipModel;
                        $UserVipModel->uid=$CompanyModel->uid;
                    }
                    $UserVipModel->update_vip=1;
                    $UserVipRuleList=[];
                    if ($VipRuleModel) {
                        list($expiry_time, $end) = Time::today();
                        $UserVipRuleModel=new UserVipRuleModel;
                        foreach ($VipRuleModel as $k => $v) {
                            switch ($v['alias']) {
                                case 'time-limit':
                                    $surplus_value=Time::daysToSecond($v['value'])+3600*24;
                                    $expiry_time=$expiry_time+$surplus_value;
                                    if ($VipModel->is_company) {
                                        if ($UserVipModel->company_vip_time>time()) {
                                            $UserVipModel->company_vip_time=Db::raw('company_vip_time+'.$surplus_value);
                                        }else{
                                            $UserVipModel->company_vip_time=$expiry_time;

                                        }
                                    }else{
                                        if ($UserVipModel->personal_vip_time>time()) {
                                            $UserVipModel->personal_vip_time=Db::raw('personal_vip_time+'.$surplus_value);
                                        }else{
                                            $UserVipModel->personal_vip_time=$expiry_time;

                                        }
                                    }
                                    break;
                                case 'bonus-points':
                                    $UserInfoModel->score=Db::raw('score+'.$v['value']);
                                    $UserScoreModel=new UserScoreModel;
                                    $UserScoreModel->tid    =   0;
                                    $UserScoreModel->score  =   $v['value'];
                                    $UserScoreModel->desc   =   '开通'.$VipModel->title.'套餐赠送'.$v['value'].'积分';
                                    break;
                                default:
                                    $v['uid']=$CompanyModel->uid;
                                    $v['level']=$VipModel->level;
                                    $v['surplus_value']=$v['value'];
                                    $UserVipRuleList[]=$v;
                                    break;
                            }
                        }
                    }
                    if (!empty($UserVipRuleList)){
                        array_walk($UserVipRuleList,function(&$v,$k)use($expiry_time){
                            $v['expiry_time']=$expiry_time;
                            krsort($v);
                        });
                    }
                }else{
                    $UserVipModel=null;
                }
            }
          
            // 启动事务
            Db::startTrans();
            try {
                $CompanyModel->save();
                $CompanyContentModel->save();
                if($VipModel)VipModel::where(['id'=>$VipModel->id])->inc('sold')->update();
                if (!empty($UserVipRuleList)) $UserVipRuleModel->saveAll($UserVipRuleList);
                if ($UserInfoModel) $UserInfoModel->save();
                if ($UserVipModel) $UserVipModel->save();
                if ($UserScoreModel) $UserScoreModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $VipController=VipController::getCate();
            View::assign('vip',$VipController);
            $Find=CompanyModel::getEditFind($id);
            View::assign('Find',$Find);
            $arealist=Cache::get('arealist');
            View::assign('arealist',$arealist);
            $attestation=StatusAliasModel::getCate('company/attestation');
            View::assign('attestation',$attestation);
            $nature=StatusAliasModel::getCate('company/nature');
            View::assign('nature',$nature);
            $finance=StatusAliasModel::getCate('company/finance');
            View::assign('finance',$finance);
            $size_type=StatusAliasModel::getCate('company/size_type');
            View::assign('size_type',$size_type);
            $corporate_welfare=StatusAliasModel::getCate('company/corporate_welfare');
            View::assign('corporate_welfare',$corporate_welfare);
            $industry=CompanyIndustryModel::getCate();
            View::assign('industry',$industry);
            return View::fetch('add_company');
        }
    }
    public function setAdviser($id,$adviser_id)
    {
        // 启动事务
        Db::startTrans();
        $CompanyModel=CompanyModel::where(['id'=>$id])->whereNull('adviser_id')->lock(true)->find();
        if($CompanyModel){
            $CompanyModel->adviser_id=$adviser_id;
            try {
                $CompanyModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已设置');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('设置失败，请重试',-100);
            }
        }else{
            Db::commit();
            return $this->ajaxReturn('企业不存在或已分配',-100);
        }
    }
    public function demeanor()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'company_id':
                        $where[]=['d.cid','=',$G['key']];
                        break;
                    case 'company_name':
                        $where[]=['company.title','like','%'.$G['key'].'%'];
                        break;
                }
            }
            if ($G['status']!='all') {
                $where[]=['d.status','=',$G['status']];
            }
            $Data=CompanyDemeanorModel::alias('d')->where($where)
                ->join('company company','company.id = d.cid')
                ->field('d.*,company.title')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['url']=config('web.imgurl').$v['path'];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function setCompanyDemeanor($id,$status)
    {
        $CompanyDemeanorModel=CompanyDemeanorModel::where(['id'=>$id])->find();
        $CompanyDemeanorModel->status=$status;
        if ($CompanyDemeanorModel->save()) {
            return $this->ajaxReturn('已保存',0,['update_time'=>date('Y-m-d H:i:s')]);
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function companyAttestation()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            $where=[];
            if ($G['key']) {
                switch($G['search_type']){
                    case 'id':
                        $where[]=['a.cid','=',$G['key']];
                        break;
                    case 'uscc':
                        $where[]=['a.uscc','=',$G['key']];
                        break;
                    case 'company_name':
                        $where[]=['company.title','like','%'.$G['key'].'%'];
                        break;
                }
            }
            if ($G['status']!='all') {
                $where[]=['a.status','=',$G['status']];
            }
            $Data=CompanyAttestationModel::alias('a')->where($where)
                ->join('company company','company.id = a.cid')
                ->field('a.*,company.title')
                ->order('id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['url']=config('web.imgurl').$v['business_license'];
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function setCompanyAttestationStatus($id,$status,$msg='')
    {
        $CompanyAttestationModel=CompanyAttestationModel::where(['id'=>$id])->find();
        $CompanyModel=CompanyModel::where(['id'=>$CompanyAttestationModel->cid])->find();
        if ($status==1) {
            $CompanyAttestationModel->status=1;
            $CompanyModel->attestation=3;
            $CompanyModel->uscc=$CompanyAttestationModel->uscc;
            $CompanyModel->business_license=$CompanyAttestationModel->business_license;
            if (CompanyModel::where(['uscc'=>$CompanyAttestationModel->uscc])->count())
                return $this->ajaxReturn('此统一社会信用代码已实名',-100);
            // 启动事务
            Db::startTrans();
            try {
                $CompanyAttestationModel->save();
                $CompanyModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-100);
            }
        }else{
            $CompanyAttestationModel->status=2;
            $CompanyAttestationModel->msg=$msg;
            $CompanyModel->attestation=2;
            // 启动事务
            Db::startTrans();
            try {
                $CompanyAttestationModel->save();
                $CompanyModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('已保存');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-100);
            }

        }
    }
    public function setting()
    {
        $Data=ConfigModel::getList([['ctype','in',['xy_company','xy_default_avatar','xy_resume']]]);
        View::assign('Data',$Data);
        View::assign('ctype','xy_company');
        return View::fetch('setting/company');
    }
    public function industry()
    {
        if (request()->isAjax()) {
            $G=request()->get();
            if (empty($G['cid'])) {
                return $this->ajaxReturn('',0,CompanyIndustryModel::getSelect(['pid'=>0]));
            }else{
                return $this->ajaxReturn('',0,CompanyIndustryModel::getSelect(['pid'=>$G['cid']]));
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 编辑文章分类
     */
    public function editIndustry($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $CompanyIndustryModel=CompanyIndustryModel::find($id);
            $CompanyIndustryModel->title    = $D['title'];
            $CompanyIndustryModel->status    = $D['status'];
            if (!empty($D['sort'])) 
                $CompanyIndustryModel->sort    = $D['sort'];
            if($CompanyIndustryModel->save()){
                $this->setCacheIndustry();
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $Find=CompanyIndustryModel::where(['id'=>$id])->find();
            View::assign('Find',$Find);
            $industry=CompanyIndustryModel::getSelect(['pid'=>0]);
            View::assign('industry',$industry);
            return View::fetch('add_industry');
        }
    }
    /**
     * 添加文章分类
     */
    public function addIndustry()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'     => 'require|max:50',
            ];
            $msg  =   [
                'title.require' => 'Title 不能为空', 
                'title.max'     => 'Title 不能超过50个字符',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $CompanyIndustryModel=new CompanyIndustryModel;
            $CompanyIndustryModel->title    = $D['title'];
            $CompanyIndustryModel->status    = $D['status'];
            if (!empty($D['sort'])) 
                $CompanyIndustryModel->sort    = $D['sort'];
            if($CompanyIndustryModel->save()){
                $this->setCacheIndustry();
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $industry=CompanyIndustryModel::getSelect(['pid'=>0]);
            View::assign('industry',$industry);
            return View::fetch();
        }
    }
    public function setCompanyIndustryStatus($id,$status)
    {
        $CompanyIndustryModel=CompanyIndustryModel::find($id);
        $CompanyIndustryModel->status=$status;
        if ($CompanyIndustryModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function setCacheIndustry()
    {
        $Data=CompanyIndustryModel::getCache();
        Cache::set('CompanyIndustry',$Data);
        return $this->ajaxReturn('保存成功');
    }
}
