<?php

namespace app\chat\controller;

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

/**
 * 游客聊天
 * Class Say
 * @package app\index\controller
 */
class Say
{
    /**
     * 全局配置
     * @var int
     */
    protected $get_options = [];

    public function __construct(Request $r)
    {
        $this->get_options = $this->get_options();
        View::assign([
            'options' => $this->get_options
        ]);
    }

    /**
     * 进行加密跳转
     */
    public function redchat(Request $r)
    {
        try {
            $gets = $r->get();
            // 这个如果成立表示是专属链接
            if (!empty($gets['cuid']) && !empty($gets['wname'])
                && !empty($gets['uname'])) {
                $param = $gets;
            } else {
                $param = Db::name('im_customer')
                    ->field('id cuid,group_id gid,web_id wname,uname')
                    ->where('group_id', $gets['gid'])
                    ->orderRaw("rand()")->find();
            }

            $url = 'chat/say/chat';
            if (!empty($gets['du'])) {
                if ($gets['du'] == 2) {
                    $url = 'chat/say/mchat';
                } elseif ($gets['du'] == 3) {
                    $url = 'chat/say/minichat';
                } else {
                    $url = 'chat/say/chat';
                }
            }
            $code = encodeing(http_build_query($param));

            return redirect(Furl($url, [
                'code' => $code
            ], true, true));
        } catch (\Exception $e) {
            abort(404, '页面异常');
        }
    }

    /**
     * 电脑端聊天界面
     */
    public function chat(Request $r)
    {
        try {
            preg_match_all("/chat\/tour\/(.*?).html/", $r->url(), $match);
            parse_str(decodeing($match[1][0]), $param);
            $ischat = Db::name('im_customer')->where([
                'id' => $param['cuid'],
                'uname' => $param['uname']
            ])->count();
            if (!empty($ischat)) {

                if ($r->isMobile()) {

                    $code = encodeing(http_build_query([
                        'cuid' => $param['cuid'],
                        'wname' => $param['wname'],
                        'uname' => $param['uname'],
                        'gid' => $param['gid'],
                    ]));

                    return redirect(Furl("chat/say/mchat", [
                        'code' => $code
                    ], true, true));
                }
            }
        } catch (\Exception $e) {
            abort(404, '页面异常');
        }

        $param['ip'] = $r->ip();

        $this->baseCommon($param);

        return View::fetch();
    }

    /**
     * 迷你聊天界面
     */
    public function minichat(Request $r)
    {
        try {
            preg_match_all("/chat\/minitour\/(.*?).html/", $r->url(), $match);
            parse_str(decodeing($match[1][0]), $param);
            // 这个如果成立表示是专属链接
            if (!empty($param['cuid']) && !empty($param['wname'])
                && !empty($param['uname'])) {

            }
        } catch (\Exception $e) {
            abort(404, '页面异常');
        }

        $param['ip'] = $r->ip();
        $this->baseCommon($param);
        return View::fetch();
    }

    /**
     * 手机端聊天界面
     */
    public function mchat(Request $r)
    {
        try {
            preg_match_all("/chat\/mtour\/(.*?).html/", $r->url(), $match);
            parse_str(decodeing($match[1][0]), $param);
            $ischat = Db::name('im_customer')->where([
                'id' => $param['cuid'],
                'uname' => $param['uname']
            ])->count();
            if (!empty($ischat)) {
                if (!$r->isMobile()) {
                    $code = encodeing(http_build_query([
                        'cuid' => $param['cuid'],
                        'wname' => $param['wname'],
                        'uname' => $param['uname'],
                        'gid' => $param['gid'],
                    ]));
                    return redirect(Furl("chat/say/chat", [
                        'code' => $code
                    ], true, true));
                }
            }
        } catch (\Exception $e) {
            abort(404, '页面异常');
        }

        $param['ip'] = $r->ip();
        $this->baseCommon($param);
        return View::fetch();
    }

    /**
     * 公共部分
     */
    public function baseCommon($param)
    {
        $toid = $param['cuid'];
        $group = $param['gid'];
        $to_nick = Db::name('im_customer')->where([
            'id' => $param['cuid'],
            'web_id' => $param['wname'],
            'uname' => $param['uname']
        ])->value('nick');
        $ip = $param['ip']; // 当前客户端ip 生产环境下使用
//        $ip = date('Y-m-d H:i', time()); // 测试环境下使用
        $visitors = Db::name('im_visitors')->where('ip', $ip)->find();
        if (empty($visitors)) {
            // 添加访客
            $from_avatar = '/images/avatar/visi/' . rand(1, 200) . '.jpg';
            $from_nick = '游客' . random_user(8);
            $data = [
                'avatar' => $from_avatar,
                'ip' => $ip,
                'state' => 1,
                'nick' => $from_nick,
                'last_time' => time()
            ];
            $fromid = Db::name('im_visitors')->insertGetId($data);
            // 添加访客信息
            $info = [
                'vsid' => $fromid,
                'cuid' => $toid,
                'source' => get_source(),
                'equi' => get_equipment()
            ];
            $visitors_info = Db::name('im_visitors_info')
                ->where($info)->count();
            if (!$visitors_info) {
                Db::name('im_visitors_info')->insertGetId($info);
            }
            // 更新咨询会员总数
            Db::name('im_site_data')->where('id', 1)
                ->inc('im_stat_zxhy', 1)->update();
        } else {
            $fromid = $visitors['id'];
            $from_nick = $visitors['nick'];
            $from_avatar = $visitors['avatar'];
        }
        $to_avatar = Db::name('im_customer')
            ->where('id', $toid)->value('avatar');
        // 获取主客服ID
        $main_id = Db::name('im_customer')->where('uname', $param['wname'])->value('id');
        $this->getComask($main_id);

        //获取会员消费插件信息
        $user_addons = goalong_hook('user_config',[],1);
        if (!$user_addons) $user_addons = false;

        View::assign([
            'fromid' => $fromid,
            'from_nick' => $from_nick,
            'from_avatar' => $from_avatar,
            'group' => $group,
            'toid' => $toid,
            'to_nick' => $to_nick,
            'to_avatar' => $to_avatar,
            'user' => $user_addons,
        ]);
    }

