<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\api\controller\chat;

use app\api\controller\Base;
use think\Db;
use app\common\model\bbfxshop\User;


class Chat extends Base
{
    protected $noNeedLogin = ['ceshi'];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Chat;
    }

    public function ceshi(){
        print_r($_SERVER['SERVER_ADDR']);die;
    }

    // 好友申请
    public function addFriend(){
        $friend_user_id = $this->param("friend_user_id/d");
        $friend_user = User::getInfo($friend_user_id);
        if(empty($friend_user)){
            __error("未查询到好友信息");
        }
        $chat_friend = Db::name("bbfx_chat_friend")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id'],'friend_user_id'=>$friend_user_id])->find();
        if(!empty($chat_friend)){
            if($chat_friend['status'] == 0){
                // __error("已向朋友申请添加");
            }
            if($chat_friend['status'] == 1 && $chat_friend['user_del'] == 0){
                __error("已经申请添加成功");
            }
            Db::name("bbfx_chat_friend")->where(['id'=>$chat_friend['id']])->update(['status'=>0,'user_del'=>0,'friend_user_del'=>0,'updatetime'=>time()]);
        }
        else{
            $data = [
                'uniacid'=>UNIACID,
                'user_id'=>$this->user['id'],
                'friend_user_id'=>$friend_user['id'],
                'status'=>0,
                'updatetime'=>time(),
                'createtime'=>time()
            ];
            Db::name("bbfx_chat_friend")->insert($data);
        }

        __success("发起朋友申请添加成功");
    }

    // 查询用户
    public function queryUser(){
        $mobile = $this->param("mobile/s");
        if(empty($mobile)){
            __error("请输入手机号或ID搜索");
        }

        $where = ['uniacid'=>UNIACID];
        if(mb_strlen($mobile) == 11){
            $where['mobile'] = $mobile;
        }
        else{
             $where['id'] = intval($mobile);
        }

        $user = Db::name("bbfx_user")->where($where)->field("id,nickname,avatar")->find();
        if(empty($user)){
            __error("用户不存在");
        }
        $user['avatar'] = cdnurl($user['avatar']);
        __success("操作成功",['user'=>$user]);
    }

    // 朋友申请列表
    public function getFriendApplyList(){
        $user_list = Db::name("bbfx_chat_friend")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where(['b.uniacid'=>UNIACID,'b.status'=>1,'a.status'=>0,'a.friend_user_id'=>$this->user['id']])->order("a.updatetime desc")->field("a.*,b.nickname,b.avatar,b.chat_uuid")->select();
        $list = [];
        foreach($user_list as $key => $val){
            if($val['friend_user_id'] != $val['user_id']){
                $val['avatar'] = cdnurl($val['avatar']);
                $val['updatetime'] = date("Y-m-d H:i:s",$val['updatetime']);
                $list[] = $val;
            }
        }

        __success("操作成功",['list'=>$list]);
    }

    public function shenheFriend(){
        $id  = $this->param("id/d");
        $status  = $this->param("status/d");
        if($status != 1) $status = 2;
        $item = Db::name("bbfx_chat_friend")->where(['uniacid'=>UNIACID,'id'=>$id,'friend_user_id'=>$this->user['id']])->find();
        if(empty($item)){
            __error("未查询申请信息");
        }

        if($item['status'] == 1){
            __error("已经添加好友了");
        }

        try {
            Db::startTrans();

            $res = Db::name("bbfx_chat_friend")->where(['id'=>$item['id']])->update(['status'=>$status]);
            if(empty($res)){
                throw new \Exception("操作失败");
            }

            Db::name("bbfx_chat_friend")->where(['id'=>$item['id']])->update(['shtime'=>time()]);

            if($status == 1){
                $result = $this->model->addDialogue($item['user_id'],$item['friend_user_id']);
                if($result['code'] != 1){
                    throw new \Exception($result['message']);
                }
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            __error($e->getMessage());
        }

        __success("操作成功");
    }

    // 好友列表
    public function getFriendList(){

        $where = ['b.uniacid'=>UNIACID,'b.status'=>1,'a.status'=>1,'a.friend_user_id'=>$this->user['id'],'a.user_del'=>0];
        $list1 = Db::name("bbfx_chat_friend")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->order("a.updatetime desc")->field("a.id,a.user_id,a.updatetime,b.nickname,b.avatar,b.chat_uuid")->select();
        

        $where = ['b.uniacid'=>UNIACID,'b.status'=>1,'a.status'=>1,'a.user_id'=>$this->user['id'],'a.user_del'=>0];
        $list2 = Db::name("bbfx_chat_friend")->alias("a")->join("bbfx_user b","a.friend_user_id=b.id","LEFT")->where($where)->order("a.updatetime desc")->field("a.id,a.friend_user_id as user_id,a.updatetime,b.nickname,b.avatar,b.chat_uuid")->select();
        $user_list = array_merge($list1,$list2);

        $updatetime = array_column($user_list,'updatetime');
        array_multisort($updatetime,SORT_DESC,$user_list);
        $list = [];
        foreach($user_list as $key => $val){
            $val['avatar'] = cdnurl($val['avatar']);
            $val['updatetime'] = date("Y-m-d H:i:s",$val['updatetime']);
            if($val['user_id'] != $this->user['id']){
                $list[] = $val;
            }
        }

        __success("操作成功",['list'=>$list]);
    }

    // 聊天列表
    public function getList(){
        $result = $this->model->getList($this->user);
        __result($result);
    }

    // 聊天详情
    public function getChatDetailList(){
        $to_user_id = $this->param("to_user_id/s");
        $chat_id = $this->param("chat_id/d");
        $result = $this->model->getChatDetailList($this->user,$to_user_id,$chat_id);
        __result($result);
    }

    // 删除对话
    public function deleteChat(){
        $to_user_id = $this->param("to_user_id/s");
        $result = $this->model->deleteChat($this->user,$to_user_id);
        __result($result);
    }

    // 删除好友
    public function deleteFriend(){
        $to_user_id = $this->param("to_user_id/s");
        $result = $this->model->deleteFriend($this->user,$to_user_id);
        __result($result);
    }

    // 添加客服
    public function addKefu(){
        $result = $this->model->addKefu($this->user['id']);
        __result($result);
    }
}