<?php

namespace app\api\controller;


use addons\faqueue\library\QueueApi;
use app\common\controller\Api;
use app\common\model\Gateway;
use think\Db;

use think\exception\ValidateException;

/**
 * 贵族接口
 */
class Noble extends Api
{
    protected $noNeedLogin = ['getNobleLevelList','getNobleLevelPrivilegeInfo','onNoble'];
    protected $noNeedRight = ['*'];

    /**
     * 获取贵族等级列表
     */
    public function getNobleLevelList() {
        $noblelevelList = controller('api/Party')->checkGetNobleLevelList(config('token')['key']);
        return $this->success("获取成功！",$noblelevelList);
    }

    /**
     * 根据贵族等级ID获取贵族等级特权
     */
    public function getNobleLevelPrivilegeInfo() {
        $level_id = $this->request->request("level_id");
        if (!$level_id) {
            $this->error(__('Invalid parameters'));
        }
        $nplModel = new \app\common\model\NobleLevelPrivilege();
        $where = [];
        $where["level_id"] = $level_id;
        $where["is_show"] = 1;
        $nplInfo = $nplModel->where($where)->select();

        if($nplInfo) {
            return $this->success("获取成功！",$nplInfo);
        } else {
            return $this->success("数据为空！",[]);
        }

    }

    /**
     * 获取贵族等级以及到期时间
     */
    public function getNobleDuetime() {
        $level_id = $this->request->request("level_id");
        if (!$level_id) {
            $this->error(__('Invalid parameters'));
        }
        $userModel = new \app\common\model\User();
        $info = $userModel->getUserNobleInfo($level_id,$this->auth->id);
        return $this->success("获取成功！",$info);
    }

    /**
     * 获取贵族等级所需金额
     */
    public function getNobleLogInfo() {
        $level_id = $this->request->request("level_id");
        if (!$level_id) {
            $this->error(__('Invalid parameters'));
        }
        $nldlModel = new \app\common\model\NobleDredgeLog();
        $noblelevelModel = new \app\common\model\NobleLevel();
        $noblelevelInfo = $noblelevelModel->where(["id"=>$level_id])->find();

        // 获取贵族等级开通信息
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["level_no"] = $noblelevelInfo["level_no"];
        $nldlCount = 0;
        $nldlInfo = $nldlModel->where($where)->limit(1)->order("dredge_num","desc")->select();
        $nldlInfo && $nldlInfo = $nldlInfo[0];
        // 判断是否是首月开通
        if($nldlInfo) {
            $nldlCount = $nldlInfo["dredge_num"];
        }
        $money = $nldlCount>0?$noblelevelInfo["renew"]:$noblelevelInfo["first"];
        $data["money"] = $money;
        return $this->success("获取成功！",$data);
    }

