<?php
// +----------------------------------------------------------------------
// | 奇乐自媒体内容管理系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com
// +----------------------------------------------------------------------
// | 官方论坛：http://bbs.qilecms.com
// +----------------------------------------------------------------------
// | Author:奇乐网络
// +----------------------------------------------------------------------
// | 版权说明：本产品为免费版，使用请保留底部版权
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\controller;
use think\DB;
use think\facade\Request;
class Article extends Category
{
	public function set(){
		return $this->fetch();
	}

	public function index(){
      $alias = 'a';        //需要别名时写别名，不需要的时候留空 
      $defaultWhere = '';
      $param = $this->request->param();
      $cid = $param['cid'];
      if($cid){
        $defaultWhere .=$alias.".cid = '$cid'";
      }
      $defaultOrder = 'a.create_time desc';
    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where   = $SearchFormData['where'];
      $order   = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];

//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'aid', //字段名
                  'name'    =>'文章ID', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'title',
                  'name'    =>'文章标题',
                  'alias'   => $alias,
                  ],
                  [
                  'field'   =>'cname',
                  'name'    =>'分类名称',
                  'alias'   => 'b',
                  ]
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'发布时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ]
              ];
//单个字段筛选
    $customSingleField =[
                            // [
                            //  'name'=>'审核状态',
                            //  'field' => 'status', 
                            //  'data'  => [ 0 =>'等待审核',1=>'正常',2=>'审核失败'],
                            //  'alias'=>$alias,
                            // ]
                       ]; 
// 组件字段组筛选
    $groupData = [
                    [
                     'name'      =>'属性',     //用户组
                     'table'     =>'article_attr', //表名
                     'field_id'  =>'attr_value',   //字段ID
                     'field_name'=>'attr_name',  //字段名
                     'alias'     => $alias,
                    ],
        
              ];
     $orderData   = [
                 [
                 'name'     =>'发布时间正序',
                 'field'    =>'create_time',  //字段名
                 'orderby'  =>'asc',     //注册排序
                 'alias'    => $alias,         //数据表别名
                 ],
            [
                 'name'     =>'发布时间倒序',
                 'field'    =>'create_time',  //字段名
                 'orderby'  =>'desc',     //注册排序
                 'alias'    => $alias,         //数据表别名
                 ],
               ];  


     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $lists = DB::name('article')->alias('a')->field('a.aid,a.uid,a.title,a.attr_value,a.username,a.create_time,a.status,b.cname')->join('article_category b','a.cid = b.cid',"LEFT")->where($where)->order($order)->paginate($pageNum);
     $page = $lists->render();
     $list = $lists->toArray()['data'];
     foreach($list as $k => $v){
       $result = DB::name('article_attr')->where('attr_value','in',$v['attr_value'])->select();
       $list[$k]['attr'] = $result;
     }
    
     $this->assign('page', $page);
     $this->assign('list', $list);
    return $this->fetch();
	} 


	public function add(){
    //获得属性
      $param = $this->request->param();
     if($this->request->isPost()){

           $cate = $param['cate'];
           $attrValue =$param['attr_value'];
              // 构造表单
            $param = [
            'cid'=>'cid',
            'title'=>'title',
            'source'=>'source',
            'introduction'=>'introduction',
            'hits'=>'hits',
            'content'=>'content',
            'username'=>'username',
            'thumb'=>'thumb',
            'status'=>'status',
            'keywords'=>'keywords',
            'video_thumb'=>'video_thumb',
            'video_url'=>'video_url'
             ]; 
            $data  = $this->buildParam($param);
           //表单验证
           $rule =[
              'cid'=>'require',
              'title'=>'require|max:150',
              'username' =>'require',
              'content'=>'require',
            ];
            $msg= [
             'cid.require' =>'请选择文章分类',
             'title.require' =>'文章标题不能为空',
             'title.max' =>'文章标题不能超过150个字',
             'username.require' =>'请选择文章作者',
             'content.require' =>'文章内容不能为空',
            
            ];
             $error = $this->checkSubmit($data,$rule,$msg);  
            if($error){
                return error_json($error);
             }
                 if(!empty($cate['three'])){
                        $data['cid'] = $cate['three'];
                  }else{
                     if(!empty($cate['two'])){
                         $data['cid'] = $cate['two'];
                     }else{
                        if(!empty($cate['one'])){
                         $data['cid'] = $cate['one']; 
                        }
                     }
                  }
           if(!empty($attrValue)){
              $data['attr_value']  = implode(',',$attrValue);
            } 
            $data['tag'] =  get_keywords($data['title'],$data['content'],3);  //生成标签
            $thumbArr    =  get_images_url(htmlspecialchars_decode($data['content'])); //提取缩略图
              if(empty($thumbArr)){
                return error_json('至少上传一张图片'); 
               }
            if(is_array($thumbArr)){
              $data['thumb']  = !empty($thumbArr[0])?$thumbArr[0]:''; //缩略图1
              $data['thumb1'] = !empty($thumbArr[1])?$thumbArr[1]:''; //缩略图2
              $data['thumb2'] = !empty($thumbArr[2])?$thumbArr[2]:''; //缩略图3
            }
            $map['username'] = $data['username'];
            $userinfo = model('user')->infoData($map);
            if(empty($userinfo)){
                 return error_json('用户不存在，请添加一个新用户'); 
             }
            $data['uid'] = $userinfo['uid'];

            $data['create_time'] = time();
            $result =  model('article')->addData($data);
          
       if($result){
              return success_json('添加成功');
             
            }else{
               return error_json('添加失败'); 
            }
           
   
        }else{

           //获得文章属性
           $articleAttr =  model('articleAttr')->getArticleAttr();
           $this->assign('articleAttr',$articleAttr);
           return $this->fetch();

        }

	}


	public function edit(){
      $param = input();
     if($this->request->isPost()){
             $param = input("post.");
              
               //表单验证
           $rule =[
              'cid'=>'require',
              'title'=>'require|max:150',
              'content'=>'require',
            ];
            $msg= [
             'cid.require' =>'请选择文章分类',
             'title.require' =>'文章标题不能为空',
             'title.max' =>'文章标题不能超过150个字',
             'content.require' =>'文章内容不能为空',
            
            ];
                 $error = $this->checkSubmit($param,$rule,$msg);  
                if($error){
                    return error_json($error);
                 }
                if(!empty($param['attr_value'])){
                  $param['attr_value']  = implode(',',$param['attr_value']);
                }
                   
                $userinfo = model('user')->infoData(['username'=>$param['username']]);

               if(empty($userinfo)){
                 return error_json('当前用户不存在，请添加一个新用户'); 
                }
                $data['uid'] = $userinfo['uid'];
                $data['cid']   =$param['cid'];
                $data['title']   =$param['title'];
                $data['source']  =$param['source'];
                $data['introduction'] = $param['introduction'];
                $data['hits']     = $param['hits'];
                $data['content']  = $param['content'];
                $data['attr_value'] =$param['attr_value'];


                $data['tag'] =  get_keywords($data['title'],$data['content'],3);  //生成标签

                $thumbArr    =  get_images_url(htmlspecialchars_decode($data['content'])); //提取缩略图
               
                 if(empty($thumbArr)){
                return error_json('至少上传一张图片'); 
               }
               if(is_array($thumbArr)){
                 $data['thumb']  = !empty($thumbArr[0])?$thumbArr[0]:''; //缩略图1
                 $data['thumb1'] = !empty($thumbArr[1])?$thumbArr[1]:''; //缩略图2
                 $data['thumb2'] = !empty($thumbArr[2])?$thumbArr[2]:''; //缩略图3
                }
               
                $data['aid'] = $param['aid'];
     
                $data['username'] = $param['username'];
                $data['update_time'] = time();
                $data['status'] = isset($param['status'])?$param['status']:'';
                $where['aid'] =$data['aid'];
                $result =  model('article')->editData($data,$where);
                if($result){
                    return success_json('更新成功');
                     
                  }else{
                     return error_json('更新失败');
                  }
                  

         }else{
               if(!$param['aid']){  return error_json('请求参数错误');}
                     $article = model('article')->getArticleInfo($param['aid']);
              $attrArr = explode(',',$article['attr_value']);
               //获得文章属性
              $articleAttr =  model('article_attr')->getArticleAttr();
              $this->assign('articleAttr',$articleAttr);
          
              $this->assign('attrArr',$attrArr);
              $this->assign('article',$article);
              return $this->fetch();
         }

	}
	public function del(){
     $param = $this->request->param();
     if(!$param['aid']){  return error_json('请求参数错误');    }

     $res= $this->delData('article','aid');
     if($res){
      return success_json('删除成功');
     }else{
      return error_json($res);
     }

	}
  
   public  function category(){

      return parent::category();
   }

   public  function categoryAdd(){

      return parent::categoryAdd();
   }
   public  function categoryEdit(){

      return parent::categoryEdit();
   }
   public  function categoryUpdate(){
  
      return parent::categoryUpdate();
   }
   public  function categoryDel(){

      return parent::del();
   }


