<?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';

    public function init()
    {

    }


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

    /**
     * 单例模式获取类实例
     *
     * @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'],

            );
        }


    }

    /**
     * 根据消息类型获得一条消息，已经未读消息数量
     *
     * @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 == 1) {
            $avatar = Common::getStaticFile(ImageConst::sysAvatarName, ImageConst::systemAvatar, ImageConst::imageDomain);
        }
        if ($type == 2) {
            $avatar = Common::getStaticFile(ImageConst::orderAvatarName, ImageConst::systemAvatar);
        }
        if ($type == 3) {
            $avatar = Common::getStaticFile(ImageConst::expressAvatarName, ImageConst::systemAvatar, ImageConst::imageDomain);
        }
        if ($type == 4) {
            $store = \DAO\StoreModel::getInstance();
            $store->setDb($db);
            $avatar = $store->getInfoById($userid, 'store_label', 'store_label');
            $avatar = Common::getStaticFile($avatar, ImageConst::storeLabel, ImageConst::imageDomain);
        }

        if ($type == 5) {
            $member = \DAO\MemberModel::getInstance();
            $memerAvatar = $member->getInfo($userid, 'member_avatar');
            $avatar = $member->getMemberAvatarUrl($userid, $memerAvatar);
        }
        return $avatar;
    }
    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();
        $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['message'] = unserialize($val['message']);
            $val['toAvatar'] = $self['avatar'];
            $val['fromAvatar'] = $toMember['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) {
            $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;
    }

    /**
     * 根据用户的消息类型获得消息列表
     *
     * @ccw
     */
    public function getMemberList($memberId, $selfType, $toId, $toType = ApiConst::systemMessageType, $field = '*', $pageIndex = ApiConst::pageIndex, $pageSize = ApiConst::pageSize)
    {
        $messageHistory = \DAO\MessageHistoryModel::getInstance();
        $self = $this->getUserByMemberIdAndSelfType($memberId, $selfType);
        $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'] = unserialize($val['message']);
            $val['message']['title'] = !empty($val['message']['title']) ? $val['message']['title'] : '';
        }
        $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['status'] == ApiConst::recieveRemove) {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'status', ApiConst::remove);
            } else {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'status', ApiConst::sendRemove);
            }
        }
        if ($memberHistory['toId'] == $memberId) {
            if ($memberHistory['status'] == ApiConst::sendRemove) {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'status', ApiConst::remove);
            } else {
                $isSuccess = $memageHistoryDao->update($messageHistoryId, 'status', ApiConst::recieveRemove);
            }
        }
        return $isSuccess;
    }

    /**
     * 获得消息按钮
     *
     * @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)
    {
        $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);
        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);
            }
        }

    }

    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'];
        $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);

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

    public function addMessageCenterToDb()
    {
        $conf = \Yaf\Registry::get('config')->get('redis.database.params');
        $redis = new \Redis();
        $redis->pconnect($conf['host'], $conf['port']);
        if (!empty($conf['password'])) {
            $redis->auth($conf['password']);
        }
        while ($center = $redis->lPop('message_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'];
        $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) {
            return $res1;
        } else {
            return false;
        }
    }
    public function set($memberId,$type){
        $memberDao=\DAO\MemberModel::getInstance(DbNameConst::masterDBConnectName);
        if($memberDao->setIsWxsend($memberId,$type)!==false){
            return true;
        }
        return false;
    }


}
