<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\service\RoomService;
use fast\Random;
use think\Collection;
use \think\Log;
use Redis;
use app\common\library\Sms as Smslib;
use app\common\service\TenimService;
use think\Db;
use think\Cache;
/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['index','contactus','tcpTest','getAppShare','getWebsiteInfo','getUserCharmRankList',
        'getPartyHotList','searchUsers','getInviteCode','getEdition','getiosEdition','getInviteImg','getWebsiteInfoForMini','getBankList',
        'getSwitch','ageList','starList','bannerList','keyworldconfig','switchenum'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    /*public function index()
    {
        // 强制关闭需要退出正在房间的用户
        $tenim = new \app\api\controller\Tenim();
        $tenim->outMemberFromRoom(4);
        $this->success('请求成功');
    }*/



    /**
     * 获取主播魅力值排行
     */
    public function getUserCharmRankList() {
        $time = $this->request->request("time",0,"intval"); //时间筛选 1=小时榜,2=今日榜,3=本周榜,4=月榜
        if(!in_array($time,[1,2,3,4])) {
            $this->error("参数传入错误!");
        }

        $hour = strtotime(date("Y-m-d H:00:00"));
        $today = strtotime(date("Y-m-d 00:00:00"));
        $weekend = strtotime('monday this week');
//        $weekend = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
        $month = strtotime(date("Y-m-01 00:00:00"));
        // 剩余时间
        $thistime = time();
        switch ($time) {
            case 1:
                $redtime = 3600-($thistime - $hour);
                break;
            case 2:
                $redtime = 3600*24-($thistime - $today);
                break;
            case 3:
                $redtime = 3600*24*7-($thistime - $weekend);
                break;
            case 4:
                $monthend = mktime(23,59,59,date("m"),date("t"),date("Y"));
                $redtime = ($monthend - $month)-($thistime - $month);
                break;
        }

        $timeArr = [1=>$hour,2=>$today,3=>$weekend,4=>$month];
        $where = [];
        $where["a.createtime"] = ["gt",$timeArr[$time]];
        $list = \app\common\model\UserCharmRank::alias("a")
            ->field("a.party_id as id,sum(a.charm) as charm,u.avatar,u.nickname,u.gender,u.level,u.is_live")
            ->where($where)
            ->join("hx_user u","u.id = a.user_id",'LEFT')
//            ->join("hx_party p","p.user_id = a.user_id",'LEFT')
            ->group("a.user_id")
            ->order("charm","desc")
            ->limit(100)
            ->select();

        $data = [];
        $data["redtime"] = $redtime;
        $data["data"] = $list;
        $this->success("获取成功!",$data);
    }

    /**
     * 获取收礼排行
     */
    public function getUserGiftRank() {
        $time = $this->request->request("time",0,"intval"); //时间筛选 1=小时榜,2=今日榜,3=本周榜,4=月榜
        if(!in_array($time,[1,2,3,4])) {
            $this->error("参数传入错误!");
        }

        $hour = strtotime(date("Y-m-d H:00:00"));
        $today = strtotime(date("Y-m-d 00:00:00"));
        $weekend = strtotime('monday this week');
        $month = strtotime(date("Y-m-01 00:00:00"));
        // 剩余时间
        $thistime = time();
        switch ($time) {
            case 1:
                $redtime = 3600-($thistime - $hour);
                break;
            case 2:
                $redtime = 3600*24-($thistime - $today);
                break;
            case 3:
                $redtime = 3600*24*7-($thistime - $weekend);
                break;
            case 4:
                $monthend = mktime(23,59,59,date("m"),date("t"),date("Y"));
                $redtime = ($monthend - $month)-($thistime - $month);
                break;
        }

        $timeArr = [1=>$hour,2=>$today,3=>$weekend,4=>$month];
        $where = [];
        $where["a.createtime"] = ["gt",$timeArr[$time]];
        $list = model('GiftUserParty')->alias("a")
            ->field("sum(a.value) as total_price,a.user_to_id,u.avatar,u.nickname")
            ->where($where)
            ->join("hx_user u","u.id = a.user_to_id")
            ->group("a.user_to_id")
            ->order("total_price","desc")
            ->limit(100)
            ->select();

        $data = [];
        $data["redtime"] = $redtime;
        $data["data"] = $list;
        $this->success("获取成功!",$data);
    }

    /**
     * 获取消费排行
     */
    public function getUserPayRank() {
        $time = $this->request->request("time",0,"intval"); //时间筛选 1=小时榜,2=今日榜,3=本周榜,4=月榜
        if(!in_array($time,[1,2,3,4])) {
            $this->error("参数传入错误!");
        }

        $hour = strtotime(date("Y-m-d H:00:00"));
        $today = strtotime(date("Y-m-d 00:00:00"));
        $weekend = strtotime('monday this week');
        $month = strtotime(date("Y-m-01 00:00:00"));
        // 剩余时间
        $thistime = time();
        switch ($time) {
            case 1:
                $redtime = 3600-($thistime - $hour);
                break;
            case 2:
                $redtime = 3600*24-($thistime - $today);
                break;
            case 3:
                $redtime = 3600*24*7-($thistime - $weekend);
                break;
            case 4:
                $monthend = mktime(23,59,59,date("m"),date("t"),date("Y"));
                $redtime = ($monthend - $month)-($thistime - $month);
                break;
        }

        $timeArr = [1=>$hour,2=>$today,3=>$weekend,4=>$month];
        $where = [];
        $where["a.type"] = ["in",[0,2,3,5,6,13]];//查看wallet.php文件
        $where["a.createtime"] = ["gt",$timeArr[$time]];
        $list = model('UserJewelLog')->alias("a")
            ->field("sum(a.value) as total_price,a.user_id,u.avatar,u.nickname")
            ->where($where)
            ->join("hx_user u","u.id = a.user_id")
            ->group("a.user_id")
            ->order("total_price","desc")
            ->limit(100)
            ->select();

        $data = [];
        $data["redtime"] = $redtime;
        $data["data"] = $list;
        $this->success("获取成功!",$data);
    }

    /**
     * 获取派对热度排序
     */
    public function getPartyHotList() {
        // 剩余时间
        $thistime = time();
        $hour = strtotime(date("Y-m-d H:00:00"));
        $redtime = 3600-($thistime - $hour);

        $where = [];
        $where["a.createtime"] = ["gt",$hour];
        $where["p.room_type"] = 1;
        $list = \app\common\model\PartyHot::alias("a")
            ->field("sum(a.hot) as hot,p.id,u.avatar,p.party_name,p.party_logo")
            ->where($where)
            ->join("hx_party p","p.id = a.party_id")
            ->join("hx_user u","u.id = p.user_id")
            ->group("a.party_id")
            ->order("hot","desc")
            ->limit(100)
            ->select();

        $data = [];
        $data["redtime"] = $redtime;
        $data["data"] = $list;
        $this->success("获取成功!",$data);
    }

    /**
     * 首页搜索
     */
    public function searchUsers() {
        $search = $this->request->request("search"); //关键词筛选
        if(!$search) {
            $this->error("请输入搜索内容!");
        }
        // 搜索派对
        global $whereOr;
        $where = [];
        $whereOr["party_id"] = $search;
        $whereOr["party_name"] = ["like","%$search%"];
        $where["room_type"] = 1;
        $partyList = \app\common\model\Party::field("id,party_logo,party_id,party_name")
            ->where($where)
            ->where(function ($query) {
            global $whereOr;
            $query->whereOr($whereOr);
        })->order("party_hot","desc")->select();


        // 搜索直播间
        global $whereOrlive;
        $where = [];
        $whereOrlive["party_id"] = $search;
        $whereOrlive["party_name"] = ["like","%$search%"];
        $where["room_type"] = 2;
        $liveList = \app\common\model\Party::field("id,party_logo,party_id,party_name")
            ->where($where)
            ->where(function ($query) {
                global $whereOrlive;
                $query->whereOr($whereOrlive);
            })
            ->order("party_hot","desc")->select();
        // 相关用户
        $where = [];
        $where["a.nickname"] = ["like","%$search%"];
        $where["a.u_id"] = $search;
        $userList = \app\common\model\User::alias("a")->field("id,avatar,nickname,u_id,f.fans")
            ->join("hx_view_fans f","f.user_id = a.id","left")
            ->order("a.is_online,a.noble,a.level")
            ->whereOr($where)->select();
        $res = [];
        $res["partylist"] = $partyList;
        $res["livelist"] = $liveList;
        $res["userlist"] = $userList;

        $this->success("获取成功!",$res);
    }

    /**
     * 首页搜索
     */
    public function searchList() {
        $search = $this->request->request("search"); //关键词筛选
        if(!$search) {
            $this->error("请输入搜索内容!");
        }
        // 搜索房间(派对和直播)
        global $whereOr;
        $where = [];
        $whereOr["party_id"] = $search;
        $whereOr["party_name"] = ["like","%$search%"];
        //$where['is_online'] = 1;
        $where['is_close'] = 0;
        $where['status'] = 1;
        $partyList = \app\common\model\Party::field("id,room_type,party_logo,party_id,party_name,party_type")
            ->where($where)
            ->where(function ($query) {
                global $whereOr;
                $query->whereOr($whereOr);
            })->order("party_hot","desc")->select();
        $partyList = collection($partyList)->toArray();
        if (!empty($partyList)) {//在线信息
            $partyListIds = array_column($partyList,'id');
            /*$tenimService = new TenimService();
            $partyParams = ['party_ids'=>$partyListIds];
            $partyRes = $tenimService->getRoomUser($partyParams);*/
            /*if ($partyRes['status'] == 1) {

            }*/
            $roomService = new RoomService();
            foreach ($partyList as $pKey => &$pVal) {
                // 派对类型
                $partyTypeName = "普通房";
                if($pVal["party_type"]) {
                    $partyTypeName = \app\common\model\PartyType::where(["id"=>$pVal["party_type"]])->value("name");
                }
                $mod = isset($pVal["party_type"])?intval($pVal["party_type"])%5:1;
                $pVal["party_type_color"] = $mod == 0?5:$mod;
                $pVal["type_name"] = $partyTypeName;
                $userDataResult = $roomService->getPartyUserList(['party_id'=>$pVal['id']]);
                $userDataRes = isset($userDataResult['data']) ? $userDataResult['data'] : [];
                $pVal['member_list'] = isset($userDataRes['member_list']) ? $userDataRes['member_list'] : [];
                $pVal['online_num']  = isset($userDataRes['online_num']) ? $userDataRes['online_num'] : [];
            }
        }
        // 家族
        $guildWhere['status'] = 1;
        $guildWhere['name'] = ["like","%$search%"];
        $guildList = model('Guild')->where($guildWhere)->with(['guildmember'=>function($gquery){
            $gquery->where(['status'=>1]);
        }])->field('id,g_id,name,image')->select();
        if (!empty($guildList)) {
            $userField = 'id,nickname,avatar';
            foreach ($guildList as $gKey => &$gVal) {
                $userData =[];
                if (isset($gVal['guildmember'])) {
                    $memberUids = array_column($gVal['guildmember'],'user_id');
                    $userWhere['is_online'] = 1;
                    $userWhere['id'] = ['in',$memberUids];
                    $userData = model('User')->field($userField)->where($userWhere)->select();
                }
                /*$mod = intval($gKey)%5;
                $pVal["party_type_color"] = $mod == 0?5:$mod;*/
                $gVal["party_type_color"] = 1;
                $gVal["type_name"] = '普通房';
                $gVal['member_list'] = $userData;
                $gVal['online_num'] = count($userData);
                unset($gVal['guildmember']);
            }
        }
        // 相关用户
        $where = [];
        $where["a.nickname"] = ["like","%$search%"];
        $where["a.u_id"] = $search;
        $userList = \app\common\model\User::alias("a")->field("id,avatar,nickname,u_id,f.fans")
            ->join("hx_view_fans f","f.user_id = a.id","left")
            ->order("a.is_online,a.noble,a.level")
            ->whereOr($where)->select();
        $res = [];
        $res["roomlist"] = $partyList;
        $res["guildlist"] = $guildList;
        $res["userlist"] = $userList;

        $this->success("获取成功!",$res);
    }


    /**
     * 获取银行列表
     */
    public function getBankList() {
        $this->success("获取成功!",["banklist"=>\app\common\model\Bank::select()]);
    }

    /**
     * 获取开关配置
     */
    public function getSwitch() {
        $this->success("获取成功!",["switch"=>config("site.switch")]);
    }





    /**
     * 星座列表
     * @return void
     */
    public function starList()
    {
        try {
            $field = 'id,name,image';
            $where['status'] = 1;
            $result = model('Constellation')->field($field)->where($where)->order('weigh asc')->select();
            if (!$result) {
                $result = list_domain_image($result,['image']);
            }
            $this->success('获取成功',$result);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }




    //开关设置
    public function switchenum(){
        $rs = [
            'alipay_switch'   => config('site.alipay_switch'),  //支付宝支付开关
            'wechat_switch'   => config('site.wechat_switch'),  //微信支付开关
            'recharge_switch' => config('site.recharge_switch'),  //所有充值开关
        ];
        $this->success('success',$rs);
    }

    ///////上面的没用到//////

    public function index(){
        echo 'apisuccess';
        exit;
    }



    //附近
    public function fujin(){
        $where = [
            'user.id' => ['neq',$this->auth->id],
            'user.status' => 1,
            'user.city_id' => $this->auth->city_id,
        ];

        //排除黑名单的
        $where_black = [];
        $black_ids = Db::name('user_blacklist')->where(['user_id'=>$this->auth->id])->column('black_user_id');
        if(!empty($black_ids)){
            $where_black['user.id'] = ['NOTIN',$black_ids];
        }

        $field = [
            'user.id',
            'user.u_id',
            'user.username',
            'user.nickname',
            'user.avatar',
            'user.gender',
            'user.desc',
            'age.name as age_text',
            'job.name as job_text',
            'area.name as city_text',
            '(st_distance(point (' . $this->auth->longitude . ', ' . $this->auth->latitude . '),point(user.longitude,user.latitude))*111195) as distance',
        ];
        $list = Db::name('user')->alias('user')->field($field)
            ->join('age','user.age_id = age.id','LEFT')
            ->join('enum_job job','user.job_id = job.id','LEFT')
            ->join('shopro_area area','user.city_id = area.id','LEFT')
            ->where($where)
            ->where($where_black)
            ->order('distance asc')
            ->autopage()
            ->select();
        $list = list_domain_image($list,['avatar']);
        foreach($list as $key => &$val){
            $val['distance'] = bcdiv(intval($val['distance']),1000,1).'km';
            $val['is_follow'] = $this->is_follow($this->auth->id,$val['id']);
            $val['is_friend'] = $this->is_friend($this->auth->id,$val['id']);
        }

        $this->success(1,$list);
    }

    //同城
    public function samecity(){

        $where = [
            'user.id' => ['neq',$this->auth->id],
            'user.status' => 1,
            'user.city_id' => $this->auth->city_id,
        ];

        //排除黑名单的
        $where_black = [];
        $black_ids = Db::name('user_blacklist')->where(['user_id'=>$this->auth->id])->column('black_user_id');
        if(!empty($black_ids)){
            $where_black['user.id'] = ['NOTIN',$black_ids];
        }

        $field = [
            'user.id',
            'user.u_id',
            'user.username',
            'user.nickname',
            'user.avatar',
            'user.gender',
            'user.desc',
            'age.name as age_text',
            'job.name as job_text',
            'area.name as city_text',
        ];
        $list = Db::name('user')->alias('user')->field($field)
            ->join('age age','user.age_id = age.id','LEFT')
            ->join('enum_job job','user.job_id = job.id','LEFT')
            ->join('shopro_area area','user.city_id = area.id','LEFT')
            ->where($where)
            ->where($where_black)
            ->autopage()
            ->select();
        $list = list_domain_image($list,['avatar']);

        $this->success(1,$list);
    }

    //匹配配置
    /*public function pipei_config(){
        $result = [
            'index_pipei_switch' => config('site.index_pipei_switch'), //匹配开关
        ];

        //首页匹配每天每人匹配次数
        $user_id = $this->auth->id;
        $is_vip = $this->is_vip($this->auth->id);
        $times_limit = $is_vip == 1 ? config('site.pipei_oneday_vipuser_times') : config('site.index_pipei_oneday_user_times');

        $times_limit_redis = 'pipei_times_limit_'.$user_id;
        $user_times = Cache::get($times_limit_redis) ?: 0;

        if($times_limit > -1){
            $remain_times = $times_limit - $user_times;
            if($remain_times < 0){
                $remain_times = 0;
            }
        }else{
            $remain_times = -1;
        }

        $result['remain_times'] = $remain_times;

        $this->success(1,$result);
    }*/

    //匹配
    //做防止重复处理,参照荔枝
    //做用户在线处理,参照mita,用户不在线,用户语音视频中,用户房间内时,不能被匹配到
    public function pipei(){

        //首页匹配功能开关
        /*$index_pipei_switch = config('site.index_pipei_switch');
        if($index_pipei_switch != 1){
            $this->error('匹配功能维护中,请稍后再试');
        }*/

        //缓存,防重复
        $user_id = $this->auth->id;
        $user_id_redis = 'pipei_repeat_'.$user_id;
        $redis_ids = json_decode(Cache::get($user_id_redis),true);

        //首页匹配每天每人匹配次数
        /*$is_vip = $this->is_vip($this->auth->id);
        $times_limit = $is_vip == 1 ? config('site.pipei_oneday_vipuser_times') : config('site.index_pipei_oneday_user_times');

        $times_limit_redis = 'pipei_times_limit_'.$user_id;
        $user_times = Cache::get($times_limit_redis) ?: 0;

        if($times_limit > -1 && $user_times >= $times_limit){
            $this->error('今日已超匹配上限'.$times_limit.'次');
        }*/

        //where
        $where = [
            'user.id' => ['neq',$this->auth->id],
            'user.status' => 1,
        ];

        //性别
        $gender = input('gender','all');
        if($gender != 'all'){
            $where['user.gender'] = $gender;
        }

        //排除黑名单的
        $where_black = [];
        $black_ids = Db::name('user_blacklist')->where(['user_id'=>$this->auth->id])->column('black_user_id');
        if(!empty($black_ids)){
            $where_black['user.id'] = ['NOTIN',$black_ids];
        }

        //匹配一个
        $result = $this->pipei_action($redis_ids,$where,$where_black);

        //匹配不到,移除防重复
        if(!$result) {
            Cache::rm($user_id_redis);
            $redis_ids = [];
            $result = $this->pipei_action($redis_ids,$where,$where_black);
        }
        // 追加一个防重复
        if($result){
            if($redis_ids) {
                $redis_ids[] = $result;
            } else {
                $redis_ids = [$result];
            }
            Cache::set($user_id_redis,json_encode($redis_ids));

            //设置次数
            /*$second = strtotime(date('Y-m-d'))+86400 - time();
            Cache::set($times_limit_redis,$user_times+1,$second);*/
        }else{
            Cache::rm($user_id_redis);
        }

        $this->success(1,$result);
    }

    private function pipei_action($redis_ids,$where,$where_black){
        $where_op = [];
        if(!empty($redis_ids)){
            $where_op['user.id'] = ['NOTIN',$redis_ids];
        }

        $result = Db::name('user')->alias('user')
//            ->join('user_active active' ,'user.id = active.user_id','LEFT')
            ->where($where)
            ->where($where_op)
            ->where($where_black)
            ->orderRaw('rand()')
            ->value('user.id');

        return $result;
    }

    public function test(){
        //缓存,防重复
        $user_id = $this->auth->id;
        $user_id_redis = 'pipei_repeat_'.$user_id;
        $redis_ids = json_decode(Cache::get($user_id_redis),true);
        dump($redis_ids);


        $times_limit_redis = 'pipei_times_limit_'.$user_id;
        $user_times = Cache::get($times_limit_redis) ?: 0;
        dump($user_times);
    }
    public function testrm(){
        $user_id = $this->auth->id;
        $user_id_redis = 'pipei_repeat_'.$user_id;
        Cache::rm($user_id_redis);

        $times_limit_redis = 'pipei_times_limit_'.$user_id;
        Cache::rm($times_limit_redis);
    }

}