<?php

defined('BASEPATH') OR exit('No direct script access allowed');



class Topic extends Api_Controller{

    private $source = array(

        '1' => '站长自建',

        '2' => '云话题',

        '3' => '用户自建'

    );

    //禁言用户组ID

    public $groupids_banned = array(4, 5, 6);

    public function __construct()

    {

        parent::__construct();

        $this->load->helper('my_api');

        $this->load->model('sharecircle/topic_model', 'topic');

        $this->load->model('sharecircle/post_model', 'post');

        $this->load->model('sharecircle/comment_model', 'comment');

        $this->load->model('sharecircle/post_like_model', 'post_like');

        $this->load->model('sharecircle/topic_post_model', 'topic_post');

        $this->load->model('sharecircle/topic_participation_model', 'topic_participation');

        $this->load->model('sharecircle/post_img_model', 'post_img');

        $this->load->helper('url_helper');

    }



    //话题详情分享页

    public function topic_detail($tid) {

        $this->load->helper('url_helper');

        $topic_info = array();

        $topic_info = $this->topic->get_one($tid, 'id,uid, username, title, listimg, detailimg, extracount, involcount, piccount');

        $part_info = array();

        $topic_info['part_uids'] = array();

        $part_info = $this->topic_participation->get_by_tid($tid, 'uid', 9);

        if (!empty($part_info)) {

            foreach ($part_info as $value) {

                $topic_info['part_uids'][] = $value['uid'];

            }

        } else {

            $topic_info['part_uids'] = array();

        }

        //获取该话题的帖子列表10个

        $topic_post = array();

        $post_ids = array();

        $topic_post = $this->topic_post->get_by_tid($tid, 10);

        if (!empty($topic_post)) {

            foreach ($topic_post as $value) {

                $post_ids[] = $value['pid'];

            }

            $post_info = array();

            $post_imgs = array();

            $imgs_pid = array();

            $field = 'id, uid, username, content, createtime';

            $post_info = $this->post->get_by_pids($post_ids, $field);

            $post_imgs = $this->post_img->get_img_by_pids($post_ids);

            if (!empty($post_imgs)) {

                foreach ($post_imgs as $value) {

                    $imgs_pid[$value['postid']][] = $value;

                }

            }

//            print_r($post_ids);

            if (!empty($post_info)) {

                $this->load->helper('my_api');

                foreach ($post_info as $key => $value) {

                    $post_info[$key]['ctime_format'] = format_date($value['createtime']);

                    if (isset($imgs_pid[$value['id']]) && !empty($imgs_pid[$value['id']])) {

                        $post_info[$key]['img_arr'] = $imgs_pid[$value['id']];

                    }

                    //为帖子内容中的话题添加蓝色样式

                    $content = smiley_parse($value['content'], asset_url('h5/images/smilies'));

                    $post_info[$key]['content'] = preg_replace('/(\#.*?\#)/', '<span class="topic_title">$1</span>', $content);

                }

            }

            $topic_info['post_info'] = $post_info;

        } else {

            $topic_info['post_info'] = array();

        }

//        echo '<pre>';

//        print_r($topic_info);die();

//        $topic_info['timestamp'] = time();

        $topic_info['domain'] = 'http://' . $_SERVER['HTTP_HOST'];

        $topic_info['timestamp'] = time();

        //为了解决title冲突问题
        $topic_info['title_conflict'] = $topic_info['title'];

        $this->load->view('sharecircle/h5/topic_detail_share', $topic_info);

    }

   

    //获取话题详情页信息

