<?php
/**
 * Created by PhpStorm.
 * User: blues
 * Date: 2018/12/1
 * Time: 15:06
 */

namespace App\Api\Model;

use phpDocumentor\Reflection\Types\Mixed_;
use \System\Model;


class Chat_rooms extends Model {
    public $timestamps = false;
    protected $table = 'chat_rooms';
    static $room_info;

    public function getRoomList(int $vip_level) {
        $cond = ['status' => 1];
        if ($vip_level === -1) {
            $vip_level = 0;
        }
        if ($vip_level === -2) {
            $cond['limit_vip'] = -2;
        } else {
            $cond['limit_vip'] = ['<=', $vip_level];
        }
        return self::where($cond)->whereOr('limit', 0)->get();
    }

    public function getRoomListByGameName(int $vip_level, string $game_name) {
        $cond = ['status' => 1];
        if ($vip_level === -1) {
            $vip_level = 0;
        }
        $cond['game_name'] = $game_name;
        if ($vip_level === -2) {
            $cond['limit_vip'] = -2;
        } else {
            $cond['limit_vip'] = ['<=', $vip_level];
        }
        return self::where($cond)->get();
    }

    /**
     * 代理身份校验（必要条件）
     * @param int $room_id
     * @param string $account
     * @return bool
     */
    public static function agentCheck(int $room_id, string $account): bool {
        //代理房间验证
        if ((new self)->isAdmin(null, $room_id, $_SESSION['uinfo']['account'])) return true;
        $root_agent = self::getRootAgent($account);
        if (!self::$room_info) {
            self::$room_info = self::where('id', $room_id)->first();
        }
        $room_info = self::$room_info;
        if (!$room_info) {
            return false;
        }
        if (intval($room_info->room_type) === 1) {
            return true;
        }
        return $root_agent === $room_info->agentname;
    }

    /**
     * VIP等级校验(必要条件)
     * @param int $room_id
     * @param int $vip_level
     * @return bool
     */
    public static function vipCheck(int $room_id, int $vip_level): bool {
        //vip等级验证
        if ((new self)->isAdmin(null, $room_id, $_SESSION['uinfo']['account'])) return true;
        if ($vip_level === -1) {
            $vip_level = 0;
        }
        if (!self::$room_info) {
            self::$room_info = self::where('id', $room_id)->first();
        }

        $room_level = self::$room_info->limit_vip;
        if ($room_level === -2) {
            if ($vip_level === 0 || $vip_level === -1) {
                return false;
            }
            return true;
        } elseif ($room_level === 0 || $room_level === -1) return true;
        else
            return $room_level <= $vip_level;
    }

    /**
     * 红包超领校验,true=pass
     * @param int $room_id
     * @param string $account_identity
     * @param int $vip_level
     * @return bool
     */
    public static function overTakeCheck(int $room_id, string $account_identity, int $vip_level): bool {
        //红包个数验证
        if ((new self)->isAdmin(null, $room_id, $_SESSION['uinfo']['account'])) return true;
        $redpackNum = (new LuckyMoneyTake())->where('account_identity', $account_identity)->select('hash')->count();
        if (!self::$room_info) {
            self::$room_info = self::where('id', $room_id)->first();
        }
        $targetRoom = self::$room_info;
        $targetLevel = $targetRoom->redbag_grade;//红包限制等级
        $targetLimit = $targetRoom->redbag_limit;//限制等级会员的红包总可领取个数
        if ($targetLevel === -2) {

            if ($vip_level === 0 || $vip_level === -1) {
                return $targetLimit > $redpackNum;
            } else {

                return true;
            }
        } elseif ($targetLevel === 0 || $targetLevel === -1) {
            return true;
        } else {
            if ($targetLevel <= $vip_level) {
                return true;
            }
            return $targetLimit > $redpackNum;
        }
    }

    public static function isAgentRoom($room_id) {
        return self::where('id', $room_id)->first()->room_type === 2 ? true : false;
    }

