<?php

namespace Business\Message;


use DAO\MemberMessageModel;
use DAO\MessageModel;
use Error\CodeConfigModel;
use Error\ErrorModel;
use Our\ApiConst;
use Our\ArrayConst;
use Our\Common;
use Our\DbNameConst;
use Our\ImageConst;
use Zend\Json\Server\Error;


/**
 * 用户登录业务
 */
class MessageServiceModel extends \Business\AbstractModel
{
    private $memberMessageDao;
    private $messageDao;
    public $memberId;
    private $memberMessageField = 'message_id,message_title,message_body,message_type,tpl_type,record_id';
    private $baseRedis;

    public function init()
    {

    }


    /**
     * 登录业务
     *
     * @var \Business\User\LoginV2Model
     */
    private static $_instance = null;

    /**update
     * 单例模式获取类实例
     *
     * @ccw
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     * 适配数据
     *
     * @ccw
     */
    public function getConvertArray($memberMessage, $message, $defalt = false)
    {
        if ($defalt) {
            return array(
                'messageId' => ApiConst::zero,
                'messageTitle' => '身边店',
                'messageContent' => ArrayConst::meg[$message['message_type']],
                'messageType' => $message['message_type'],
                'gmtCreate' => TIMESTAMP,
                'isRead' => ApiConst::one,
                'unReadCount' => ApiConst::zero,
                'id' => ApiConst::zero,
                'messageTplId' => ApiConst::zero,

            );
        } else {
            return array(
                'messageId' => $message['message_id'],
                'messageTitle' => $message['message_title'] ? $message['message_title'] : '',
                'messageContent' => $message['message_body'],
                'messageType' => $message['message_type'],
                'gmtCreate' => $memberMessage['gmt_create'],
                'isRead' => $memberMessage['status'],
                'id' => $message['record_id'],
                'messageTplId' => $message['tpl_type'],

            );
        }


    }

    public function getUnreadCountByMemberIdAndType($toId)
    {
        $memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();
        $unredMessageCount=$memberDb0Redis->tableHGet($toId,'unread_message_count');
        if($unredMessageCount===false){
            $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
            $unredMessageCount = $messageHistoryDao->getUnreadCountByToIdAndToType($toId);
            $memberDb0Redis->tableHset($toId,'unread_message_count',$unredMessageCount);
        }
        return $unredMessageCount;

    }

    /**
     * 根据消息类型获得一条消息，已经未读消息数量
     *
     * @ccw
     */
    public function getOneByType($memberId, $type)
    {
        $this->memberMessageDao = MemberMessageModel::getInstance();
        $this->messageDao = MessageModel::getInstance();
        $memberMessage = $this->memberMessageDao->getOneByMemberIdAndType($memberId, $type);
        if ($memberMessage) {
            $message = $this->messageDao->getOneById($memberMessage['message_id'], $this->memberMessageField);
            //获得未读的消息数量
            $count = $this->memberMessageDao->getUnreadCountByMemberIdAndType($memberId, $type);
            if ($message) {
                $messages = $this->getConvertArray($memberMessage, $message);
            }
        }
        if ($messages) {
            $data['unreadCount'] = $count;
            $data['list'] = $messages;
            return $data;
        }
        return new \stdClass();
    }

