    <?php
/**
 * Copyright (C) LJCMS All rights reserved.
 * <E-Mail：aspcms@qq.com>
 * Url http://www.liangjing.org
 *     http://www.8CMS.com
 * Update 2016.03.19
 */

class control extends indexbase {


    public function control_run() {
        $_tpl = "question_index";
        if (false === $this->existsTplFile($_tpl)) {
            $this->control_list();
        }
        else {
            $this->getMeta('ch_question_index');
            $page_title = $this->metawrap['title'];
            $page_description = $this->metawrap['description'];
            $page_keyword = $this->metawrap['keyword'];
            $var_array = array(
                'page_title'=>$page_title,
                'page_description'=>$page_description,
                'page_keyword'=>$page_keyword,
            );
            TPL::assign($var_array);
            TPL::display($this->getTPLFile($_tpl));
        }
    }


    public function control_list() {
        $this->pagesize = intval(parent::$cfg['questionpagesize']) > 0 ? intval(parent::$cfg['questionpagesize']) : 10;
        $searchsql = "";

        $model = parent::model("quetopic", "im");

        list($total, $data) = $model->getList(
            array(
                "page"=>$this->page,
                "pagesize"=>$this->pagesize,
                "searchsql"=>$searchsql,
                "orderby"=>"",
            )
        );
        unset($model);


        $this->getMeta('ch_question_list');
        $page_title = $this->metawrap['title'];
        $page_description = $this->metawrap['description'];
        $page_keyword = $this->metawrap['keyword'];
        $url = XRequest::getPhpSelf()."?c=question&a=list";
        $showpage = XPage::index($total, $this->pagesize, $this->page, $url, 10);

        foreach($data as $k=>$v){
            $len=strlen($v['intro']);
            $data[$k]['len']=$len;
            if(!empty($v['intro'])){
                $data[$k]['intro']=substr($v['intro'],0,180).'....';
            }

        }
        array_multisort(array_column($data,'len'),SORT_DESC,$data);
        $data=array_slice($data,0,3);
        $parent=[
            'modalias'  =>'question',
            'url'  =>'/index.php?c=question&cid=9',
        ];
        $var_array = array(
            'page'=>$this->page,
            'nextpage'=>$this->page+1,
            'prepage'=>$this->page-1,
            'pagecount'=>ceil($total/$this->pagesize),
            'pagesize'=>$this->pagesize,
            'total'=>$total,
            'showpage'=>$showpage,
            'question'=>$data,
            'page_title'=>$page_title,
            'page_keyword'=>$page_keyword,
            'page_description'=>$page_description,
            'parent'=>$parent,

        );

//        echo '<pre>';
//        print_r($var_array);die;

        TPL::assign($var_array);
        TPL::display($this->getTPLFile("question_list"));
    }


    public function control_detail() {
        $path_info = $GLOBALS['path_info'];
        if (!empty($path_info) && isset($path_info['id'])) {
             $id = intval($path_info['id']);
        } else {
             $id = XRequest::getInt('id');
        }
        
        if ($id < 1) {
            XHandle::halt("参数错误", "", 1);
        }

        $model = parent::model("quetopic", "im");
        $_data = $model->getOneData($id);
        if (empty($_data)) {
            XHandle::halt("对不起，信息不存在或未审核", "", 1);
        }
        $previous_item = $model->getPrevious($id);


        if (!empty($previous_item)) {
            $url_item='index.php?c=question&a=detail&id='.$previous_item['topicid'];
            $previous_item = "<a href='".$url_item."'>".$previous_item['topicname']."</a>";
        }
        else {
            $previous_item = '没有了';
        }
        $next_item = $model->getNext($id);

        if (!empty($next_item)) {
            $url_next='index.php?c=question&a=detail&id='.$next_item['topicid'];
            $next_item = "<a href='".$url_next."'>".$next_item['topicname']."</a>";
        }
        else {
            $next_item = '没有了';
        }
        unset($model);

        $this->getMeta('ch_question_detail');
        $page_title = str_ireplace(
            array('{title}'), array($_data['topicname']), $this->metawrap['title']
        );
        $page_description = str_ireplace(
            array('{title}'), array($_data['topicname']), $this->metawrap['description']
        );
        $page_keyword = str_ireplace(
            array('{title}'), array($_data['topicname']), $this->metawrap['keyword']
        );

        # 查询问卷题目
        $searchsql = "";
        if ($_REQUEST['id'] > 0) {
            $id=$_REQUEST['id'];
            $searchsql .= " AND v.topicid='{$id}'";
        }
        if (!empty($this->stitle)) {
            $searchsql .= " AND v.title LIKE '%".$this->stitle."%'";
        }
        $question_model= parent::model('question', "am");
        $question_where=[
            'page'=>$this->page,
            'pagesize'=>$this->pagesize,
            'searchsql'=>$searchsql
        ];
        $question_list=$question_model->getList($question_where);
        $qu=$question_list[1];
        if(!empty($qu)){
            foreach($qu as $k=>$v){
                $queid=$v['queid'];
                $topicid=$v['topicid'];
                $sql="select * from 8cms_question_option where queid=$queid";
                $arr=parent::$obj->getall($sql);
                foreach($arr as $ke=>$val){
                    if($queid==$val['queid']){
                        $qu[$k]['option_list']=$arr;
                    }
                }
            }
        }


        $var_array = array(
            'question'=>$_data,
            'page_title'=>$page_title,
            'page_keyword'=>$page_keyword,
            'page_description'=>$page_description,
            'previous_item'=>$previous_item,
            'next_item'=>$next_item,
            'qu'=>$qu,
            'id'=>$id,
        );

        TPL::assign($var_array);
        TPL::display($this->getTPLFile("question_detail"));
    }


