<?php

namespace DAO;
use Our\Common;


/**
 * 用户数据层
 */
class MemberMessageModel extends \DAO\AbstractModel {
    

    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_member_message';

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';
    public function init(){
            parent::setDb();
    }
    /**
     * 根据用户编号查找数据
     *
     * @param int $userId
     * @return array
     */
    public function find($userId) {

        $redis = \Redis\Db0\UserModel::getInstance();
        $user  = $redis->find($userId);
        if (!$user) {
            $mysql = \Mysql\UserModel::getInstance();
            $user  = $mysql->find($userId);
            if ($user) {
                $redis->update($userId, $user);
            }
        }
        return $user;
    }
    //原生方法
    public function query(){
        echo 23424;exit;
        $mysql=\Mysql\Slave\MemberModel::getInstance();
        $res=$mysql->query("select * from han_member");
        echo json_encode($res);
        exit;
    }
    //对主库进行操作
    public function update($sql){
        $mysql=\Mysql\UserModel::getInstance();
        $res=$mysql->excute($sql);
        return $res;
    }
    public function getOneByWhereWithField($where,$field){
        $memberMessage=$this->db->select($field)->from($this->_tableName)->where($where)->order('gmt_create','DESC')->fetchOne();
        return $memberMessage;
    }
    public function getOneByMemberIdAndType($memberId,$type,$field='*'){
        $where=Common::format(" member_id={0} and message_type={1} and status>=0",$memberId,$type);
        $memberMessage=$this->getOneByWhereWithField($where,$field);
        return $memberMessage;

    }
    /**
     * 根据类型获得未读消息数量
     *
     * @ccw
     */
    public function getUnreadCountByMemberIdAndType($memberId,$type){
        $where['member_id']=$memberId;
        $where['message_type']=$type;
        $where['status']=0;
        $count=$this->db->from($this->_tableName)->where($where)->fetchNum();
        return $count;
    }
    /**
     * 根据类型获得消息列表
     *
     * @ccw
     */
    public function getListByMemberIdAndType($memberId,$type,$pageIndex=0,$pageSize=20){
        $where=Common::format(" member_id={0} and message_type={1} and status>=0",$memberId,$type);
        $order=array(
            'gmt_create'=>'DESC',
        );
       $returnData= $this->lists($where,$order,'*',$pageIndex,$pageSize);
        return $returnData;
    }
    /**
     * 类实例
     *
     * @var \DAO\UserModel
     */
    private static $_instance = null;

    /**
     * 获取类实例
     *
     * @return \DAO\UserModel
     */
    public static function getInstance() {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

}
