<?php
namespace app\bsadmin\controller;
use think\facade\View;
use think\facade\Validate;
use app\bsadmin\model\ApiApp as ApiAppModel;
use app\common\model\Ads as AdsModel;
use app\common\model\AdsPosition as AdsPositionModel;
use app\common\model\Area as AreaModel;
use app\common\model\CompanyIndustry as CompanyIndustryModel;
class Ads extends Base
{
    public function adsPosition()
    {
        if(request()->isAjax()){
            $G=request()->get();
            $where=[];
            if (!empty($G['id'])) {
                $where[]=['ads.pid','=',$G['id']];
            }
            $Data=AdsModel::alias('ads')->where($where)
                ->join('ads_position p','p.id=ads.pid')
                ->field('ads.*,p.title as ptitle')
                ->order('ads.id desc')->paginate($G['pageSize'])->each(function($v){
                    $v['imgurl']=config('web.imgurl').$v['path'];
                    $v['start_time']=$v['start_time']?date('Y-m-d',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d',$v['end_time']):'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            View::assign('app_list',ApiAppModel::select());
            $AdsPositionModel=AdsPositionModel::alias('ads')
            ->join('api_app app','app.app_id=ads.app_id')
            ->withAttr('start_time',function($v){
                return $v?date('Y-m-d',$v):'';
            })->withAttr('end_time',function($v){
                return $v?date('Y-m-d',$v):'';
            })->field('ads.*,app.app_name')->select();
            View::assign('ads_position_list',$AdsPositionModel);
            return View::fetch();
        }
    }
    public function addAdsPosition()
    {
        if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'app_id'        => 'require',
                'title'         => 'require|max:50',
                'alias'         => 'require|max:30',
                'status'        => 'require',
                'width'         => 'require',
                'height'        => 'require',
            ];
            $msg  =   [
                'app_id.require'    => '请选择客户端', 
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过50个字符',
                'alias.require'     => '别名不能为空',
                'alias.max'         => '别名不能超过30个字符',
                'alias.unique'      => '别名已存在',
                'status.require'    => '请选择状态',
                'width.require'     => '请输入建议尺寸',
                'height.require'    => '请输入建议尺寸',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AdsPositionModel=new AdsPositionModel;
            $AdsPositionModel->app_id       =   $D['app_id'];
            $AdsPositionModel->title        =   $D['title'];
            $AdsPositionModel->alias        =   $D['alias'];
            $AdsPositionModel->status       =   $D['status'];
            $AdsPositionModel->width        =   $D['width'];
            $AdsPositionModel->height       =   $D['height'];
            if (strtotime($D['start_time']))
                $AdsPositionModel->start_time=strtotime($D['start_time'].' 00:00:00');
            if (strtotime($D['end_time']))
                $AdsPositionModel->end_time=strtotime($D['end_time'].' 23:59:59');
            if($AdsPositionModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            View::assign('app_list',ApiAppModel::select());
            return View::fetch('add_ads_position');
        }
    }
    public function editAdsPosition($id)
    {
        if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'app_id'        => 'require',
                'title'         => 'require|max:50',
                'alias'         => 'require|max:30',
                'status'        => 'require',
                'width'         => 'require',
                'height'        => 'require',
            ];
            $msg  =   [
                'app_id.require'    => '请选择客户端', 
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过50个字符',
                'alias.require'     => '别名不能为空',
                'alias.max'         => '别名不能超过30个字符',
                'alias.unique'      => '别名已存在',
                'status.require'    => '请选择状态',
                'width.require'     => '请输入建议尺寸',
                'height.require'    => '请输入建议尺寸',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AdsPositionModel=AdsPositionModel::where(['id'=>$id])->find();
            $AdsPositionModel->app_id       =   $D['app_id'];
            $AdsPositionModel->title        =   $D['title'];
            $AdsPositionModel->alias        =   $D['alias'];
            $AdsPositionModel->status       =   $D['status'];
            $AdsPositionModel->width        =   $D['width'];
            $AdsPositionModel->height       =   $D['height'];
            if (strtotime($D['start_time'])){
                $AdsPositionModel->start_time=strtotime($D['start_time'].' 00:00:00');
            }else{
                $AdsPositionModel->start_time=null;
            }
            if (strtotime($D['end_time'])){
                $AdsPositionModel->end_time=strtotime($D['end_time'].' 23:59:59');
            }else{
                $AdsPositionModel->end_time=null;
            }
            if($AdsPositionModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            View::assign('app_list',ApiAppModel::select());
            $AdsPositionModel=AdsPositionModel::where(['id'=>$id])
                ->withAttr('start_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })
                ->withAttr('end_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })->find();
            View::assign('Find',$AdsPositionModel);
            return View::fetch('add_ads_position');
        }
    }
    public function setAdsPositionStatus($id,$status)
    {
        $AdsPositionModel=AdsPositionModel::where(['id'=>$id])->find();
        $AdsPositionModel->status=$status;
        $AdsPositionModel->start_time=null;
        $AdsPositionModel->end_time=null;
        if ($AdsPositionModel->save()) {
            return $this->ajaxReturn('保存成功');
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function delAdsPosition($id)
    {
    	if (AdsModel::where(['pid'=>$id])->count()) {
	        return $this->ajaxReturn('该广告位下图片不为空，请先删除图片',-200);
    	}else{
	        $AdsPositionModel=AdsPositionModel::where(['id'=>$id])->find();
	        if ($AdsPositionModel->delete()) {
	            return $this->ajaxReturn('已删除');
	        }else{
	            return $this->ajaxReturn('删除失败，请重试',-200);
	        }
    	}
    }
    public function add($id)
    {
    	if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'path'         	=> 'require',
                'status'        => 'require',
            ];
            $msg  =   [
                'path.require'     	=> '请上传图片',
                'status.require'    => '请选择状态',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AdsModel=new AdsModel;
            $AdsModel->pid        	=   $id;
            $AdsModel->title        =   empty($D['title'])?'ads_'.time():$D['title'];
            $AdsModel->path        	=   $D['path'];
            $AdsModel->url        	=   $D['url'];
            $AdsModel->sort         =   intval($D['sort'])?intval($D['sort']):9999;
            $AdsModel->col        	=   intval($D['col'])?intval($D['col']):1;
            $AdsModel->status       =   $D['status'];
            $AdsModel->ads_icon     =   $D['ads_icon'];
            $AdsModel->industry     =   $D['industry'];
            if (!empty($D['area'])&&count($D['area'])>=3) {
                $AdsModel->province  = $D['area'][0];
                $AdsModel->city      = $D['area'][1];
                $AdsModel->area      = $D['area'][2];
            }else{
                $AdsModel->province  = null;
                $AdsModel->city      = null;
                $AdsModel->area      = null;
            }
            if (strtotime($D['start_time']))
                $AdsModel->start_time=strtotime($D['start_time'].' 00:00:00');
            if (strtotime($D['end_time']))
                $AdsModel->end_time=strtotime($D['end_time'].' 23:59:59');
            if($AdsModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
    	}else{
            $industry=CompanyIndustryModel::getSelect(['pid'=>0]);
            View::assign('industry',$industry);
            $area=AreaModel::getCache();
            View::assign('area',$area);
    		View::assign('id',$id);
	        return View::fetch('add');
    	}
    }
    public function edit($id)
    {
    	if (request()->isPost()) {
            $D=request()->post();
            $rule =   [
                'path'         	=> 'require',
                'status'        => 'require',
            ];
            $msg  =   [
                'path.require'     	=> '请上传图片',
                'status.require'    => '请选择状态',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $AdsModel=AdsModel::where(['id'=>$id])->find();;
            $AdsModel->title        =   empty($D['title'])?'ads_'.time():$D['title'];
            $AdsModel->path        	=   $D['path'];
            $AdsModel->url        	=   $D['url'];
            $AdsModel->sort        	=   intval($D['sort'])?intval($D['sort']):9999;
            $AdsModel->col          =   intval($D['col'])?intval($D['col']):1;
            $AdsModel->status       =   $D['status'];
            $AdsModel->ads_icon     =   $D['ads_icon'];
            $AdsModel->industry     =   $D['industry'];
            if (strtotime($D['start_time'])){
                $AdsModel->start_time=strtotime($D['start_time'].' 00:00:00');
            }else{
                $AdsModel->start_time=null;
            }
            if (strtotime($D['end_time'])){
                $AdsModel->end_time=strtotime($D['end_time'].' 23:59:59');
            }else{
                $AdsModel->end_time=null;
            }
            if (!empty($D['area'])&&count($D['area'])>=3) {
                $AdsModel->province  = $D['area'][0];
                $AdsModel->city      = $D['area'][1];
                $AdsModel->area      = $D['area'][2];
            }else{
                $AdsModel->province  = null;
                $AdsModel->city      = null;
                $AdsModel->area      = null;
            }
            if($AdsModel->save()){
                return $this->ajaxReturn('保存成功');
            }else{
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
    	}else{
            $industry=CompanyIndustryModel::getSelect(['pid'=>0]);
            View::assign('industry',$industry);
            $area=AreaModel::getCache();
            View::assign('area',$area);
            $AdsModel=AdsModel::where(['id'=>$id])
                ->withAttr('start_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })
                ->withAttr('end_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })->find();
            View::assign('Find',$AdsModel);
	        return View::fetch('add');
    	}
    }
    public function setAdsStatus($id,$status)
    {
        $AdsModel=AdsModel::where(['id'=>$id])->find();
        $AdsModel->status=$status;
        $AdsModel->start_time=null;
        $AdsModel->end_time=null;
        if ($AdsModel->save()) {
            return $this->ajaxReturn('保存成功');
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function setAdsCol($id,$col)
    {
        $AdsModel=AdsModel::where(['id'=>$id])->find();
        $AdsModel->col=$col;
        if ($AdsModel->save()) {
            return $this->ajaxReturn('保存成功');
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function setAdsIcon($id,$status)
    {
        $AdsModel=AdsModel::where(['id'=>$id])->find();
        $AdsModel->ads_icon=$status;
        if ($AdsModel->save()) {
            return $this->ajaxReturn('保存成功');
        }else{
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function del($id)
    {
        $AdsModel=AdsModel::where(['id'=>$id])->find();
        if ($AdsModel->delete()) {
            return $this->ajaxReturn('已删除');
        }else{
            return $this->ajaxReturn('删除失败，请重试',-200);
        }
    }
}
