<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\controllers;

use Yii;
use home\models\Message;
use home\models\MessageLink;
use yii\console\Request;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;
use common\models\User;

/**
 * 个人的收件箱/发件箱  信息类型：（人<-->人）或（人-->人）
 * 
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class MessageController extends Controller
{
    public function actions()
    {
		return [];
	}

    /**
     * 当前用户的收件箱,包含了接收的短消息和接收的的通知公告
     */
    public function actionInbox()
    {
        $messageQuery = Message::find();

        $request = Yii::$app->request;
		$keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $beginTime = $request->get('begin_time');
		$endTime = $request->get('end_time');

        //$messageQuery->where(['status'=> Message::STATUS_ENABLE]);
        if(!empty($beginTime)) {
			$beginTime = strtotime($beginTime);
			$messageQuery->where('create_time >= :beginTime', [':beginTime' => $beginTime]);
		}
		if(!empty($endTime)) {
			$endTime = strtotime($endTime) + 86399;
			$messageQuery->andWhere('create_time <= :endTime', [':endTime' => $endTime]);
		}
		if (!empty($keywords) && !empty($field)) {
            if ($field == 'realname') {    //当查询的关键字是发件人
                $userIds = User::find()->select('user_id')->where(['like', $field, $keywords])->asArray()->all();
                //把以user_id为键名的数组重组，取user_id的键值重新组成一个新的一维数组
                $userIdsArray = arrayHelper::getColumn($userIds,'user_id');
            } else if ($field == 'title') {   //当查询的关键字是标题
                $messageQuery->andwhere(['like', $field, $keywords]);
            }
		}

        //按照上面条件，查询出最终结果，不包含关键字是发件人的
        $messageIds = $messageQuery->select('message_id')->asArray()->all();
        //把以message_id为键名的数组重组，取message_id的键值重新组成一个新的一维数组
        $messageIdsArray = arrayHelper::getColumn($messageIds,'message_id');

        $query = MessageLink::find()
                    ->where(['to_user_id' => Yii::$app->user->identity->user_id, 'status'=> Message::STATUS_DISABLE ])
                    ->orderBy(['is_read' => SORT_ASC, 'link_id' => SORT_DESC]);
        if (isset($userIdsArray)) {
            $query->andWhere(['in', 'from_user_id', $userIdsArray]);
        }
        if (isset($messageIdsArray)) {
            $query->andWhere(['in', 'message_id', $messageIdsArray]);
        }
		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 20,
			],
		]);
        return $this->render('inbox', [
			'get' => $request->get(),
			'model' => new MessageLink,
			'models' => $provider->models,
			'pages' => $provider->pagination,
		]);
    }

    /**
     * 当前用户的发件箱,包括 回复的信息，发送的通知公告，短消息
     */
    public function actionOutbox()
    {
        $model = new Message;
		$query = Message::find();
        $query->select('message_id, title, create_time, type, is_reply');
        $query->orderBy(['message_id' => SORT_DESC]);
        $query->where(['user_id' => Yii::$app->user->identity->user_id, 'status'=> Message::STATUS_ENABLE]);
        
		$request = Yii::$app->request;
		$keywords = trim($request->get('keywords'));
        $field = $request->get('search_field');
        $beginTime = $request->get('begin_time');
		$endTime = $request->get('end_time');
        
        if(!empty($beginTime)) {
			$beginTime = strtotime($beginTime);
			$query->andWhere('create_time >= :beginTime', [':beginTime' => $beginTime]);
		}
		if(!empty($endTime)) {
			$endTime = strtotime($endTime) + 86399;
			$query->andWhere('create_time <= :endTime', [':endTime' => $endTime]);
		}
		if (!empty($keywords) && !empty($field)) {
			$query->andwhere(['like', $field, $keywords]);
		}
        
		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 20,
			],
		]);
        return $this->render('outbox', [
			'get' => $request->get(),
			'model' => $model,
			'models' => $provider->models,
			'pages' => $provider->pagination,
		]);
    }

    /**
     * 查看信息所有的接收人员
     */
    public function actionSendLists()
    {
        $model = new Message;
		$id = (int) Yii::$app->request->get('id');
        //查找出当前信息的标题和内容
        $model = Message::find()->select('title, content')->where(['message_id' => $id])->one();
        
        $query = MessageLink::find()
                ->where(['message_id' => $id])
                ->with('toName')
                ->orderBy(['is_read' => SORT_ASC, 'link_id' => SORT_DESC]);
		$provider = new ActiveDataProvider([
			'query' => $query,
			'pagination' => [
				'pageSize' => 20,
			],
		]);
        return $this->render('send-lists',
            [
                'model' => $model,
                'models' => $provider->models,
                'pages' => $provider->pagination,
            ]);
    }

    /**
     * 发送短消息
     * @return type
     */
    public function actionShortMessage()
    {
        $this->layout = 'modal';
        $model = new Message;
        $request = Yii::$app->request;
        if ($request->isPost) {
            $model->load($request->post());
            $recipients = Message::getArray($model->get_user_ids);
            if (Message::send($model->title, $model->content, $recipients, 'insert', $model->is_reply, 1)) {
                Yii::$app->getSession()->setFlash('success', '发送成功');
            } else {
                $firstError = reset($model->getFirstErrors());
                Yii::$app->getSession()->setFlash('error', $firstError);
            }
        }
        return $this->render('short-message',
            [
                'model' => $model,
                'action' => ['/message/short-message'],
            ]);
    }

    /**
     * 发送通知公告
     * @return type
     */
    public function actionNotice()
    {
        $this->layout = 'modal';
        $model = new Message;
        $request = Yii::$app->request;
        if ($request->isPost) {
            $model->load($request->post());
            $recipients = Message::getArray($model->get_user_ids);
            if (Message::send($model->title, $model->content, $recipients, 'insert', 0, 2)) {
                Yii::$app->getSession()->setFlash('success', '发送成功');
            } else {
                $firstError = reset($model->getFirstErrors());
                Yii::$app->getSession()->setFlash('error', $firstError);
            }
        }
        return $this->render('notice',
            [
                'model' => $model,
                'action' => ['/message/notice'],
            ]);
    }

    /**
     * 查看收到的信息内容并进行回复
     */
    public function actionLookReply()
    {
        $this->layout = 'modal';
        $model = new Message;
        $request = Yii::$app->request;

        $id = $request->getQueryParam('id', $request->post('id') );
        $model = Message::findOne($id);
        $model->replycontent = $model->content;
        $model->content = '';
        $model->get_user_ids = $model->user_id;
        $model->send_sers = MessageLink::findReceivers($id);
        $model->title = 'RE:'.$model->title;
        $model->is_reply = 1;

        if ($request->isPost) {
            $model->load($request->post());
            $recipients = Message::getArray($model->get_user_ids);
            if (Message::send($model->title, $model->content, $recipients, 'reply', $model->is_reply)) {
                Yii::$app->getSession()->setFlash('success', '回复成功');
            } else {
                $firstError = reset($model->getFirstErrors());
                Yii::$app->getSession()->setFlash('error', $firstError);
            }
        } else {
            $link_id = $request->get('link_id');
            //查看消息的同时更新当前这条的阅读时间和阅读状态
            MessageLink::UpdateRead($link_id);
        }

        return $this->render('look-reply', [
            'model' => $model,
            'action' => ['/message/look-reply'],
        ]);
    }

    /**
     * 查看通知公告或者不需要回复的短消息
     */
    public function actionOnlySee()
    {
        $this->layout = 'modal';
        $model = new Message;
        MessageLink::UpdateRead(Yii::$app->request->get('link_id'));
        $id = Yii::$app->request->get('id');
        $model = Message::findOne($id);
        $model->send_sers = MessageLink::findReceivers($id);
        return $this->render('only-see', [
            'model' => $model,
        ]);
    }

    /**
     * 发件箱删除数据，逻辑删除
     */
    public function actionOutboxDelete()
    {
        $model = new Message;

        $id = Yii::$app->request->get('id');
        $ids = Yii::$app->request->post('delete');
        $session = Yii::$app->getSession();

        if (empty($id) && empty($ids)) {
            $session->setFlash('error', '要删除的对象不存在');
        } else {
            !empty($id) && $ids[] = $id;
            $success = true;
            $canDelete = true;
            foreach ($ids as $id) {
                $model = Message::findOne(['message_id' => $id, 'user_id' => Yii::$app->user->identity->user_id ]);

                if (empty($model)) {
                    $session->setFlash('error', 'ID为' . $id . '的对象不存在');
                    $success = false;
                    break;
                }
                $model->status = 99;
                $model->scenario = 'save';
                if ( !$model->save() ) {
                    $session->setFlash('error', 'ID为' . $id . '的对象删除失败');
                    $success = false;
                    break;
                }
            }
            if ($canDelete && $success) {
                $session->setFlash('success', '删除成功');
            }
        }
        return $this->redirect(['outbox']);
    }

    /**
     * 收件箱删除数据，逻辑删除
     */
    public function actionInboxDelete()
    {
        $model = new MessageLink;

        $id = Yii::$app->request->get('id');
        $ids = Yii::$app->request->post('delete');
        $session = Yii::$app->getSession();

        if (empty($id) && empty($ids)) {
            $session->setFlash('error', '要删除的对象不存在');
        } else {
            !empty($id) && $ids[] = $id;
            $success = true;
            $canDelete = true;
            foreach ($ids as $id) {
                $model = MessageLink::findOne(['message_id' => $id, 'to_user_id' => Yii::$app->user->identity->user_id ]);

                if (empty($model)) {
                    $session->setFlash('error', 'ID为' . $id . '的对象不存在');
                    $success = false;
                    break;
                }
                $model->status = 99;
                if ( !$model->save() ) {
                    $session->setFlash('error', 'ID为' . $id . '的对象删除失败');
                    $success = false;
                    break;
                }
            }
            if ($canDelete && $success) {
                $session->setFlash('success', '删除成功');
            }
        }
        return $this->redirect(['inbox']);
    }

}