    public static function isAgentUser(string $account, $parent_path, int $room_id): bool {
        if (!self::$room_info) {
            self::$room_info = self::where('id', $room_id)->first();
        }
        if (self::$room_info->room_type !== 2) return true;

        $p_identity = explode(',', $parent_path);
        $ar = [];
        if (!empty($p_identity)) {
            foreach ($p_identity as $key => $val) {
                $parents = lm('Account', 'Api')->where('identity', $val)->where('account', '!=', 'root')->first(['identity', 'account']);
                $parents = $parents ? $parents->toarray() : [];
                if ($parents) array_unshift($ar, $parents['account']);
            }
        }
        $ar[] = $account;
        return in_array(self::$room_info->agentname, $ar);
    }

    protected function getRootAgent(string $account_identity): string {
        $agent = lm('nagent_detailed', 'commons')->where('agent_user', $account_identity)->first(['parent_path', 'parent_id']);
        $parent_path = $agent->parent_path ?? '';
        $rootUUID = explode(',', $parent_path)[0];
        if (!$rootUUID) return '';
        return lm('Account', 'Api')->where('identity', $rootUUID)->first()->account ?? '';
    }

    /**
     * 红包领取规则验证
     * @param $room_id
     * @return mixed
     */
    public function redPackTakeRule($room_id) {
        //房间打赏规则
        $roomInfo = $this
            ->where('id', $room_id)
            ->where('status', 1)
            ->first(['redbag_grade', 'redbag_limit', 'redbag_max_money', 'redbag_max_no']);
        if (!$roomInfo) {
            //房间不存在或已关闭
            return -7000;
        }
        if ($this->isAdmin($roomInfo, $room_id, $_SESSION['uinfo']['name'])) return $roomInfo;
        $uuid = $_SESSION['uinfo']['identity'];
        //取得当前用户当天领取红包的总个数
        $luckyMoneyTakeNum = lm('LuckyMoneyTake', 'Api')
            ->where('room_id', $room_id)
            ->where('account_identity', $uuid)
            ->where('time', '>=', strtotime('-1 day'))
            ->whereIn('type', [0, 1])
            ->count('id');

        $roomInfo->lucky_money_take_num = $luckyMoneyTakeNum;//今日领取红包的总个数

        $level = $_SESSION['uinfo']['level'];
        $minLevel = (int)$roomInfo->redbag_grade;
        if ($minLevel === -2) {
            $sw = ($level === -2 || $level > 0);
        } else if ($minLevel > 0) {
            $sw = ($level >= $minLevel);
        } else {
            $sw = !($level === 0 || $level === -1);
        }
//        $roomInfo->canTake = $sw;
        if (!$sw && $luckyMoneyTakeNum >= $roomInfo->redbag_limit) {
            //可领个数超出限制
            return -70162;
        }
        return $roomInfo;

    }

    /**
     * 房间用户昵称列表
     * @param int $room_id
     * @return array
     */
    public function getNickNames(int $room_id): array {
        $lm = (new Chat_rooms())->where('id', $room_id)->first();
        $manArr = [];
        if ($lm) {
            $mans = trim($lm->nickname_list) . ',';
            $tmp = explode(',', $mans);
            foreach ($tmp as $k => $v) {
                if (!$v) continue;
                list ($kk, $vv) = explode('||', $v);
                $manArr[$kk] = $vv;
            }
            $manArr['room_mangers_id'] = $lm['room_mangers_id'];
        }
        return $manArr;
    }

    /**
     * 验证用户是否是管理员
     * @param $roomObj
     * @param int $room_id
     * @param string $user_name
     * @return mixed
     */
    public function isAdmin( $roomObj, int $room_id, string $user_name){
        $roomObj ?: $roomObj = $this->where('id', $room_id)->first();
        if (!$roomObj) return false;
        $admins = explode(',', $roomObj->room_mangers_id);
        return in_array($user_name, $admins);
    }
}
