<?php

namespace app\admin\controller\fastim;

use app\common\controller\Backend;
use addons\fastim\library\Common;

/**
 * 会话管理
 *
 * @icon fa fa-circle-o
 */
class Session extends Backend
{

    /**
     * Session模型对象
     * @var \app\admin\model\fastim\Session
     */
    protected $model = null;

    protected $pageCount = 15;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\fastim\Session;
        $this->view->assign("typeList", $this->model->getTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 聊天记录
     */
    public function record($ids, $page = 1)
    {
        $sessionInfo = Common::sessionInfo($ids);
        if (!$sessionInfo) {
            $this->error(__('No Results were found'));
        }

        // 重新获取带会话用户的会话资料
        $sessionInfo = Common::sessionInfo($ids, $sessionInfo['user_one']);

        if ($page == 1) {
            $min = 0;
        } else {
            $min = ($page - 1) * $this->pageCount;
        }

        if ($sessionInfo['type'] == 'single') {
            // 单聊消息
            $message = Common::loadSingleChatRecord($sessionInfo['id'], [
                'min'       => $min,
                'pageCount' => $this->pageCount
            ], $sessionInfo['user_one']);

            $sessionInfo['windowType'] = 'message';
        } elseif ($sessionInfo['type'] == 'service') {
            if ($sessionInfo['chat_id'] == 1 || $sessionInfo['chat_id'] == 2 || $sessionInfo['chat_id'] == 3) {
                $message = Common::loadServiceRecord($sessionInfo, [
                    'min'       => $min,
                    'pageCount' => $this->pageCount
                ], $sessionInfo['user_one']);

                if ($message) {
                    $sessionInfo['windowType'] = $message['windowType'];
                    $message                   = $message['message'];
                }
            }
        }

        $nextpage = (count($message) < $this->pageCount) ? false : true;
        $message  = Common::groupByTime($message);

        if ($this->request->isAjax()) {
            $this->success('ok', '', [
                'pageData'    => [
                    'nextpage' => $nextpage,
                    'page'     => $page
                ],
                'message'     => $message,
                'sessionInfo' => $sessionInfo
            ]);
        }

        $this->assignconfig('pageData', [
            'nextpage' => $nextpage,
            'page'     => $page,
            '__CDN__'  => $this->request->domain()
        ]);
        $this->assignconfig('message', $message);
        $this->assignconfig('sessionInfo', $sessionInfo);
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model->with([
                'user'    => ['fauser', 'admin'],
                'usertwo' => ['fauser', 'admin']
            ])
                ->where($where)
                ->where('session.type="single" OR session.type="service"')
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname']);
                $aNickname  = $row->user->admin->nickname ?? '';
                $faNickname = $row->user->fauser->nickname ?? '';
                if ($aNickname || $faNickname) {
                    $row->user->nickname = $row->user->nickname . '(' . ($aNickname ? $aNickname : $faNickname) . ')';
                }

                $row->getRelation('usertwo')->visible(['nickname', 'id']);
                if ($row->type == 'single') {
                    $aNickname  = $row->usertwo->admin->nickname ?? '';
                    $faNickname = $row->usertwo->fauser->nickname ?? '';
                    if ($aNickname || $faNickname) {
                        $row->usertwo->nickname = $row->usertwo->nickname . '(' . ($aNickname ? $aNickname : $faNickname) . ')';
                    }
                } elseif ($row->chat_info) {
                    $row->usertwo->id       = $row->chat_info['id'];
                    $row->usertwo->nickname = $row->chat_info['nickname'];
                }
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

}