    public function get_topic_detail_info($tid,$uid,$page,$pagesize,$offset,$auth,$ttitle,$gag) {

        $topic_info = array();

        if($page==1){

        if($tid){

            $topic_info = $this->topic->get_one($tid, 'title, detailimg, involcount,extracount, piccount');

        }


        if($ttitle && !$tid){

            $topic_info = $this->topic->get_one_by_title($ttitle, 'id,title, detailimg,involcount, extracount, piccount');

            $tid=$topic_info['id'];

        }


        if($topic_info['extracount']!=0){

              $topic_info['involcount']=$topic_info['extracount'];

              unset($topic_info['extracount']);

        }else{

            unset($topic_info['extracount']);

        }

        if($tid){

           $topic_info['topic_weiurl']=base_url()."index.php?/api/sharecircle/topic/topic_detail/".$tid;  

        }

        //获取参与人

        $part_info = array();

        $topic_info['part_avatars'] = array();

        $part_info = $this->topic_participation->get_by_tid($tid, 'uid', 10);

        if (!empty($part_info)) {

            foreach ($part_info as $value) {

                $topic_info['part_avatars'][] = UC_API."/avatar.php?uid=".$value['uid']."&size=small&random=".time(); 

            }

        } else {

            $topic_info['part_avatars'] = array();

        }

        }

        $topic_post = array();

        $post_ids = array();

        $topic_post = $this->topic_post->get_by_tid($tid, '');
            $topic_info['posts_pagecount']=0;
            $topic_info['posts_totalpage']=0;
        if (!empty($topic_post)) {
            foreach ($topic_post as $value) {

                $post_ids[] = $value['pid'];

            }

            $post_info = array();

            $field = 'id,uid, username, content, createtime';

            $post_info = $this->post->get_by_pids_tz($post_ids, $field,$pagesize,$offset);

            $topic_info['posts_pagecount']=count($post_ids);

            $topic_info['posts_totalpage']=ceil(count($post_ids)/$pagesize);

            if (!empty($post_info)) {

            //     $this->load->helper('my_api');

            //     foreach ($post_info as $key => $value) {

            //         $post_info[$key]['ctime_format'] = format_date($value['createtime']);

            //         if (!empty($value['img'])) {

            //             $post_info[$key]['img_arr'] = explode(',', $value['img']);

            //         }

            //     }

            // }

                $uids=array();

                $postids=array();

            foreach ($post_info as $he => $da) {

                $postids[]=$da['id'];

                $uids[]=$da['uid'];

            }

            $uids=array_unique($uids);

            $temp=$this->post_like->get_by_postids($postids);//点赞情况

            $userlevels=$this->user->get_usergroup_levels($uids);//用户等级

            //$topicid=$this->topic_post->get_tids_by_pids($postids);//帖子话题id

            $postimgs=array();

            $postimgs=$this->post_img->get_img_by_pids($postids,'');//帖子图片

                foreach ($post_info as &$val) {

                $postimg=array();

                $val['showtime']=format_date($val['createtime']);

                // $temp=$this->post_like->get_by_postid($val['id'],'');

                $rep=$this->comment->get_by_postid($val['id'],6);

                // $topicid=$this->topic_post->get_tids_by_pid($val['id']);

                // $postimgs=$this->post_img->get_post_img_by_postid($val['id']);

                  if($postimgs){

                   foreach ($postimgs as $kit => $vit) {

                    if($vit['postid']==$val['id']){

                   $path_thumb=$vit['path'].".small.jpg";

                   $postimg[]=array('height'=>$vit['height'],'thumb'=>$path_thumb,'thumb_image'=>$vit['path'],'weight'=>$vit['width']);

                    }

                }

                }

                $repls=array();

                $likeusername=array();

                $prat=0;//获取点赞图标亮否

                $praid='';//获取要点击点赞时的用户id

                   if($temp){

                    foreach ($temp as $king => $box) {

                    if($box['postid']==$val['id']){

                    $likeusername[]=$box['username'];

                    if($box['uid']==$uid&&$auth==1){

                        $prat=1;

                    }

                    }



                }

                }

                 if($prat==0&&$auth==1){

                    $praid=$uid;

                }

                if($rep){

                foreach ($rep as $k => $v) {

                       $repl=array();

                       $repl['author']=$v['username'];

                       $repl['authorid']= $v['uid'];

                       $repl['requtename']=$v['to_username'];

                       $repl['message']= $v['content'];

                       $repl['pid']= $v['postid'];

                       $repls[] = $repl;

                }

            }

                //$value['sortlist']=array(array('height'=>'100','thumb'=>$val['listimg'],'thumb_image'=>$val['detailimg'],'weight'=>'100'));

                $val['praiselist']=$likeusername;

                $val['message']=$val['content'];

                unset($val['content']);

                $val['sortlist']=$postimg;

                $val['pratimes']=count($temp);

                $val['prat']=$praid;

                $val['praid']=$prat;

                $val['gag']=$gag;

                $val['replies']=count($repls);

                $val['replylist']=$repls;

                $val['usergroup_level'] = $userlevels[$val['uid']];

                $val['avatar']=UC_API."/avatar.php?uid=".$val['uid']."&size=small&random=".time();

                $val['sharetext']="分享的内容";

                $val['weiurl']=base_url()."index.php?/api/sharecircle/post/post_detail_share/".$val['id'];

                $val['createtime']=format_date($val['createtime']);

                $val['authorid']=$val['uid'];

                $val['author']=$val['username'];

                unset($val['createtime']);

                unset($val['uid']);

                unset($val['username']);

            }

            unset($val);

            $topic_info['post_info'] = $post_info;
            
        } else {

            $topic_info['post_info'] = array();

        }

    }

        return $topic_info;

    }



