<?php

namespace DAO;
use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;
use Our\Push;
use Our\RedisHelper;


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


    /**
     * 表名
     *
     * @var stringgetListByUserIdAndType
     */
    protected $_tableName = 'han_message_history';

    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'id';
    public function init(){

    }

    /**
     * 根据用户id和用户类型获取聊天的列表
     *
     * @ccw
     *
     */
    public function getListByMemberIdAndToIdAndToType($memberId,$selfType,$toId,$toType,$field='*',$pageIndex=0,$pageSize=20){
        $where=Common::format(" ((fromId={0} and toId={1} and toType={2} and fromType={3} and isDel not in(-1,2)) or (fromId={4} and toId={5}  and fromType={6} and toType={7} and isDel not in(-1,3)))",$memberId,$toId,$toType,$selfType,$toId,$memberId,$toType,$selfType);
        parent::setDb();
        $messages=$this->lists($where,array('gmtCreate'=>'desc'),$field,$pageIndex,$pageSize);
        return $messages;
    }

    public function getUnreadCountByToIdAndToType($toId,$toType){
        $this->setDb($this->dbName);
        $where=Common::format(" (toId={0} and status ={2})",$toId,$toType,ApiConst::unread);
        $num=$this->db->from($this->_tableName)->select("count(*) as count")->where($where)->fetchNum();
        return $num?$num:ApiConst::zero;
    }

    public function getOneById($id,$field='*'){
        parent::setDb();
        $where[$this->_primaryKey]=$id;
        $memberHistory= $this->db->select($field)->where($where)->from($this->_tableName)->fetchOne();
        return $memberHistory?$memberHistory:array();
    }
    public function update($id,$field,$value){
        parent::setDb(DbNameConst::masterDBConnectName);
        $where[$this->_primaryKey]=$id;
        $res=$this->db->update($this->_tableName)->where($where)->set($field,$value)->execute();
        return $res;
    }

    public function updateByWhere($where,$data){

        parent::setDb(DbNameConst::masterDBConnectName);
        $res=$this->db->update($this->_tableName)->where($where)->rows($data)->execute();
        return $res;
    }

    public function updateByFromIdAndSelfTypeAndToIdAndToType($fromId,$fromType,$toId,$toType){
        if($fromId!=$toId){
            $where=Common::format(" (((fromId={0} and toId={1} and toType={2} and fromType={3}) and status=0))",$toId,$fromId,$fromType,$toType);
        }else{
            $where=Common::format(" (((fromId={0} and toId={1} and toType={2} and fromType={3}) and status=0))",$toId,$fromId,$toType,$fromType);
        }
        $data['status']=ApiConst::read;
        return $this->updateByWhere($where,$data);
    }
    //发送消息$data数据格式请参考api里面的data数据
    public function sendMessage($data,$uid=false){
        $pushHelper=Push::getInstance();
        if($uid!==false){
            $pushHelper->add($data);
            $pushHelper->uid=$uid;
        }else{
            $pushHelper->addList($data);
        }
        return $pushHelper->sendTcpMessage();

    }
    public function add($data){
        $res=$this->db->insert($this->_tableName)->rows($data)->execute();
        return $res;
    }
    public function convertMessage($message){
        $message = unserialize($message);
        $message['title'] = !empty($message['title']) ? $message['title'] : '';
        $message['content'] = !empty($message['content']) ? base64_decode($message['content']) : '';
        if(!empty($message['buttons'])){
            $timeDiff=TIMESTAMP-$message['createTime'];
            foreach($message['buttons'] as &$button){
                if($button['type']==ApiConst::messageButtonTypeReciverButton){
                    if($timeDiff>(ApiConst::tenMinSecond-ApiConst::oneMinute)){
                        $button['showType']=ApiConst::messageButtonShowTypeGray;
                    }
                }
                if($button['type']==ApiConst::messageButtonTypeConfirmButton ){
                    if($timeDiff>(ApiConst::oneDaySecond)){
                        $button['showType']=ApiConst::messageButtonShowTypeGray;
                    }
                }
            }
        }
        return $message;

    }

    /**
     * 类实例
     *
     * @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;
    }

}