    /**
     * 显示常见问题
     */
    public function getComask($main_id = 0)
    {
        $comask_lists = Db::name('im_comask')->where([
            'cuid' => $main_id,
            'isshow' => 1
        ])->order('sort desc')->column('ask', 'id');
        View::assign('comask_lists', $comask_lists);
    }

    /**
     * 评价页面
     */
    public function evaluation(Request $r)
    {
        if ($r->isAjax() && $r->post()) {
            $cuid = $r->post('cuid', 0, 'intval');
            // 获取主客服ID
            $customer = Db::name('im_customer')
                ->field('id,pid,is_main')->find($cuid);
            if ($customer['is_main'] == 1) {
                $main_id = $customer['id'];
            } else {
                $main_id = $customer['pid'];
            }
            $temps = Db::name('im_evaluation_temp')->where('cuid', $main_id)->find();
            if (!empty($temps)) {
                $temp = '';
                $temp .= '<div class="dialog-body"><div style="margin-bottom: 20px;">' . $temps['evins'] . '</div>';
                $evlimit = explode(',', $temps['evlimit']);
                foreach ($evlimit as $item) {
                    $temp .= '<div class="evaluate-item evaluate-score" data-score="0">
                        <span class="evaluate-title">' . $item . '</span>
                        <input type="hidden" name="' . $item . '">
                        <img class="star" data-id="1" src="/images/star/star-2.png">
                        <img class="star" data-id="2" src="/images/star/star-2.png">
                        <img class="star" data-id="3" src="/images/star/star-2.png">
                        <img class="star" data-id="4" src="/images/star/star-2.png">
                        <img class="star" data-id="5" src="/images/star/star-2.png">
                      </div>';
                }
                if ($temps['wzev_open'] == 1) {
                    $temp .= '<div class="evaluate-item" style="height: 80px;line-height: 1;margin-top: 10px;align-items: flex-start">
                        <span style="display: inline-block;margin-right: 12px;white-space: nowrap">' . $temps['wzev_name'] . '</span>
                        <textarea class="about-text" cols="30" rows="4"></textarea>
                    </div>';
                }
                $temp .= '</div>';
                return json(['code' => 200, 'data' => $temp]);
            }
        }
    }

    /**
     * 评价提交
     */
    public function addevaluation(Request $r)
    {
        if ($r->isAjax() && $r->post()) {
            $ykid = $r->post('ykid', 0, 'intval');
            $kfid = $r->post('kfid', 0, 'intval');
            $stext = $r->post('stext', '', 'strip_tags');
            $data = $r->post('data', []);
            if (strlen($stext) > 150) {
                return json(['code' => 300, 'data' => '评价内容太长了']);
            }
            $cust = Db::name('im_customer')
                ->alias('c')
                ->field('c.nick,g.name,c.id,c.pid,c.is_main')
                ->where('c.id', $kfid)
                ->join('we_im_customer_group g', 'g.id=c.group_id')
                ->find();
            $vs_nick = Db::name('im_visitors')->where('id', $ykid)->value('nick');
            $pjqk = "";
            if (!empty($data)) {
                foreach ($data as $item) {
                    $pjqk .= "{$item['sname']}|{$item['score']},";
                }
                $pjqk = rtrim($pjqk, ',');
            }
            // 获取主客服ID
            if ($cust['is_main'] == 1) {
                $main_id = $cust['id'];
            } else {
                $main_id = $cust['pid'];
            }
            $post = [
                'vsid' => $ykid,
                'main_id' => $main_id,
                'vs_nick' => $vs_nick,
                'groups' => $cust['name'],
                'cunick' => $cust['nick'],
                'add_time' => time(),
                'pjqk' => $pjqk,
                'wzpj' => $stext,
            ];
            Db::name('im_evaluation')->insert($post);
            return json(['code' => 200, 'data' => '感谢评价']);
        }
    }

    /**
     * 获取全局配置
     */
    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)
                ->column('*');
            $options = array_merge($im_options, $im_general_config);
            Cache::set('options', $options);
        }
        return $options;
    }
}