    //话题详情页接口

    public function get_topic_detail() {

         //$tid=$this->input->post("tid");

         // $uid=1989;

        $ttitle='';

        $tid=1;

        $auth=0;

        // $ttitle="标题1";

        $gag=0;//用户禁言与否

        $tid = $this->get_param('tid');

        $ttitle = $this->get_param('tname');


        $user_groupid=$this->user->checkLogin($this->get_param('auth'));

        if($user_groupid){

           $auth=1;

           if(in_array($user_groupid,$this->groupids_banned)){

            $gag=1;

            }

        }

        $tpage=$this->get_param('page');

        $page = $tpage ? $tpage : 1;

        //$uid=1989;

         $page = $page < 1 ? 1 : $page;

        //$page=1;

        $pagesize=10;

        $offset = ($page - 1) * $pagesize;

        $uid = $this->user->uid;

        $topic_info = array();

        $topic_info = $this->get_topic_detail_info($tid,$uid,$page,$pagesize,$offset,$auth,$ttitle,$gag);

        // if(empty($topic_info['posts_pagecount'])==""||empty($topic_info['posts_totalpage'])==""){
        //     $topic_info['posts_totalpage']=0;
        //     $topic_info['posts_pagecount']=0;
        // }
        $this->odz_result($topic_info);

    }



    //坛友圈'最新'页面接口

    public function get_topic_index(){

        //处理页数和分页数量

        $auth=0;

        $gag=0;//用户禁言与否

        $user_groupid=$this->user->checkLogin($this->get_param('auth'));

        if($user_groupid){

            $auth=1;

            if(in_array($user_groupid,$this->groupids_banned)){

            $gag=1;

            } 

        }

        $uid = $this->user->uid;

        $username = $this->user->username;

        $op=$this->get_param('op');//操作字段 判断请求的是话题 还是帖子

        $tpage=$this->get_param('page');

        $page = $tpage ? $tpage : 1;

        // $uid=1000;

        $page = $page < 1 ? 1 : $page;

        $pagesize=10;

        $offset = ($page - 1) * $pagesize;

        $result=array();

        //人气

        $hot_post=array();

        $offsetc=0;

        $limit=8;

        $where[]='isdelete=0';

        $fileds = 'id,content,username,uid,readcount';

        $query=$this->post->get_post_list($where,$fileds,$limit, $offsetc);

            foreach ($query as $vas) {

                $img=$this->post_img->get_img_by_pid($vas['id']);

                $hot_post[]=array(

                    'id'=>$vas['id'],

                    'content'=>$vas['content'],

                    'uid'=>$vas['uid'],

                    'username'=>$vas['username'],

                    'img'=>$img[0]['path'].'.small.jpg',

                    'readcount'=>$vas['readcount']

                    );

            }

            $result['hot_post']=$hot_post;

            //人气end

        if($op == 'index' || $op == 'topics')//获取话题

        {   $result['hastopic']=0;

            $where=array();

            $topics_info=array();

            $where["isdelete"] = 0;

            $where["isrec"]=1;

            $fileds = 'id,title,involcount,piccount,extracount,createtime,listimg';

            //根据uid来查询是否有发帖

            $ontopic=$this->post->get_one_by_uid($uid);

            if(!empty($ontopic)&&$auth==1){

                $result['hastopic']=1;

            }

            $pagesizeb=12;

            $offsetb = ($page - 1) * $pagesizeb;

            $page_count=$this->topic->get_count($where);

            $topics_info=$this->topic->get_topic($where,$fileds,$pagesizeb,$offsetb);

             foreach ($topics_info as &$val) {

                $val['createtime']=format_date($val['createtime']);

                unset($val['createtime']);

           if($val['extracount']!=0){

              $val['involcount']=$val['extracount'];

              unset($val['extracount']);

        }else{

            unset($val['extracount']);

        }

            }

            unset($val);

            $result['topics_pagecount']=$page_count;

            $result['topics_totalpage']=ceil($page_count/$pagesizeb);

            $result['topics']=$topics_info;

        }

        if($op == 'index' || $op == 'posts')//获取帖子

        {

            $where=array();

            $posts_info=array();

            $postids=array();

            $where[]='isdelete=0';

            $fileds = 'id,uid,username,content,likecount,responsecount,createtime';

            $post_pagecount=$this->post->get_count($where);

            $posts_info=$this->post->get_post_lists($where,$fileds,$pagesize,$offset);

            $uids=array();

            $postids=array();

            foreach ($posts_info as $he => $da) {

                $postids[]=$da['id'];

                $uids[]=$da['uid'];

            }

            if($postids){

            $uids=array_unique($uids);

            $temp=$this->post_like->get_by_postids($postids);//点赞情况

            $userlevels=$this->user->get_usergroup_levels($uids);//用户等级

            $postimgs=array();

            $postimgs=$this->post_img->get_img_by_pids($postids,'');//帖子图片



            foreach ($posts_info as &$value) {

                $postimg=array();

                $value['showtime']=format_date($value['createtime']);

                $rep=$this->comment->get_by_postid($value['id'],6);//帖子回复

                if($postimgs){

                   foreach ($postimgs as $kit => $vit) {

                    if($vit['postid']==$value['id']){

                   $path_thumb=$vit['path'].".small.jpg";

                   $postimg[]=array('height'=>$vit['height'],'thumb'=>$path_thumb,'thumb_image'=>$vit['path'],'weight'=>$vit['width']);

                    }

                }

                }

                $repls=array();

                $likeusername=array();

                $prat=0;//获取点赞图标亮否

                $praid='';//获取要点击点赞时的用户id

                if($temp){

                    foreach ($temp as $king => $box) {

                    if($box['postid']==$value['id']){

                    $likeusername[]=$box['username'];

                    if($box['uid']==$uid&&$auth==1){

                        $prat=1;

                    }

                    }



                }

                }

                 if($prat==0&&$auth==1){

                    $praid=$uid;

                }

                if($rep){

                   foreach ($rep as $k => $v) {

                       $repl=array();

                       $repl['author']=$v['username'];

                       $repl['authorid']= $v['uid'];

                       $repl['requtename']=$v['to_username'];

                       // $repl['author']= $v['to_username'];

                       // $repl['authorid']= $v['to_uid'];

                       $repl['message']= $v['content'];

                       $repl['pid']= $v['postid'];

                       $repls[] = $repl;

                }

                }

                $value['praiselist']=$likeusername;

                $value['message']=$value['content'];

                unset($value['content']);

                $value['sortlist']=$postimg;

//                unset($value['img']);

                $value['pratimes']=count($temp);

                $value['prat']=$praid;

                $value['praid']=$prat;

                $value['gag']=$gag;

                $value['replies']=count($repls);

                $value['replylist']=$repls;

                $value['usergroup_level'] = $userlevels[$value['uid']];

                $value['avatar']=UC_API."/avatar.php?uid=".$value['uid']."&size=small&random=".time();

                $value['sharetext']="分享的内容";

                $value['weiurl']=base_url()."index.php?/api/sharecircle/post/post_detail_share/".$value['id'];

                $value['createtime']=format_date($value['createtime']);

                $value['authorid']=$value['uid'];

                $value['author']=$value['username'];

                unset($value['createtime']);

                unset($value['uid']);

                unset($value['username']);

            }

            unset($value);

        }

            $result['posts']=$posts_info;

            $result['posts_totalpage']=ceil($post_pagecount/$pagesize);

            $result['posts_pagecount']=$post_pagecount;

        }

        $this->odz_result($result);

    }

