<?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 questionAModel extends X {
    private $tbname = "question";
    private $pkid = "queid";

    
    public function getList($items) {
        $where = " WHERE 1=1".$items['searchsql'];
        $start = ($items['page']-1)*$items['pagesize'];
        $countsql = "SELECT COUNT(*) AS my_count".
                    " FROM ".DB_PREFIX."{$this->tbname} AS v".$where;
        $total = parent::$obj->fetch_count($countsql);
        if ($total > 0) {
            $sql = "SELECT v.*, t.topicname FROM ".DB_PREFIX."{$this->tbname} AS v".
                    " LEFT JOIN ".DB_PREFIX."question_topic AS t ON v.topicid=t.topicid".
                    $where." ORDER BY v.topicid DESC,v.orders ASC LIMIT {$start}, {$items['pagesize']}";
            $_data = parent::$obj->getall($sql);
        }
        return array($total, $_data);
    }

    
    public function getData($id) {
        $sql = "SELECT * FROM ".DB_PREFIX."{$this->tbname} WHERE {$this->pkid}='{$id}'";
        return parent::$obj->fetch_first($sql);
    }

    
    public function doAdd($args) {
        $res = false;
        $queid = parent::$obj->fetch_newid("SELECT MAX({$this->pkid}) FROM ".DB_PREFIX."{$this->tbname}", 1);
        $args = array_merge(array(
                "queid"=>$queid,
                "addtime"=>time(),
            ), $args);
        $res = parent::$obj->insert(DB_PREFIX."{$this->tbname}", $args);
        if (true === $res) {
            $this->updateQuetionNums($args['topicid']);
        }
        return $res;
    }

    
    public function doEdit($id, $args) {
        $res = parent::$obj->update(DB_PREFIX."{$this->tbname}", $args, "{$this->pkid}='{$id}'");
        if (true === $res) {
            $this->updateQuetionNums($args['topicid']);
        }
        return $res;
    }

    
    public function doDel($id) {
        parent::$obj->query("DELETE FROM ".DB_PREFIX."question_option WHERE queid='{$id}'"); 
        return parent::$obj->query("DELETE FROM ".DB_PREFIX.$this->tbname." WHERE queid='{$id}'");
    }

    
    public function updateQuetionNums($topicid) {
        $_count = 0;
        $_count_sql = "SELECT COUNT(*) AS my_count FROM ".DB_PREFIX."question".
                        " WHERE topicid='{$topicid}'";
        $_count = parent::$obj->fetch_count($_count_sql);
        $up_array = array(
            "quenums"=>$_count,
        );
        return parent::$obj->update(DB_PREFIX."question_topic", $up_array, "topicid='{$topicid}'");
    }
}
?>