    /**
     * 开通贵族
     */
    public function beNoble() {
        $level_id = $this->request->request("level_id"); // 贵族等级ID
        if (!$level_id) {
            $this->error(__('Invalid parameters'));
        }

        $time = time();
        // 获取贵族信息
        $noblelevelModel = new \app\common\model\NobleLevel();
        $nldlModel = new \app\common\model\NobleDredgeLog();
        $noblelevelInfo = $noblelevelModel->where(["id"=>$level_id])->find();

        // 获取贵族等级开通信息
        $where = [];
        $where["user_id"] = $this->auth->id;
        $where["level_no"] = $noblelevelInfo["level_no"];
        $nldlCount = 0;
        $nldlInfo = $nldlModel->where($where)->limit(1)->order("dredge_num","desc")->select();
        $nldlInfo && $nldlInfo = $nldlInfo[0];
        // 判断是否是首月开通
        if($nldlInfo) {
            $nldlCount = $nldlInfo["dredge_num"];
//            if(time() - $nldlInfo["createtime"] < 60) { // 同一个人，同一等级，一分钟之内重复开通，鉴定为系统bug
//                $this->error("您刚刚开通过此贵族特权");
//            }
        }
        $money = $nldlCount>0?$noblelevelInfo["renew"]:$noblelevelInfo["first"];

        if(!$noblelevelInfo || $money <= 0) {
            $this->error(__('贵族等级信息有误！'));
        }
        $userModel = new \app\common\model\User();
        $userjewellogModel = new \app\common\model\UserJewelLog();
        $where = [];
        $where["id"] = $this->auth->id;
        $userInfo = $userModel->where($where)->find();
        // 判断用户余额
        if($userInfo["jewel"]-$money < 0) {
            $this->error("您的钻石余额不足，请先充值");
        }

        // 获取当前用户贵族等级
        if($userInfo["noble"] == $level_id) {
            $duetime = $userInfo["noble_duetime"];
        } else {
            $duetime = $time;
        }

        Db::startTrans();
        try{
            // 扣除当前用户钻石余额 更新用户贵族信息
            $where = [];
            $where["id"] = $this->auth->id;
            $duetime = strtotime("+1 month",$duetime);
            $nextMonth = strtotime("+1 month",$time);
            $data = [];
            $data["noble"] = $level_id;
            $data["noble_duetime"] = $duetime;
            $submoney = bcsub($userInfo["jewel"],$money);
            // 开通返现
            $return = $nldlCount>0?$noblelevelInfo["give"]:$noblelevelInfo["firstgive"];
            $data["jewel"] = bcadd($submoney,$return);

            $res1 = $userModel->update($data,$where);
            // 添加当前用户钻石流水记录
            $res2 = $userjewellogModel->addUserJewelLog($this->auth->id, $money, "-", $userInfo["jewel"], "开通贵族：'" . $noblelevelInfo["name"] . "',扣除" . $money . "钻石！", 5);

            // 添加贵族等级开通明细
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["level_no"] = $noblelevelInfo["level_no"];
            $data["dredge_num"] = $nldlCount+1;
            $data["createtime"] = $time;
            $res3 = $nldlModel->insertGetId($data);

            // 添加当前用户钻石流水记录
            $res4 = $userjewellogModel->addUserJewelLog($this->auth->id, $return, "+", $userInfo["jewel"] - $money, "开通贵族：'" . $noblelevelInfo["name"] . "',赠送" . $money . "钻石！", 5);


            if($res1 && $res2 && $res3 && $res4) {
                Db::commit();
                // $this->onNobleEffect($noblelevelInfo,$this->auth->id,$this->auth->nickname);
                $this->onNobleAttire($noblelevelInfo,$this->auth->id,$nextMonth,$time);

                // +exp
                $nobleArr = ['1'=>'entymIFE3J'];
                isset($nobleArr[$level_id]) && \app\common\model\TaskLog::tofinish($this->auth->id,$nobleArr[$level_id],1);

                // +message
                \app\common\model\Message::addMessage($this->auth->id,"贵族开通通知","恭喜，您已成功开通！".$noblelevelInfo["name"]." 贵族特权！");

                // 赠送消息尾灯
                \app\common\model\AttireBack::addToMyBack(15,$this->auth->id);

                // 赠送聊天气泡
                if($noblelevelInfo->tqgq) {
                    $params_from = $this->request->request("params_from"); // 贵族等级ID
                    $attireInfo = \app\common\model\Attire::where(["use"=>1,"use_id"=>$level_id])->find();
                    $attireInfo && \app\common\model\AttireBack::addToMyBack($attireInfo->id,$this->auth->id,$params_from);
                }


                $this->success("开通成功！");
            }

        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }


    /**
     * 获取指定等级的贵族数据
     * @param $level_id
     */
    private function getNobleLevelData($level_id)
    {

        $getNobleLevelList = controller('api/Party')->checkGetNobleLevelList(config('token')['key']);
        foreach ($getNobleLevelList as $v){
            if ($level_id == $v['id']) return $v;
        }
        return [];
    }

    /**
     * 消费足额开通贵族(内部调用）
     * @param string $tokenKey 内部调用密码
     * @param string $level_id
     * @return void
     */
    public function checkBeNoble2($tokenKey='',$level_id=''){

        if ($tokenKey!==config('token')['key']) return;
        $this->beNoble2($level_id);
    }
    private function beNoble2($level_id) {
        if (empty($level_id)) return;

        //算当日0点开启的
        $time = strtotime(date('Y-m-d'),time());
        // 获取贵族信息
        $noblelevelModel = new \app\common\model\NobleLevel();
        $nldlModel = new \app\common\model\NobleDredgeLog();
        $noblelevelInfo = $this->getNobleLevelData($level_id);

        Db::startTrans();
        try {
            // 获取贵族等级开通信息
            $where = [];
            $where["user_id"] = $this->auth->id;
            $where["level_no"] = $noblelevelInfo["level_no"];
            $nldlCount = 0;
            $nldlInfo = $nldlModel->where($where)->order("dredge_num", "desc")->find();
            if (!empty($nldlInfo)) $nldlCount = $nldlInfo["dredge_num"];

            // 更新用户贵族信息
            $userModel = new \app\common\model\User();
            $where = [];
            $where["id"] = $this->auth->id;
            $duetime = strtotime("+1 month", $time);
            $nextMonth = $duetime;
            $data = [];
//            if($level_id>$this->auth->noble_max) {
//                $data["noble_max"] = $level_id;
//            }
            $data["noble"] = $level_id;
            $data["noble_duetime"] = $duetime;
            $res1 = $userModel->update($data, $where);

            // 添加贵族等级开通明细
            $data = [];
            $data["user_id"] = $this->auth->id;
            $data["level_no"] = $noblelevelInfo["level_no"];
            $data["dredge_num"] = $nldlCount + 1;
            $data["createtime"] = time();
            $res2 = $nldlModel->insertGetId($data);

            if ($res1 && $res2) {
                Db::commit();
                // $this->onNobleEffect($noblelevelInfo,$this->auth->id,$this->auth->nickname);
                $this->onNobleAttire($noblelevelInfo, $this->auth->id, $nextMonth, $time);

                // +exp
                $nobleArr = ['1' => 'entymIFE3J'];
                isset($nobleArr[$level_id]) && \app\common\model\TaskLog::tofinish($this->auth->id, $nobleArr[$level_id], 1);
                // +message
                \app\common\model\Message::addMessage($this->auth->id, "贵族开通通知", "恭喜，您已成功开通！" . $noblelevelInfo["name"] . " 贵族特权！");

                // 赠送消息尾灯
                \app\common\model\AttireBack::addToMyBack(15, $this->auth->id);

                // 赠送聊天气泡
                if ($noblelevelInfo['tqgq']) {
                    $params_from = $this->request->request("params_from"); // 贵族等级ID
                    $attireInfo = \app\common\model\Attire::where(["use" => 1, "use_id" => $level_id])->find();
                    $attireInfo && \app\common\model\AttireBack::addToMyBack($attireInfo->id, $this->auth->id, $params_from);
                }

                $this->onNobleEffect($noblelevelInfo,$this->auth->id,$this->auth->nickname);
                //定时保级
//                echo '升级'.$level_id;
                if ($level_id>1) QueueApi::timeRelegation($this->auth->id,$nextMonth,$level_id);
            }
        }catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    /**
     * 开通贵族后效果
     */
    private function onNobleEffect($noblelevelInfo,$user_id,$user_nickname) {

        $serviceNotice = "";
        $serviceSvga = "";
        $partyNotice = "";
        // 全服通知
        if($noblelevelInfo["qftz"] == 1) {
            $serviceNotice = "恭喜，玩家：".$user_nickname." 成功升级：".$noblelevelInfo["name"]."贵族特权！";
        }
        //全服动画
        if($noblelevelInfo["qfdh"]) {
            $serviceSvga = $noblelevelInfo["qfdh"];
        }
        // 公屏通知
        if($noblelevelInfo["gptz"] == 1) {
            $partyNotice = "恭喜，玩家：".$user_nickname." 成功升级：".$noblelevelInfo["name"]."贵族特权！";
        }

        $tcpArr = [];
        $tcpArr['type'] = "userBeNoble";
        $tcpArr['data'] = [
            'user_id' => $user_id,
            'nickname' => $user_nickname,
            'serviceNotice' => $serviceNotice,
            'serviceSvga' => $serviceSvga,
            'partyNotice' => $partyNotice,
        ];
        $tcpJson = json_encode($tcpArr);
        Gateway::sendToAll($tcpJson);

    }

    /**
     * 开通贵族后获得专属座驾
     */
    private function onNobleAttire($noblelevelInfo,$user_id,$nextMonth,$time) {
        // 获取贵族专属座驾信息
        $nobleAttireInfo = \app\common\model\NobleAttire::where(["noble_id"=>$noblelevelInfo["id"]])->find();
        if($nobleAttireInfo) {
            Db::startTrans();
            try{
                // 更新当前用户背包使用状态
                $res1 = \app\common\model\AttireBack::update(["is_using"=>0],["user_id"=>$user_id]);
                // 保存用户背包信息
                $data = [];
                $data["user_id"] = $user_id;
                $data["attire_id"] = 0;
                $data["type"] = 1;
                $data["attire_name"] = $nobleAttireInfo["attire_name"];
                $data["price"] = $nobleAttireInfo["price"];
                $data["file_image"] = $nobleAttireInfo["file_image"];
                $data["android_image"] = $nobleAttireInfo["file_image"];
                $data["gif_image"] = $nobleAttireInfo["gif_image"];
                $data["limit_day"] = round(($nextMonth-$time)/86400);
                $data["duetime"] = $nextMonth;
                $data["is_use"] = 1;
                $data["is_using"] = 1;
                $data["createtime"] = time();
                $res2 = \app\common\model\AttireBack::insert($data);
                if($res1 && $res2) {
                    Db::commit();
                }

            }catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
    }

    public function aa() {
        Gateway::sendToAll("aaaaaa");
    }
}
