<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\love\controller;

use app\love\model\UserFriendModel;
use app\love\model\UserInviteModel;
use app\love\model\UserMessageModel;
use app\love\model\UserModel;

class MessageController extends LoveBaseController
{
    /**
     * 好友列表
     */
    public function index()
    {
        $user_id = cmf_get_current_user_id();
        $list    = UserFriendModel::with('friend')->where('user_id', $user_id)->select();
        foreach ($list as $v) {
            $v['last_msg_time_text'] = date('m-d H:i', $v['last_msg_time']);
        }
        $this->assign('list', $list);

        //未读消息数
        $unread_num = UserFriendModel::where('user_id', $user_id)->sum('unread_num');

        //收到邀请数
        $invite_num = UserInviteModel::where('to_id', $user_id)
            ->where('status', 1)
            ->count();
        $this->assign('unread_num', $unread_num + $invite_num);
        $this->assign('invite_num', $invite_num);

        return $this->fetch();
    }

    /**
     * 聊天页
     */
    public function detail()
    {
        //错误判断
        $id = $this->request->get('id');
        if (empty($id)) {
            $this->error('该用户不存在');
        }
        $my_id = cmf_get_current_user_id();
        if ($id == $my_id) {
            $this->error('不能和自己对话');
        }
        $user = UserModel::get($id);
        if (empty($user)) {
            $this->error('该用户不存在');
        }
        $this->assign('user', $user);
        $this->assign('to_id', $id);
        $this->assign('from_id', $my_id);

        //好友
        $friend = UserFriendModel::get(['user_id' => $my_id, 'friend_id' => $id]);
        if (empty($friend)) {
            $this->error('请等待对方通过聊天邀请');
        } else {
            $friend->unread_num = 0;
            $friend->save();
        }

        //获取消息
        $message = UserMessageModel::with('toUser,fromUser')
            ->where(function ($query) use ($id, $my_id) {
                $query->where(function ($query) use ($id, $my_id) {
                    $query->where([
                        ['from_id', '=', $id],
                        ['to_id', '=', $my_id],
                    ]);
                })->whereOr(
                    function ($query) use ($id, $my_id) {
                        $query->where([
                            ['from_id', '=', $my_id],
                            ['to_id', '=', $id],
                        ]);
                    });
            })->order('create_time desc')->limit(10)->select();
        $this->assign('last_message_time', $message->isEmpty() ? 0 : $message[0]['create_time']);
        foreach ($message as $v) {
            $v['create_time_text'] = date('m-d H:i', $v['create_time']);
        }
        $message = $message->reverse();
        $this->assign('first_message_time', $message->isEmpty() ? time() : $message[0]['create_time']);
        $this->assign('message', $message);

        //更多
        $count = UserMessageModel::with('toUser,fromUser')
            ->where([
                ['from_id', '=', $id],
                ['to_id', '=', $my_id],
            ])->whereOr([
                ['from_id', '=', $my_id],
                ['to_id', '=', $id],
            ])->count();
        $this->assign('has_more', $count > 10 ? 'true' : 'false');

        return $this->fetch();
    }

    /**
     * 发送消息
     */
    public function sendMessage()
    {
        $data    = $this->request->post();
        $user_id = cmf_get_current_user_id();
        $time    = time();

        //增加聊天记录
        UserMessageModel::create([
            'from_id'     => $user_id,
            'to_id'       => $data['to_id'],
            'message'     => $data['message'],
            'create_time' => $time,
        ]);

        //增加最后聊天消息
        UserFriendModel::update(['last_msg' => '我：' . $data['message'], 'last_msg_time' => $time], ['user_id' => $user_id, 'friend_id' => $data['to_id']]);
        $friend                = UserFriendModel::get(['user_id' => $data['to_id'], 'friend_id' => $user_id]);
        $friend->last_msg      = '对方：' . $data['message'];
        $friend->last_msg_time = $time;
        $friend->unread_num++;
        $friend->save();

        //获取消息
        $message = UserMessageModel::with('toUser,fromUser')
            ->where(function ($query) use ($user_id, $data) {
                $query->where(function ($query) use ($user_id, $data) {
                    $query->where([
                        ['from_id', '=', $user_id],
                        ['to_id', '=', $data['to_id']],
                    ]);
                })->whereOr(
                    function ($query) use ($user_id, $data) {
                        $query->where([
                            ['from_id', '=', $data['to_id']],
                            ['to_id', '=', $user_id],
                        ]);
                    });
            })->where(
                function ($query) use ($data) {
                    $query->where('create_time', '>', $data['message_time']);
                })
            ->order('create_time asc')->select();

        $this->result($message, 1);
    }