    public function getAvatar($type, $userid = 0, $db = DbNameConst::masterDBConnectName)
    {
        $avatar = '';
        if ($type == ApiConst::systemMessageType) {
            $avatar = Common::getStaticFile(ImageConst::sysAvatarName, ImageConst::systemAvatar, ImageConst::imageDomain);
        }
        if ($type == ApiConst::orderMessageType) {
            $avatar = Common::getStaticFile(ImageConst::orderAvatarName, ImageConst::systemAvatar);
        }
        if ($type == ApiConst::deliveryMessageType) {
            $avatar = Common::getStaticFile(ImageConst::expressAvatarName, ImageConst::systemAvatar, ImageConst::imageDomain);
        }
        if ($type == ApiConst::storeMessageType) {
            $store = \DAO\StoreModel::getInstance();
           // $storeData = \Our\RedisHelper::cachedFunction(\Redis\Db5\OrderRedisModel::getInstance(), array(&$store, 'getInfoById'), array($userid, $store->detailField), \Our\ApiConst::oneDaySecond,array($userid));
            $storeData=$store->getStoreInfoCache($userid);
            $avatar = $storeData['store_label'];
            if ($avatar) {
                $avatar = \Our\Common::getStaticFile($avatar, \Our\ImageConst::storeLabel, 'ossHost');
            } else {
                $avatar = \Our\Common::getStaticFile(ImageConst::defaultStoreLabelName, ImageConst::defaultPath);
            }
            // $avatar = $store->getInfoById($userid, 'store_label', 'store_label');
           // $avatar = $storeData[ApiConst::one];
        }

        if ($type == ApiConst::memberMessageType || $type == ApiConst::serviceMessageType) {
            $member = \DAO\MemberModel::getInstance();
            $memerAvatar = $member->getInfo($userid, 'member_avatar');
            $avatar = $member->getMemberAvatarUrl($userid, $memerAvatar);
        }
        return $avatar;
    }

//    public function __destruct()
//    {
//        $store = \DAO\StoreModel::getInstance();
//        $member = \DAO\MemberModel::getInstance();
//        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
//        $mesageOneDao = \DAO\MessageOneModel::getInstance();
//        $store->unsetDb();
//        $member->unsetDb();
//        $messageHistoryDao->unsetDb();
//        $mesageOneDao->unsetDb();
//    }
//
//    public function unsetDb()
//    {
//        $store = \DAO\StoreModel::getInstance();
//        $member = \DAO\MemberModel::getInstance();
//        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
//        $mesageOneDao = \DAO\MessageOneModel::getInstance();
//        $store->unsetDb();
//        $member->unsetDb();
//        $messageHistoryDao->unsetDb();
//        $mesageOneDao->unsetDb();
//    }

    /**
     * 获得全部类型消息，每种消息一条数据，以及每种消息的未读条数
     *
     * @ccw
     */
    public function getList($memberId, $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize)
    {
        $messageOneDao = \DAO\MessageOneModel::getInstance();
        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $messageOneList = $messageOneDao->getListByMemberId($memberId, '*', $pageIndex, $pageSize);
        foreach ($messageOneList['list'] as &$val) {
            $self = $this->getUserByMemberIdAndSelfType($val['fromId'], $val['fromType']);
            $toMember = $this->getUserByMemberIdAndSelfType($val['toId'], $val['toType']);
            $val['toAvatar'] = !empty($toMember['avatar'])?$toMember['avatar']:'';
            $val['message'] = $messageHistoryDao->convertMessage($val['message']);
            $val['fromAvatar'] = $self['avatar'];
//                $val['toAvatar']=$this->getAvatar($val['toType'],$val['toId']);
//                $val['fromAvatar']=$this->getAvatar($val['fromType'],$val['fromId']);
        }
        return $messageOneList;
    }

    public function getUserByMemberIdAndSelfType($memberId, $type)
    {
        $member = array();
        if ($type == ApiConst::systemMessageType || $type == ApiConst::orderMessageType || $type == ApiConst::deliveryMessageType) {
            $member['uid'] = $type;
            $member['name'] = ArrayConst::messageName[$type];
        }
        if ($type == ApiConst::storeMessageType) {
            $storeDao = \DAO\StoreModel::getInstance();
            $store = $storeDao->getInfoByMemberId($memberId, 'store_id,store_name,store_label');
            $member['uid'] = $store['store_id'];
            $member['name'] = $store['store_name'];
        }
        if ($type == ApiConst::memberMessageType || $type == ApiConst::serviceMessageType) {
            $memberDao = \DAO\MemberModel::getInstance();
            $member = $memberDao->getOneByMemberId($memberId, 'member_id,member_name');
            $member['uid'] = $member['member_id'];
            $member['name'] = $member['member_name'];
        }
        $member['type'] = $type;
        $member['avatar'] = $this->getAvatar($type, $member['uid'], DbNameConst::salveDBConnectName);
        return $member;
    }

    public function getMemberIdByOtherIdAndType($otherId, $type)
    {
        if($type==ApiConst::storeMessageType){
            $storeDao=\DAO\StoreModel::getInstance();
            $condition['store_id'] = $otherId;
            $store = \Our\RedisHelper::cachedFunction(\Redis\Db6\StoreRedisModel::getInstance(), array(&$storeDao, 'getInfo'), array($condition), ApiConst::oneDaySecond, array($otherId));
            return $store['member_id'];
        }
        ErrorModel::throwException(CodeConfigModel::paramsError);
    }

