<?php

namespace DAO;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\Common;
use Our\DbNameConst;


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


    /**
     * 表名
     *
     * @var string
     */
    protected $_tableName = 'han_message_one';
    /**
     * 主键
     *
     * @var string
     */
    protected $_primaryKey = 'message_id';
    public function init(){

    }
    /**
     * 根据用户编号查找数据
     *
     * @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,$db=DbNameConst::salveDBConnectName){
        parent::setDb($db);
        $memberMessage=$this->db->select($field)->from($this->_tableName)->where($where)->order('gmtUpdate','DESC')->fetchOne();
        return $memberMessage;
    }


    public function getListByUserIdAndType($id,$field='*',$pageIndex=0,$pageSize=20){
        $where[$this->_primaryKey]=$id;
        $memberMessage=$this->db->select($field)->from($this->_tableName)->where($where)->fetchOne();
        return $memberMessage?$memberMessage:array();
    }
    public function getListByMemberId($memberId,$field='*',$pageIndex,$pageSize){
        if(empty($memberId)|| $memberId!=(int)$memberId){
            return false;
        }
        parent::setDb();
        $where=Common::format(" fromId={0} or toId={1}",$memberId,$memberId);
        $messages=$this->lists($where,array('gmtUpdate'=>'desc'),$field,$pageIndex,$pageSize);
        return $messages;
    }
    public function update($data,$where=array()){
        $res=$this->db->update($this->_tableName)->rows($data)->where($where)->execute();
        return $res;
    }
    public function updateUnreadField($fromId,$fromType,$toId,$toType){
        $where=Common::format(" (fromId={0} and fromType={1} and toId={2} and toType={3}) or (fromId={4} and fromType={5} and toId={6} and toType={7})",$fromId,$fromType,$toId,$toType,$toId,$toType,$fromId,$fromType);
        $one=$this->getOneByWhereWithField($where,"*",DbNameConst::masterDBConnectName);
        if(isset($one['toId']) && $one['toId']==$fromId){
            $updateData['toUnreadCount']=ApiConst::zero;
            if($this->update($updateData,$where)!==false){
                return true;
            }else{
                ErrorModel::throwException(ErrorModel::throwException(CodeConfigModel::updateReadedError));
            }

        }else{
            $updateData['fromUnreadCount']=ApiConst::zero;
            if($this->update($updateData,$where)!==false){
                return true;
            }else{
                ErrorModel::throwException(ErrorModel::throwException(CodeConfigModel::updateReadedError));
            }
        }
    }
    public function insertOrUpdate($data){
        $where=Common::format(" (fromUserId={0} and fromType={1} and toUserId={2} and toType={3}) or (fromUserId={4} and fromType={5} and toUserId={6} and toType={7})",$data['fromUserId'],$data['fromType'],$data['toUserId'],$data['toType'],$data['toUserId'],$data['toType'],$data['fromUserId'],$data['fromType']);
        $one=$this->getOneByWhereWithField($where,"*",DbNameConst::masterDBConnectName);
        if(isset($one['toUserId']) && $one['toUserId']==$data['fromUserId']){
            $insertSql=Common::format("insert into {0}(`fromId`,`toUserId`,`toUserName`,`toType`,`fromUserId`,`fromUserName`,`fromType`,`message`,`fromUnReadCount`,`toUnReadCount`,`gmtCreate`,`gmtUpdate`,`toId`) VALUES({1},{2},'{3}',{4},{5},'{6}',{7},'{8}',{9},{10},{11},{12},{13}) ON DUPLICATE KEY UPDATE message='{14}',fromUnReadCount=fromUnReadCount+1,gmtUpdate={15} ",$this->_tableName,$data['toId'],$data['fromUserId'],$data['fromUserName'],$data['fromType'],$data['toId'],$data['toUserName'],$data['toType'],$data['message'],ApiConst::zero,ApiConst::one,time(),time(),$data['toId'],$data['message'],time());
        }else{
            $insertSql=Common::format("insert into {0}(`fromId`,`toUserId`,`toUserName`,`toType`,`fromUserId`,`fromUserName`,`fromType`,`message`,`fromUnReadCount`,`toUnReadCount`,`gmtCreate`,`gmtUpdate`,`toId`) VALUES({1},{2},'{3}',{4},{5},'{6}',{7},'{8}',{9},{10},{11},{12},{13}) ON DUPLICATE KEY UPDATE message='{14}',toUnReadCount=toUnReadCount+1,gmtUpdate={15} ",$this->_tableName,$data['fromId'],$data['toUserId'],$data['toUserName'],$data['toType'],$data['fromUserId'],$data['fromUserName'],$data['fromType'],$data['message'],ApiConst::zero,ApiConst::one,time(),time(),$data['toId'],$data['message'],time());
        }
        $res=$this->db->update($this->_tableName)->query($insertSql);
        if($res){
            $id=$this->db->getInsertId();
            return $id;
        }else{
            return false;
        }
    }


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

}