    public function control_poll() {
        $res = false;
        $topicid = XRequest::getInt("topicid");

        if ($topicid < 1) {
            XHandle::halt("参数错误", "", 1);
        }

        $model = parent::model("question", "im");
        if (false === $model->checkCanPoll($topicid)) {
            XHandle::halt("您已投过票了", "", 1);
        }
        $question_list = $model->getVolist("v.topicid='{$topicid}'", "", 1000);

        foreach ($question_list as $key=>$value) {
            $_option_id = XRequest::getInt("question_".$value['queid']);
            if ($_option_id > 0) {
                $res = $model->doPolls($value['queid'], $_option_id);
            }
        }
        if (true === $res) {

            $model->addPollLog($topicid);
            XHandle::halt("投票成功", parent::$urlpath."index.php?c=question&a=detail&id=".$topicid, 0);
        }
        else {
            XHandle::halt("投票失败", "", 1);
        }
    }


    public function control_vote(){
        $queid=$_REQUEST['queid'];
        $topicid=$_REQUEST['topicid'];
        $optionid=$_REQUEST['optionid'];
        if(empty($queid)){
            print_r(json_encode(['msg'=>'缺少queid参数','code'=>10001]));
            die;
        }
        if(empty($topicid)){
            print_r(json_encode(['msg'=>'缺少topicid参数','code'=>10002]));
            die;
        }
        if(empty($optionid)){
            print_r(json_encode(['msg'=>'缺少optionid参数','code'=>10003]));
            die;
        }
        if(!is_numeric($queid) || !is_numeric($topicid) || !is_numeric($optionid) ){
            print_r(json_encode(['msg'=>'非法参数','code'=>10003]));
            die;
        }

        # 修改投票总数
        $sql="select * from 8cms_question where topicid='$topicid' and queid='$queid'";
        $question_list=parent::$obj->fetch_first($sql);

        $args=[
            'totalpolls'=>$question_list['totalpolls']+1,
        ];

        $res1=parent::$obj->update("8cms_question", $args, "queid='{$queid}'");

        # 修改 单独投票数
        $sql2="select * from 8cms_question_option where optionid='$optionid' and queid='$queid'";
        $option_list=parent::$obj->fetch_first($sql2);
        $argS2=[
            'polls'=>$option_list['polls']+1,
        ];
        $res2=parent::$obj->update("8cms_question_option", $argS2, "optionid='{$optionid}'");

        $question_list['totalpolls']=$question_list['totalpolls']+1;
        $option_list['polls']=$option_list['polls']+1;
        $data=[
            'question_list'=>$question_list,
            'option_list'=>$option_list,
        ];
        if($res1&&$res2){
            print_r(json_encode(['msg'=>'投票成功','code'=>200,'data'=>$data]));
            die;
        }else{
            print_r(json_encode(['msg'=>'投票失败','code'=>10004]));
            die;
        }
    }

}
?>
