<?php

namespace app\api\controller;

use app\common\controller\Common;
use think\facade\Db;
use think\Request;

/**
 * 对话平台 api类
 * Class Chats
 * @package app\api\controller
 */
class Chats extends Common
{
    /**
     * 获取当前客服的对话游客列表
     */
    public function getchats(Request $r)
    {
        if ($r->isAjax()) {
            $dialogue = Db::name('im_dialogue')->alias('d')
                ->field('d.vsid,d.new_cont,v.avatar,v.nick,d.unread_count,v.state')
                ->join('we_im_visitors v','v.id=d.vsid')
                ->where(['d.cuid' => $this->custs['id'], 'd.isshow' => 1])
                ->limit(30)->order('d.add_time desc')->select();
            return json(['code' => 200, 'data' => $dialogue]);
        }
    }

    /**
     *获取当前客服的黑名单
     */
    public function getBlacklist(Request $r)
    {
        if ($r->isAjax()) {
            $dialogue = Db::name('im_blacklist')->alias('b')
                ->field('b.id,b.vsid,v.avatar,v.nick')
                ->join('we_im_visitors v','v.id=b.vsid')
                ->where('b.cuid', $this->custs['id'])
                ->limit(30)->order('b.add_time desc')->select();
            return json(['code' => 200, 'data' => $dialogue]);
        }
    }

    /**
     * 获取快捷回复分组列表
     */
    public function getGroupList(Request $r)
    {
        if ($r->isAjax()) {
            $fastreply_group = Db::name('im_fastreply_group')
                ->where('cuid', $this->custs['id'])
                ->order('add_time desc')->select();
            return json(['code' => 200, 'data' => $fastreply_group]);
        }
    }

    /**
     * 根据分组id获取回复列表
     */
    public function getReplyList(Request $r)
    {
        if ($r->isAjax()) {
            $group_id = $r->post('group_id', 0, 'imDataFilter');
            $fastreply = Db::name('im_fastreply')
                ->field('id,title,content')
                ->where(['group_id' => $group_id, 'cuid' => $this->custs['id']])
                ->order('add_time desc')->select();
            return json(['code' => 200, 'data' => $fastreply]);
        }
    }

    /**
     * 删除分组以及分组下所有回复
     */
    public function delGroup(Request $r)
    {
        if ($r->isAjax()) {
            $group_id = $r->post('group_id', 0, 'imDataFilter');
            $where = ['group_id' => $group_id, 'cuid' => $this->custs['id']];

            $fastreply = Db::name('im_fastreply')->where($where)->count();
            if ($fastreply) {
                Db::name('im_fastreply')->where($where)->delete();
            }

            Db::name('im_fastreply_group')->delete($group_id);
            return json(['code' => 200, 'data' => []]);
        }
    }

    /**
     * 删除快捷回复
     */
    public function delReply(Request $r)
    {
        if ($r->isAjax()) {
            $reply_id = $r->post('reply_id', 0, 'imDataFilter');
            $where = ['id' => $reply_id, 'cuid' => $this->custs['id']];
            Db::name('im_fastreply')->where($where)->delete();
            return json(['code' => 200, 'data' => []]);
        }
    }

    /**
     * 游客端 加载历史消息
     */
    public function loadRecordLists(Request $r)
    {
        if ($r->isAjax()) {
            $post = $r->post();
            $record = Db::name('im_record')
                ->where("send = {$post['fromid']} AND receive = {$post['toid']}")
                ->whereOr("send = {$post['toid']} AND receive = {$post['fromid']}")
                ->page($post['page'],10)->order('send_time desc')->select();
            $data = array_reverse($record->toArray());
            if (!empty($data)) {
                return json([
                    'code' => 200,
                    'data' => $data
                ]);
            } else {
                return json([
                    'code' => 300,
                    'data' => []
                ]);
            }
        }
    }

    /**
     * 获取当前客户端ip及地址
     */
    public function getIpinfo(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $vsid = $r->post('vsid', false);
            $ip = Db::name('im_visitors')
                ->where('id', $vsid)->value('ip');
            if (!$ip) {
                $ip = $r->ip();
            }
            $info = Db::name('im_visitors_info')
                ->field('id,city')->where('vsid', $vsid)->find();
            if (empty($info['city'])) {
                $city = "";
                $data = curl_get('https://www.ip138.com/iplookup.asp', $get_data = [
                    'ip'     => $ip,
                    'action' => 2
                ]);
                preg_match_all("/\{\"ASN归属地\":\"(.*?)\",/", gbk2utf8($data), $match);
                if (!empty($match[1][0])) {
                    $city = $match[1][0];
                }
                Db::name('im_visitors_info')->save(['id' => $info['id'], 'city' => $city]);
            } else {
                $city = $info['city'];
            }
            if (!empty($city)) {
                return json([
                    'code' => 200,
                    'data' => $city
                ]);
            }
        }
    }

    /**
     * 获取游客全部信息
     */
    public function getVisitors(Request $r)
    {
        if ($r->isAjax() && $r->isAjax()) {
            $vsid = $r->post('vsid', 0, 'intval');
            $visitors = Db::name('im_visitors')
                ->field('vi.id,v.ip,v.avatar,v.nick,vi.source,vi.city,v.state,v.last_time,vi.views,vi.equi,vi.name,vi.phone,vi.note')
                ->alias('v')->join('we_im_visitors_info vi','vi.vsid=v.id')
                ->where(['v.id' => $vsid, 'cuid' => $this->main_id])->find();
            if (!empty($visitors)) {
                $visitors['last_time'] = date('Y年m月d日 H:i', $visitors['last_time']);
                $visitors['views'] = $visitors['views'] . '次';
                if ($visitors['state'] == 1) {
                    $visitors['state'] = '在线';
                } else {
                    $visitors['state'] = '离线';
                }
                return json([
                    'code' => 200,
                    'data' => $visitors
                ]);
            } else {
                return json([
                    'code' => 300,
                    'data' => []
                ]);
            }
        }
    }

    /**
     * 查看和某个游客的历史记录
     */
    public function getOneHistoryLists(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $data   = $r->post();
            $fromid = $data['cuid']??0;
            $toid   = $data['vsid']??0;
            $type   = $data['type']??'7day';

            $record = Db::name('im_record')
                ->field('send,send_avatar,receive,receive_avatar,utype,content')
                ->whereMonth('send_time')
                ->where("send = {$fromid} AND receive = {$toid} OR send = {$toid} OR receive = {$fromid}")
                ->order('send_time desc')
                ->select();

            if (!$record->isEmpty()) {
                $record = array_reverse($record->toArray());
                return json(['code' => 200, 'data' => $record]);
            } else {
                return json(['code' => 300, 'msg' => '无数据']);
            }
        }
    }

    /**
     * 获取当前主客服下的全部客服
     */
    public function getCustomerLists(Request $r)
    {
        if ($r->isAjax() && $r->isPost()) {
            $customer = Db::name('im_customer')
                ->field('id,avatar,nick,state')
                ->where("pid=".$this->main_id." or id=".$this->main_id)
                ->order('login_time desc')->select();
            if (!$customer->isEmpty()) {
                $customer = $customer->toArray();
                foreach ($customer as $key=>$item) {
                    if ($item['id'] == $this->custs['id']) {
                        unset($customer[$key]);
                    }
                }
                return json(['code' => 200, 'data' => $customer]);
            } else {
                return json(['code' => 300, 'msg' => '无数据']);
            }
        }
    }
}