    /**
     * 根据用户的消息类型获得消息列表
     *
     * @ccw
     */
    public function getMemberList($memberId, $selfType, $toId, $otherId, $toType = ApiConst::systemMessageType, $field = '*', $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize)
    {
        if($memberId==$toId){
            $toType=ApiConst::storeMessageType;
            $selfType=ApiConst::memberMessageType;
        }
        $messageHistory = \DAO\MessageHistoryModel::getInstance();
        $self = $this->getUserByMemberIdAndSelfType($memberId, $selfType);
        if (empty($toId)) {
            $toId =$this->getMemberIdByOtherIdAndType($otherId,$toType);
        }
        $toMember = $this->getUserByMemberIdAndSelfType($toId, $toType);
        $returnMemeber['toId'] = (int)$toId;
        $returnMemeber['toUserId'] = (int)$toMember['uid'];
        $returnMemeber['toUserName'] = $toMember['name'];
        $returnMemeber['toType'] = (int)$toMember['type'];
        $returnMemeber['toAvatar'] = $toMember['avatar'];
        $returnMemeber['fromId'] = $memberId;
        $returnMemeber['fromUserId'] = (int)$self['uid'];
        $returnMemeber['fromUserName'] = $self['name'];
        $returnMemeber['fromType'] = (int)$self['type'];
        $returnMemeber['fromAvatar'] = $self['avatar'];
        $memberMessages = $messageHistory->getListByMemberIdAndToIdAndToType($memberId, $selfType, $toId, $toType, $field, $pageIndex, $pageSize);
        foreach ($memberMessages['list'] as &$val) {
            $val['message'] = $messageHistory->convertMessage($val['message']);
        }
        $memberMessages['list'] = array_reverse($memberMessages['list']);
        $returnMemeber['messages'] = $memberMessages;
        return $returnMemeber;
    }

