<?php

namespace app\common\controller;

use think\facade\Db;
use think\facade\Session;
use think\facade\View;
use think\facade\Cache;
use think\Request;

/**
 * 总公共类
 * Class Common
 * @package app\common\controller
 */
class Common
{
    /**
     * 当前的客服信息
     * @var int
     */
    protected $custs = [];

    /**
     * 当前主客服ID
     * @var int
     */
    protected $main_id = 0;

    /**
     * 当前主客服ID
     * @var int
     */
    protected $main_uname = '';

    /**
     * 全局配置
     * @var int
     */
    protected $get_options = [];

    /**
     * 判断用户登录中间件
     * @var string[]
     */
    protected $middleware = [
        \app\middleware\CheckLoginUser::class
    ];

    public function __construct(Request $r)
    {
        $cust_info   = Session::get('cust_info');
        $this->custs = Db::name('im_customer')->find($cust_info['cuid']);

        if ($this->custs['is_main'] == 0) {
            $this->main_id = $this->custs['pid'];
            $this->main_uname = Db::name('im_customer')
                ->where('id', $this->main_id)->value('uname');
        } else {
            $this->main_id = $this->custs['id'];
            $this->main_uname = $this->custs['uname'];
        }

        $controller    = $r->controller();
        $action        = $r->action();
        $this->get_options = $this->get_options();
        View::assign([
            'web_title'     => '',
            'options'       => $this->get_options,
            'main_id'       => $this->main_id,
            'main_uname'    => $this->main_uname,
            'custs'         => $this->custs,
            'controller'    => $controller,
            'action'        => $action
        ]);
    }

    /**
     * 获取全局配置
     */
    public function get_options()
    {
        $options = Cache::get('options');

        if (empty($options)) {
            $im_options = Db::name('im_options')
                ->where('cuid', 1)
                ->column('option_value', 'option_ename');

            $im_general_config = Db::name('im_general_config')
                ->field('mess_prompt,mess_clues,mess_distr,mess_mp3')
                ->where('cuid', 1)
                ->find();

            $options = array_merge($im_options, $im_general_config);

            Cache::set('options', $options);
        }
        return $options;
    }
}