    //点击话题时展示的接口

    public function topic_list(){

         $auth=0;

        if($this->user->checkLogin($this->get_param('auth'))){

           $auth=1;

        }

        $uid = $this->user->uid;

        $username = $this->user->username;

        $op=$this->get_param('op');//操作字段 判断请求的是话题 还是帖子

        $tpage=$this->get_param('page');

        $page = $tpage ? $tpage : 1;

        $page = $page < 1 ? 1 : $page;

        $pagesize = 20;

        $offset = ($page - 1) * $pagesize;

        $result=array();

        $tuijian=array();

        $topic_info=array();

        $sor=array();

        $sort=array();

        $fileds = 'id,title,involcount,extracount,piccount,createtime,listimg';

        if($op=="index"){

            $jointopic=0;

            $topic=array();

            if(isset($uid)&&$uid!=0){

               $topic=$this->topic_participation->get_tid_by_uid($uid); 

            }

            if(!empty($topic)&&$auth==1){

                $jointopic=1;

            }

            if($topic){

                foreach ($topic as $value) {

                $temp=$this->topic->get_one_fileds($value['tid'],$fileds);

                if(!empty($temp)){

					$temp['createtime']=$value['createtime'];

                    $topic_info[]=$temp;

                }

                }

                if(!empty($topic_info)){

                    foreach ($topic_info as  &$val) {

                $sort[]=$val['createtime'];

                if($val['extracount']!=0){

                    $val['involcount']=$val['extracount'];

                    unset($val['extracount']);

                }else{

                    unset($val['extracount']);

                }

                $val['createtime']=format_date($val['createtime']);

                unset($val['createtime']);

                    }

                unset($val);

                array_multisort($sort,SORT_DESC,$topic_info);

                $topic_info=array_slice($topic_info,0,2);

                }

            }

      $result['hasjointopic']=$jointopic;

      $result['jointopic']=$topic_info;//参与的话题

        }

      $result['auth']=$auth;

      if($op=="isrectopic"||$op=="index"){

         $where["isdelete"] = 0;

         $where["isrec"]=1;

         $page_count=$this->topic->get_count($where);

         $tuijian=$this->topic->get_topic($where,$fileds,$pagesize,$offset);

         foreach ($tuijian as &$box) {

              if($box['extracount']!=0){

                    $box['involcount']=$box['extracount'];

                    unset($box['extracount']);

                }else{

                    unset($box['extracount']);

                }

             $box['createtime']=format_date($box['createtime']);

             unset($box['createtime']);

        }

         unset($box);

         $result['isrectopic']=$tuijian;

         $result['totalpage']=ceil($page_count/$pagesize);

         $result['page_count']=$page_count;

      }

     $this->odz_result($result);

    }