    /**
     * 获取消息
     */
    public function getMessage()
    {
        $data    = $this->request->post();
        $user_id = cmf_get_current_user_id();

        //获取消息
        $message = UserMessageModel::with('toUser,fromUser')
            ->where(function ($query) use ($user_id, $data) {
                $query->where(function ($query) use ($user_id, $data) {
                    $query->where([
                        ['from_id', '=', $user_id],
                        ['to_id', '=', $data['to_id']],
                    ]);
                })->whereOr(
                    function ($query) use ($user_id, $data) {
                        $query->where([
                            ['from_id', '=', $data['to_id']],
                            ['to_id', '=', $user_id],
                        ]);
                    });
            })->where(
                function ($query) use ($data) {
                    $query->where('create_time', '>', $data['message_time']);
                })
            ->order('create_time asc')->select();

        $this->result($message, 1);
    }

    /**
     * 更多记录
     */
    public function moreMessage()
    {
        $data    = $this->request->post();
        $user_id = cmf_get_current_user_id();

        //获取消息
        $list = UserMessageModel::with('toUser,fromUser')
            ->where(function ($query) use ($user_id, $data) {
                $query->where(function ($query) use ($user_id, $data) {
                    $query->where([
                        ['from_id', '=', $user_id],
                        ['to_id', '=', $data['to_id']],
                    ]);
                })->whereOr(
                    function ($query) use ($user_id, $data) {
                        $query->where([
                            ['from_id', '=', $data['to_id']],
                            ['to_id', '=', $user_id],
                        ]);
                    });
            })->where(
                function ($query) use ($data) {
                    $query->where('create_time', '<', $data['message_time']);
                })
            ->order('create_time desc')->limit(10)->select();
        foreach ($list as $v) {
            $v['create_time_text'] = date('m-d H:i', $v['create_time']);
        }
        $list = $list->reverse();

        $this->result($list, 1);
    }

    /**
     * 邀请
     */
    public function invite()
    {
        $list = UserInviteModel::with('from_user')
            ->where('to_id', '=', cmf_get_current_user_id())
            ->limit(10)
            ->order('status asc,create_time desc')
            ->select();
        foreach ($list as $v) {
            $v['user']        = $v['from_user'];
            $v['user']['age'] = empty($v['user']['birthday']) ? 0 : date('Y') - date('Y', $v['user']['birthday']);
            $v['create_time'] = date('m-d H:i', $v['create_time']);
        }
        $this->assign('list1', $list);

        $list = UserInviteModel::with('to_user')
            ->where('from_id', '=', cmf_get_current_user_id())
            ->limit(10)
            ->order('status asc,create_time desc')
            ->select();
        foreach ($list as $v) {
            $v['user']        = $v['to_user'];
            $v['user']['age'] = empty($v['user']['birthday']) ? 0 : date('Y') - date('Y', $v['user']['birthday']);
            $v['create_time'] = date('m-d H:i', $v['create_time']);
        }
        $this->assign('list2', $list);

        return $this->fetch();
    }

    /**
     * 邀请列表
     */
    public function inviteList()
    {
        $param   = $this->request->post();
        $user_id = cmf_get_current_user_id();
        $where   = [];
        $with    = 'from_user';
        if ($param['status'] == 0) {
            $where[] = ['to_id', '=', $user_id];
        } elseif ($param['status'] == 1) {
            $where[] = ['from_id', '=', $user_id];
            $with    = 'to_user';
        }

        $list = UserInviteModel::with($with)
            ->where($where)
            ->page($param['page'])
            ->limit(10)
            ->order('status asc,create_time desc')
            ->select();
        foreach ($list as $v) {
            if ($param['status'] == 0) {
                $v['user'] = $v['from_user'];
            } elseif ($param['status'] == 1) {
                $v['user'] = $v['to_user'];
            }
            $v['user']['age'] = empty($v['user']['birthday']) ? 0 : date('Y') - date('Y', $v['user']['birthday']);
            $v['create_time'] = date('m-d H:i', $v['create_time']);
        }

        $this->result($list, 1);
    }

    /**
     * 处理邀请
     */
    public function dealInvite()
    {
        $post    = $this->request->post();
        $user_id = cmf_get_current_user_id();
        $info    = UserInviteModel::get(['from_id' => $post['id'], 'to_id' => $user_id]);
        if (empty($info)) {
            $this->error('请刷新页面');
        }

        //更改状态
        $info->status = $post['status'];
        $info->save();

        //增加好友
        if ($post['status'] == 2) {
            UserFriendModel::create([
                'user_id'       => $post['id'],
                'friend_id'     => $user_id,
                'last_msg_time' => time(),
            ]);
            UserFriendModel::create([
                'user_id'       => $user_id,
                'friend_id'     => $post['id'],
                'last_msg_time' => time(),
            ]);
            $this->error('', url('detail') . '?id=' . $post['id']);
        } else {
            $this->success('');
        }
    }
}