    /**
     * 删除用户消息
     *
     * @ccw
     */
    public function remove($memberId, $messageHistoryId)
    {
        $memageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $memberHistory = $memageHistoryDao->getOneById($messageHistoryId);
        $isSuccess = false;
        if ($memberHistory['fromId'] == $memberId) {
            if ($memberHistory['isDel'] == ApiConst::recieveRemove) {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'isDel', ApiConst::remove);
            } else {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'isDel', ApiConst::sendRemove);
            }
        }
        if ($memberHistory['toId'] == $memberId) {
            if ($memberHistory['isDel'] == ApiConst::sendRemove) {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'isDel', ApiConst::remove);
            } else {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'isDel', ApiConst::recieveRemove);
            }
        }
        return $isSuccess;
    }
    /**
     * 删除用户消息
     *
     * @ccw
     */
    public function removeAll($memberId, $fromType,$toId,$toType)
    {
        $memageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $where=Common::format(" (fromId={0} and fromType={1} and toId={2} and toType={3} and isDel={4}) or (fromId={2} and fromType={3} and toId={0} and toType={1} and idDel={5})",$memberId,$fromType,$toId,$toType,ApiConst::sendRemove);
        $data['isDel']=ApiConst::remove;
        $memageHistoryDao->updateByWhere($where,$data);
        $where=Common::format(" fromId={0} and fromType={1} and toId={2} and toType={3} and isDel={4}",$memberId,$fromType,$toId,$toType,ApiConst::zero);
        $data['isDel']=ApiConst::sendRemove;
        $memageHistoryDao->updateByWhere($where,$data);
        $where=Common::format(" fromId={2} and fromType={3} and toId={0} and toType={1} and isDel={4}",$memberId,$fromType,$toId,$toType,ApiConst::zero);
        $data['isDel']=ApiConst::recieveRemove;
        $memageHistoryDao->updateByWhere($where,$data);
        return true;
    }
    /**
     * 获得消息按钮
     *
     * @ccw
     */
    public function getMessageButton($id, $buttonId)
    {
        $memageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $memberHistory = $memageHistoryDao->getOneById($id);
        if (empty($memberHistory)) {
            ErrorModel::throwException(CodeConfigModel::noExistMessage);
        }
        $message = unserialize($memberHistory['message']);
        $buttonIndex = $buttonId - ApiConst::one;
        $button = $message['buttons'][$buttonIndex];
        if (empty($button)) {
            ErrorModel::throwException(CodeConfigModel::noExistButton);
        }
        $retrunButton = $button;
        $button['status'] = ApiConst::messageButtonIsClick;
        $button['showType'] = ApiConst::messageButtonShowTypeGray;
        $message['buttons'][$buttonIndex] = $button;
        $message = serialize($message);
        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $messageHistoryDao->update($id, 'message', $message);
        return $retrunButton;
    }


    public function update($fromId, $fromType, $toId, $toType)
    {
        if($fromId==$toId){
            $fromType=ApiConst::memberMessageType;
            $toType=ApiConst::storeMessageType;
        }
        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $messageOneDao = \DAO\MessageOneModel::getInstance();
        $messageOneDao->setDb(DbNameConst::masterDBConnectName);
        $messageOneDao->updateUnreadField($fromId, $fromType, $toId, $toType);
        $isSuccess = $messageHistoryDao->updateByFromIdAndSelfTypeAndToIdAndToType($fromId, $fromType, $toId, $toType);
        $memberDb0Redis=\Redis\Db0\MemberRedisModel::getInstance();
        if($isSuccess){
                $isSuccess=-1*$isSuccess;
                $memberDb0Redis->tableHIncrBy($fromId,'unread_message_count',$isSuccess);
        }

        return $isSuccess;
    }

    public function checkIsCanSend($memberId)
    {
        $memberDao = \DAO\MemberModel::getInstance();
        $sendTime = $memberDao->getInfo($memberId, 'sendTime');
        if (!empty($sendTime)) {
            if (TIMESTAMP - $sendTime < 1) {
                ErrorModel::throwException(CodeConfigModel::sendLimitError);
            }
        }

    }
    private $messageHistoryDao;
    private $mesageOneDao;
    public function addMessage($fromId, $selfId, $fromName, $fromType, $message, $toId, $toUserId, $toName, $toType, $messageId = false)
    {
        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $mesageOneDao = \DAO\MessageOneModel::getInstance();
        $message['gmtCreate'] = TIMESTAMP;
        $message['isRead'] = ApiConst::unread;
        $message['type'] = (int)$message['type'];
        $message['content'] = base64_encode($message['content']);
        $serializeMessage = serialize($message);
        //将消息添加到表messageHistory
        $mesageHistory['fromId'] = $fromId;
        $mesageHistory['fromType'] = $fromType;
        $mesageHistory['toId'] = $toId;
        $mesageHistory['toType'] = $toType;
        $mesageHistory['title'] = $message['title'];
        $mesageHistory['message'] = $serializeMessage;
        $mesageHistory['type'] = $message['type'];
        $mesageHistory['gmtCreate'] = time();
        $mesageHistory['gmtUpdate'] = time();
        if ($messageId) {
            $mesageHistory['id'] = $messageId;
        }
        $messageHistoryDao->setDb(DbNameConst::masterDBConnectName);
        $messageHistoryDao->db->doTransaction();
        $res1 = $messageHistoryDao->add($mesageHistory);
        //将最后一条消息更新到消息用户表messageOne
        $messageOne['fromId'] = $fromId;
        $messageOne['toUserId'] = $toUserId;
        $messageOne['toUserName'] = $toName;
        $messageOne['toType'] = $toType;
        $messageOne['fromUserId'] = $selfId;
        $messageOne['fromUserName'] = $fromName;
        $messageOne['fromType'] = $fromType;
        $messageOne['toId'] = $toId;
        $messageOne['message'] = $serializeMessage;
        //推送补充
        $mesageHistory['fromUserId'] = $selfId;
        $mesageHistory['fromUserName'] = $fromName;
        $mesageHistory['fromAvatar'] = $this->getAvatar($fromType, $selfId);
        $mesageHistory['toUserId'] = $toUserId;
        $mesageHistory['toUserName'] = $toName;
        //register_shutdown_function(array($messageHistoryDao,'sendMessage'),array($mesageHistory,$toId));
        $mesageOneDao->setDb(DbNameConst::masterDBConnectName);
        $res2 = $mesageOneDao->insertOrUpdate($messageOne);
        $messageHistoryDao->db->doCommit();
        unset($messageHistoryDao->db);
        unset($messageHistoryDao);
        unset($mesageOneDao->db);
        unset($mesageOneDao);

        //$messageHistoryDao->sendMessage($mesageHistory,$toId);
        if ($res1 && $res2) {
            return $res1;
        } else {
            return false;
        }
    }

    public function addMessageCenterToDb()
    {
        $conf = \Yaf\Registry::get('config')->get('redis.database.params');
        $this->baseRedis = new \Redis();
        $this->baseRedis->pconnect($conf['host'], $conf['port']);
        if (!empty($conf['password'])) {
            $this->baseRedis->auth($conf['password']);
        }
        while ($center = $this->baseRedis->lPop('message_center')) {
            $this->baseRedis->rPush('push_center', $center);
            $addData = unserialize($center);
            $addData['message'] = unserialize($addData['message']);
            $this->addMessage($addData['fromId'], $addData['fromUserId'], $addData['fromUserName'], $addData['fromType'], $addData['message'], $addData['toId'], $addData['toUserId'], $addData['toUserName'], $addData['toType'], $addData['id']);
        }
        return true;
    }


    /**
     * 新增用户消息
     *
     * @ccw`
     */
    public function add($fromId, $selfId, $fromName, $fromType, $message, $toId, $toUserId, $toName, $toType)
    {
        $messageHistoryDao = \DAO\MessageHistoryModel::getInstance();
        $mesageOneDao = \DAO\MessageOneModel::getInstance();
        $message['gmtCreate'] = TIMESTAMP;
        $message['isRead'] = ApiConst::unread;
        $message['type'] = (int)$message['type'];
        $message['content'] = base64_encode($message['content']);
        $serializeMessage = serialize($message);
        //将消息添加到表messageHistory
        $mesageHistory['fromId'] = $fromId;
        $mesageHistory['fromType'] = $fromType;
        $mesageHistory['toId'] = $toId;
        $mesageHistory['toType'] = $toType;
        $mesageHistory['title'] = $message['title'];
        $mesageHistory['message'] = $serializeMessage;
        $mesageHistory['type'] = $message['type'];
        $mesageHistory['gmtCreate'] = TIMESTAMP;
        $mesageHistory['gmtUpdate'] = TIMESTAMP;
        $messageHistoryDao->setDb(DbNameConst::masterDBConnectName);
        $messageHistoryDao->db->doTransaction();
        $res1 = $messageHistoryDao->add($mesageHistory);
        //将最后一条消息更新到消息用户表messageOne
        $messageOne['fromId'] = $fromId;
        $messageOne['toUserId'] = $toUserId;
        $messageOne['toUserName'] = $toName;
        $messageOne['toType'] = $toType;
        $messageOne['fromUserId'] = $selfId;
        $messageOne['fromUserName'] = $fromName;
        $messageOne['fromType'] = $fromType;
        $messageOne['toId'] = $toId;
        $messageOne['message'] = $serializeMessage;
        //推送补充
        $mesageHistory['fromUserId'] = $selfId;
        $mesageHistory['fromUserName'] = $fromName;
        $mesageHistory['fromAvatar'] = $this->getAvatar($fromType, $selfId);
        $mesageHistory['toUserId'] = $toUserId;
        $mesageHistory['toUserName'] = $toName;
        //register_shutdown_function(array($messageHistoryDao,'sendMessage'),array($mesageHistory,$toId));
        $mesageOneDao->setDb(DbNameConst::masterDBConnectName);
        $res2 = $mesageOneDao->insertOrUpdate($messageOne);
        $messageHistoryDao->db->doCommit();
        register_shutdown_function(array($messageHistoryDao, "sendMessage"), $mesageHistory, $toId);
        //$messageHistoryDao->sendMessage($mesageHistory,$toId);
        if ($res1 && $res2) {
            $clientPush=\JPush\ClientPush::getInstance();
            $mesageHistory['id']=$res1;
            $addData['message'] = unserialize($mesageHistory['message']);
            $addData['message']['content']=base64_decode($addData['message']['content']);
            $clientPush->push($addData);
            return $res1;
        } else {
            return false;
        }
    }

    public function set($memberId, $pushData)
    {
        $memberDao = \DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        if ($memberDao->setIsWxsend($memberId, $pushData) !== false) {
            return true;
        }
        return false;
    }


}