     public function get_topic_by_name(){

        $name = $this->get_param('tname');

        $limit = "-1";

        $offset = 0;

        $where=array();

        $where[]="isdelete=0";

        $where[] ='position("'.$name.'" in `title`)';

        $fields = 'id,title,listimg';

        $topic=$this->topic->get_topic_list($where, $fields, $limit, $offset);

        $this->odz_result(array('topic'=>$topic));

    }



    //获取话题参与用户

    public function topic_part_users() {

        $tid = $this->get_param('tid');

        $users = array();

        $uids = array();

        $signatures = array();

        $user_signatures = array();

        $users = $this->topic_participation->get_by_tid($tid, '', 999999);

        if (!empty($users)) {

            foreach ($users as $key => $value) {

                $uids[] = $value['uid'];

            }

            $signatures = $this->user_model->get_user_signature_from_discuz($uids);

            if (!empty($signatures)) {

                foreach ($signatures as $value) {

                    $user_signatures[$value['uid']] = $value['sightml'];

                }

            }


            foreach ($users as $key => $value) {

                $users[$key]['avatar'] = UC_API . "/avatar.php?uid=".$value['uid']."&size=small&random=".time();

                if (!empty($user_signatures[$value['uid']])) {

                    $users[$key]['signature'] = $user_signatures[$value['uid']];

                } else {

                    $users[$key]['signature'] = '这个人很懒，什么也没留下';

                }

            }

        }



//        echo '<pre>';

//        print_r($users);

        $this->odz_result(array('users' => $users));

    }

    //有站点修改域名时，修改话题和帖子图片中的域名
    public function modify_img_domain() {
        $old_domain = 'http://www.pinketianxia.com';
        $new_domain = 'http://yishuiapp.com';

        $new_listimg = '';
        $new_detailimg = '';
        $param = array();
        $data = array();
        $data = $this->topic->getall();
        $this->load->model('sharecircle/post_img_model', 'post_img');
        $info = $this->post_img->getall();
        echo '<pre>';
        print_r($data);
        print_r($info);
        die();
        if (!empty($data)) {
            echo '修改topic表中域名，id: ';
            foreach ($data as $key => $value) {
                if (!empty($value['listimg'])) {
                    $param['listimg'] = str_replace($old_domain, $new_domain, $value['listimg']);
                } else {
                    $param['listimg'] = $value['listimg'];
                }
                if (!empty($value['detailimg'])) {
                    $param['detailimg'] = str_replace($old_domain, $new_domain, $value['detailimg']);
                } else {
                    $param['detailimg'] = $value['detailimg'];
                }
                $ret = $this->topic->update($param, $value['id']);
                echo $ret;
            }
        }

        $pa = array();
        $info = array();
        $this->load->model('sharecircle/post_img_model', 'post_img');
        $info = $this->post_img->getall();
        if (!empty($info)) {
            echo '<br><br>修改post_img表中域名，id: ';
            foreach ($info as $key => $value) {
                if (!empty($value['path'])) {
                    $pa['path'] = str_replace($old_domain, $new_domain, $value['path']);
                } else {
                    $pa['path'] = $value['path'];
                }
                $ret = $this->post_img->update($pa, $value['id']);
                echo $ret;
            }
        }


        echo '<br><br>执行完成。';
        // echo '<pre>';
        // print_r($pa);
        // print_r($info);
    }



}

