<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use util\Tree;
use app\admin\model\Menu;

use app\admin\model\Category as CategoryModel;


class Advertisement extends Base
{
    public function index($tab = 1, $id = 0){
        $category = CategoryModel::order('listorder')->select();
        $categoryList = array();
        foreach ($category as $key => $value) {


 
            $categoryList[] = $value->toArray(); //对象转数组
            //一对一关联出对应模型
            if( 0 != $categoryList[$key]['isend'] && 0 != $categoryList[$key]['modelid']){
                $categoryList[$key]['models'] = $value->models->toArray(); //关联模型用时才加载
            }

        }
        $tree = new Tree();
        $tree->tree($categoryList,'id','parentid','catname');
        $categoryArray = $tree->getArray();
        
        $this->assign('category',$categoryArray);
        // // 编辑菜单，默认加载
        if( 3 == $tab ){
            // 获取所要编辑菜单的信息
            $info = Db::name('advertisement')->where('id',$id)->find();
            if($info!=null && is_array($info)){
                $this->assign('info',$info);
            }
        }
        return view();
    }
   


  
    public function getDataTables() {
        

        //获取请求过来的数据
        $getParam = request()->param();

        $draw = $getParam['draw'];

        //排序
        $orderSql = 'id desc';

        //自定义查询参数
        $extra_search = $getParam['extra_search'];

        // 获取表名
        $tablename = 'advertisement';
        // 总记录数
        $recordsTotal = Db::name($tablename)->count();
        //过滤条件后的总记录数
        $search = $getParam['search']['value'];
        $recordsFiltered = strlen($search) ?  Db::name($tablename)->where($extra_search,'like','%'.$search.'%')->count() : $recordsTotal;

        //分页
        $start = $getParam['start']; //起始下标
        
        $length = $getParam['length']; //每页显示记录数

        //根据开始下标计算出当前页
        $page = intval($start/$length) + 1;
        $config = ['page'=>$page, 'list_rows'=>$length];
        $list = Db::name($tablename)->where($extra_search,'like','%'.$search.'%')->order($orderSql)->paginate(null,false,$config);
        $lists = [];
        if(!empty($list)){
            foreach ($list as $key => $value) {
                $lists[$key] = $value;
                
                $lists[$key]['advename'] =str_cut($value['advename'],20);

               
              if($lists[$key]['advepic'] ==NULL){
                  $lists[$key]['advepic']= "请上传广告图片！";
                   
              }else{
               

                 $imgdata=explode(',',$value['advepic']);
                $listimg='';
              
                $listimg="<img src='/public/uploads/".$imgdata[0]."' width='80' >";
             
               $lists[$key]['advepic']= $listimg;
              }
               

                if($lists[$key]['adveban']==0){
                    $lists[$key]['adveban'] ="<button class='btn btn-info btn-circle btn-lg' id='".$value['id']."'  type='button' ><i class='fa fa-check'></i></button>";
                }else{
                    $lists[$key]['adveban'] ="<button class='btn btn-info btn-circle btn-lg' id='".$value['id']."'  type='button' ><i class='fa fa-times'></i></button>";
                }

                if($lists[$key]['advewz']==0){
                    $lists[$key]['advewz'] ="请选择位置";
                }
                if($lists[$key]['advewz']==1){
                    $lists[$key]['advewz'] ="幻灯片";
                }
                if($lists[$key]['advewz']==2){
                    $lists[$key]['advewz'] ="列表图组";
                }
                if($lists[$key]['advewz']==3){
                    $lists[$key]['advewz'] ="单页";
                }
                if($lists[$key]['advewz']==4){
                    $lists[$key]['advewz'] ="列表页";
                }
                if($lists[$key]['advewz']==5){
                    $lists[$key]['advewz'] ="内容页";
                }
                $lists[$key]['operate'] = "<a href='". url('index',['id'=>$value['id'], 'tab'=>3]) ."' title='编辑'><i class='fa fa-edit text-navy'></i></a>&nbsp;&nbsp;
                <a name='delete' href='". url('del',['id'=>$value['id'], 'catid'=>$value['catid']]) ."' title='删除'><i class='fa fa-trash-o text-navy'></i></a>";
            }
        }

        $data = array(
            "draw"=>$draw,
            "recordsTotal"=>$recordsTotal, //数据总数
            "recordsFiltered"=>$recordsFiltered, //过滤之后的记录总数
            "data"=>$lists
        );

        echo json_encode($data);
    }

    

    


   
    public function add($requireField = '', $requireFieldName = '') {
        
        if(request()->isPost()) {
          $data=input('post.');

             if($data['advename']==null)
           {
                $this->error("广告名称不能为空！");
           }
             
            $newname=$data['advename'];
            $searchname=Db::name('advertisement')->where('advename',$newname)->find();
            if(!empty($searchname)){
               $this->error('广告名称已存在！');
                exit();
            }

            if($_FILES['advepic']['tmp_name']){
                $data['advepic']=$this->upload();
            }
           $add=db('advertisement')->insert($data);
           if($add){
             $this->success('广告提交成功！',url('index'));
           }else{
              $this->error('广告提交失败！');
           }
          return view();
        }
    }


    public function edit($id = 0, $requireField = '', $requireFieldName = '') {
        
        if(request()->isPost()) {
          $data=input('post.');
          // var_dump($data);
          // die;
             if($data['advename']==null)
           {
                $this->error("广告名称不能为空！");
           }
             if(preg_match("/\\d+/",$data['advename'])==1)
              {
                 $this->error("广告必须包含中文！");//全数字
              }
             if($_FILES['advepic']['tmp_name']){
                $oldadrts=db('advertisement')->field('advepic')->find($data['id']);
                $oldadrtImg=IMG_UPLOADS.$oldadrts['advepic'];
                
                if(file_exists($oldadrtImg)){
                    @unlink($oldadrtImg);
                }
                $data['advepic']=$this->upload();
            }
           $save=db('advertisement')->where('id',$id)->update($data);
           if($save!== false){
             $this->success('广告修改成功！',url('index'));
           }else{
              $this->error('广告修改失败！');
           }

          
          return view();
        }
    }
    

     public function del($id)
    {
        $advert=db('advertisement');
        $advertres=$advert->field('advepic')->find($id);
        $advertImg=IMG_UPLOADS.$advertres['advepic'];
        if(file_exists($advertImg)){
            @unlink($advertImg);
         }
         $del=$advert->where('id',$id)->delete();
         if ($del){
             $this->success('删除广告成功！',url('index'));
         }else{
             $this->error('删除广告失败！');
         }
    }
    

     //上传图片
    public function upload(){
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file('advepic');
    
    // 移动到框架应用根目录/public/uploads/ 目录下
    if($file){
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            return $info->getSaveName();
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
            die;
        }
    }
}

  


  

}