//文章评论操作
   public function comment(){
     $post = $this->request->param(); 
    if($post){
            $keywords = $post['keywords'];
            $group_id   = $post['group_id'];
            $status   =$post['status'];
            foreach($post['date'] as $k=>$v){
              $post['date'][] = strtotime($v);
            }
              $date = $post['date'];
              $where = 1;
             if($keywords['name']){
                 $where .= " and ".$keywords['name']." = '".$keywords['value']."'";
              }
             
             if($status){
                $where .=' and status = '.$status;
             }
        
      }else{
          $where .='';
      }  
// 排序
      $order = "create_time desc";

  // 关键词筛选  格式：字段名称加显示名称
     $keywords  = ['comment_id'=>'评论ID','nickname'=>'昵称','article_id'=>'文章ID'];

 //日期筛选    
     $date = [ ];
// 自定义单个字段筛选
     $customSingleField = []; 
 //数据库某个表中的字段筛选
     $sqlTable = [];

     $this->assign('sqlTable',$sqlTable);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('keywords',$keywords);
     $this->assign('date',$date);
     $pageNum = 10;
     $list = DB::name('article_comment')->alias('a')->join('article b','a.article_id = b.aid',"LEFT")->field('a.comment_id,a.uid,a.content,a.username,a.create_time,a.status,a.zan,a.ip,b.title')->where($where)->order($order)->paginate($pageNum);
     $page = $list->render();
     $this->assign('page', $page);
     $this->assign('list', $list);
    return $this->fetch();
  }

// 文章评论添加
   public function commentAdd(){
    
  }



// 文章评论修改
   public function commentEdit(){
    $param = input();
    if(!$param['comment_id']){  return error_json('缺少请求参数');    }
    if(!$param['status']){  return error_json('缺少请求参数');    }
    $data['status'] = $param['status'];
    $where['comment_id'] =$param['comment_id'];
    $res = model('article_comment')->editData($data,$where);
     if($res){
      return success_json('更新成功');
     }else{
      return error_json('更新失败');
     }
  }

// 文章评论删除
   public function commentDel(){

             $param = $this->request->param();
           if(!$param['comment_id']){  return error_json('请求参数错误');    }

         return  $res= $this->delData('articleComment',"comment_id");
            echo  model('articleComment')->getLastSql();
           if($res){
            return success_json('删除成功');
           }else{
            return error_json($res);
           }


  }
}