<?php

namespace app\api\controller;


use addons\faqueue\library\QueueApi;
use app\common\controller\Api;
use think\Db;
use Redis;
/**
 * 砸蛋接口
 */
class Eggnew extends Api
{
    protected $noNeedLogin = ['getThisJackpot'];
    protected $noNeedRight = ['*'];

    /**
     * 获取本期奖池列表
     */
    public function getThisJackpot() {
        $type = input('type',1);
        $jackId = \app\common\model\EggJackpot::where(["status"=>1,'type'=>$type])->value("id");
        $egggiftModel = new \app\common\model\EggGift();
        $where = [];
        $where["Jackpot_id"] = $jackId;
        $egggiftList = $egggiftModel->where($where)->group("gift_id")->order("price","desc")->select();
        return $this->success("获取成功!",$egggiftList);
    }

    /**
     * 查找下一个奖池ID
     */
    private function getNextJackpot($jackpot_id,$type) {
        //$type = Db::name('egg_jackpot')->where(['id'=>$jackpot_id])->value('type');

        $jackpotIds = Db::name('egg_jackpot')->order('weigh asc,id asc')->where('type',$type)->column("id");
        $next = 0;
        foreach($jackpotIds as $k => $v) {
            if($v == $jackpot_id) {
                $next = isset($jackpotIds[$k+1])?$jackpotIds[$k+1]:$jackpotIds[0];
            }
        }
        return $next;
    }

    /**
     * 砸金蛋
     */
    public function strike() {
//        $this->error("系统正在维护中。。。");
        $nowtime = time();
        $num  = $this->request->request("num");
        $type = $this->request->request("type",1);
        $party_id = $this->request->request("party_id", 0);// 派对ID
        if($num <=0) {
            $this->error("参数错误");
        }

        //走次数配置
        $total_jewel = Db::name('egg_timesprice')->where('type',$type)->where('times',$num)->find();
        if(empty($total_jewel)){
            $this->error('错误的次数');
        }
        $total_jewel = $total_jewel['price'];

        $giftdata = [];
        $user_id = $this->auth->id;


        $do_no = createUniqueNo('E',$user_id);
        $jockpot_finish = 0; //产出统计


        Db::startTrans();

        //判断钻石余额
        $user_jewel = model('wallet')->getwallet($user_id,'jewel');
        if($user_jewel < $total_jewel){
            $this->error('钻石不足');
            Db::rollback();
        }

            // 查找正在开放的奖池,奖池锁
            $jackpot = Db::name('egg_jackpot')->where(["status"=>1,'type'=>$type])->order('weigh asc,id asc')->lock(true)->find();
            if($jackpot) {
                // 有开放的奖池
                $jackpot_id = $jackpot["id"];
            } else {
                // 没有开放的奖池
                $jackpotlist = Db::name('egg_jackpot')->where('type',$type)->order('weigh asc,id asc')->lock(true)->select();//该类型奖池全锁
                if(empty($jackpotlist)){
                    Db::rollback();
                    $this->error('暂时还没有奖池');
                }

                $jackpot    = $jackpotlist[0];
                $jackpot_id = $jackpot["id"];

                //打开,启用时间
                $open1 = Db::name('egg_jackpot')->where(["id"=>$jackpot_id])->update(["status"=>1,'starttime'=>$nowtime]);
                if($open1 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }
                //重置礼物,启用时间
                $open2 = Db::name('egg_gift')->where(["Jackpot_id"=>$jackpot_id])->update(["is_use"=>0,'starttime'=>$nowtime]);
                if($open2 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }

                //省的再查一次
                $jackpot['status'] = 1;
                $jackpot['starttime'] = $nowtime;
            }

            // 查找奖池对应的奖池礼物
                           Db::name('egg_gift')->where(["Jackpot_id"=>$jackpot_id])->lock(true)->select(); //这个奖池礼物全锁
            $jackpotGift = Db::name('egg_gift')->where(["Jackpot_id"=>$jackpot_id,"is_use"=>0])->select();

            $giftCount = count($jackpotGift);

            //当前奖池已不足,或需要启用下一池
            if($giftCount <= $num) {

                //下一个奖池锁
                $next_jackpot_id = $this->getNextJackpot($jackpot_id,$jackpot['type']);
                Db::name('egg_jackpot')->where('id',$next_jackpot_id)->lock(true)->find();

                // 下个奖池礼物,全锁
                Db::name('egg_gift')->where(["Jackpot_id"=>$next_jackpot_id])->lock(true)->select();

                // 先获取$giftCount个礼物
                $giftArr1 = $jackpotGift;

                // 更新礼物抽取状态
                $giftids = array_column($giftArr1,"id");
                $res1 = Db::name('egg_gift')->where(["id"=>["in",$giftids]])->update(["is_use"=>1]);
                if($res1 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }

                // 更新奖池
                $res2 = Db::name('egg_jackpot')->where(["id"=>$jackpot_id])->update(["status"=>-1]);
                if($res2 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }
                // 更新新奖池
                $res3 = Db::name('egg_jackpot')->where(["id"=>$next_jackpot_id])->update(["status"=>1,'starttime'=>$nowtime]);//打开,启用时间
                if($res3 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }

                // 下个奖池所有礼物改为未使用
                $res4 = Db::name('egg_gift')->where(["Jackpot_id"=>$next_jackpot_id])->update(["is_use"=>0,'starttime'=>$nowtime]);//重置礼物,启用时间
                if($res4 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }

                $nextjackpotGift = Db::name('egg_gift')->where(["Jackpot_id"=>$next_jackpot_id])->select();

                $newnum = $num-$giftCount;

                if($newnum == 0) {


                    $giftdata = $giftArr1;
                } else {
                    if($newnum > count($nextjackpotGift)){ //需要开启下下个奖池
                        Db::rollback();
                        $this->error("奖池礼物待更新,请耐心等待!");
                    }

                    $giftArr = [];
                    foreach($nextjackpotGift as $k => $v) $giftArr[$v["id"]] = $v;

                    if(!$giftArr){
                        Db::rollback();
                        $this->error("奖池礼物待更新,请耐心等待!");
                    }

                    $giftids = array_rand($giftArr,$newnum);

                    // 更新礼物抽取状态
                    $res5Info = Db::name('egg_gift')->where(["id"=>["in",$giftids]])->select();

                    $res5 = Db::name('egg_gift')->where(["id"=>["in",$giftids]])->update(["is_use"=>1]);
                    if($res5 === false){
                        Db::rollback();
                        $this->error('开奖失败');
                    }

                    $giftdata = array_merge($giftArr1,$res5Info);
                }

                //产出统计,在这里记录奖池产出统计,老一轮的奖池已经消耗完毕
                $jockpot_finish = 1;

            } else {
                // 随机抽取$num个礼物
                $giftArr = [];
                foreach($jackpotGift as $k => $v) $giftArr[$v["id"]] = $v;
                $giftids = array_rand($giftArr,$num);

                // 更新礼物抽取状态
                $res1 = Db::name('egg_gift')->where(["id"=>["in",$giftids]])->update(["is_use"=>1]);
                if($res1 === false){
                    Db::rollback();
                    $this->error('开奖失败');
                }
                $res1Info = Db::name('egg_gift')->where(["id"=>["in",$giftids]])->select();



                $giftdata = $res1Info;
            }

            if(empty($giftdata)) {
                Db::rollback();
                $this->error('礼物为空');
            }

            $data = [];
            foreach($giftdata as $k => $v) {
                // 保存砸蛋记录
                $data[] = [
                    "do_no" => $do_no,
                    "pay_fee" => $k == 0 ? $total_jewel : 0,
                    "party_id" => $party_id,
                    "user_id" => $user_id,
                    "gift_id" => $v["gift_id"],
                    "egg_gift_id" => $v["id"],
                    "image" => $v["image"],
                    "special" => $v["special"],
                    "gift_name" => $v["gift_name"],
                    "Jackpot_id" => $v["Jackpot_id"],
//                    "prize_no" => $v["prize_no"],
                    "starttime" => $v["starttime"],
                    "price" => $v["price"],
                    "createtime" => time(),
                ];
                // 添加用户背包
                $backdata[] = [
                    "user_id" => $user_id,
                    'gift_id' => $v["gift_id"],
                    "name" => $v["gift_name"],
                    "image" => $v["image"],
                    "gif_image" => $v["special"],
                    "value" => $v["price"],
                    "number" => 1,
                    "is_use" => 0,
                    "get_way" => 1,
                    "createtime" => time(),
                ];
            }
            $res6 = Db::name('egg_do')->insertAll($data);
            if($res6 === false){
                Db::rollback();
                $this->error('开奖失败');
            }

            // 添加到用户背包
            $res7 = Db::name('gift_back')->insertAll($backdata);
            if($res7 === false){
                Db::rollback();
                $this->error('开奖失败');
            }


            //扣钻石
            $rs_wallet = model('wallet')->lockChangeAccountRemain($user_id,$total_jewel,'-',0,'开箱子和大转盘',13,'jewel');
            if($rs_wallet['status'] === false){
                Db::rollback();
                $this->error($rs_wallet['msg']);
            }

            //每一期奖池的产出统计
            if($jockpot_finish == 1){
                $jackpot_chanchu = [
                    //奖池的
                    'jp_giftnum'   => Db::name('egg_gift')->where('Jackpot_id',$jackpot_id)->count(), //总礼物数量
                    'jp_giftprice' => Db::name('egg_gift')->where('Jackpot_id',$jackpot_id)->sum('price'), //总礼物价值
                    //抽奖的
                    'do_payfee'    => Db::name('egg_do')->where('Jackpot_id',$jackpot_id)->where('starttime',$jackpot['starttime'])->sum('pay_fee'), //物抽总礼奖费用
                    'do_usercount' => Db::name('egg_do')->where('Jackpot_id',$jackpot_id)->where('starttime',$jackpot['starttime'])->group('user_id')->count('id'),//抽奖总人数
                    'do_usertimes' => Db::name('egg_do')->where('Jackpot_id',$jackpot_id)->where('starttime',$jackpot['starttime'])->group('do_no')->count('id'),//抽奖总次数
                    'do_giftnum'   => Db::name('egg_do')->where('Jackpot_id',$jackpot_id)->where('starttime',$jackpot['starttime'])->count('id'),//抽奖总礼物数量
                    'do_giftprice' => Db::name('egg_do')->where('Jackpot_id',$jackpot_id)->where('starttime',$jackpot['starttime'])->sum('price'),//抽奖总礼物价值

                    //基础信息
                    'jackpot_id' => $jackpot_id,
                    'starttime'  => $jackpot['starttime'],
                    'createtime' => time(),
                ];
                //产出比
                $jackpot_chanchu['chanchubi'] = bcdiv($jackpot_chanchu['do_giftprice'],$jackpot_chanchu['jp_giftprice'],2);
                $rs_chanchu = Db::name('egg_jackpot_chanchu')->insertGetId($jackpot_chanchu);
                if(!$rs_chanchu){
                    Db::rollback();
                    $this->error('开奖失败');
                }
            }

            Db::commit();


        // 返回抽到的礼物列表
        $result = [
            'list' => [],
            'bigshow' => [],
            'sumvalue' => Db::name('egg_do')->where('do_no',$do_no)->sum('price'),
        ];

        $list = Db::name('egg_do')->alias('do')->join('gift','do.gift_id = gift.id','LEFT')->field('do.gift_id,do.gift_name,do.image,do.special,do.price,count(do.id) as number,gift.is_big')->where('do.do_no',$do_no)->order('gift.is_big desc,gift.value desc')->group('do.gift_id')->select();
        $list = list_domain_image($list,['image','special']);
        $result['list'] = $list;
        //只弹一个大礼物,专门拿出结构
        if(!empty($list)){
            if($list[0]['is_big'] == 1){
                $result['bigshow'] = $list[0];
            }
        }
        $this->success("获取成功!",$result);
    }

    //手气榜单
    public function getRankList(){
        $type = $this->request->request("type",1);

        $today = strtotime(date("Y-m-d"));
        $where = [];
        $where["a.createtime"] = ["gt",$today];
        $where["jp.type"] = $type;

        $ranklist = \app\common\model\EggDo::alias("a")->field("a.user_id,a.image,a.price as money,a.createtime,u.nickname")
            ->join("hx_user u","u.id = a.user_id","left")
            ->join("egg_jackpot jp","a.Jackpot_id = jp.id","left")
            ->where($where)
//            ->group("a.user_id")
            ->order("money","desc")
            ->limit(20)
            ->select();
        $this->success("获取成功!",$ranklist);
    }

    /**
     * 获取排行榜
     */
    public function getRankList_old() {
        $time = $this->request->request("time"); // 1=今天,2=昨天
        if(!in_array($time,[1,2])) {
            $this->error("参数缺失!");
        }
        // 先根据用户抽奖总值排序 筛选
        $today = strtotime(date("Y-m-d 00:00:00"));
        $yestoday = $today - 86400;
        $where = [];
        $time == 1 && $where["a.createtime"] = ["gt",$today];
        $time == 2 && $where["a.createtime"] = ["between","$yestoday,$today"];
        $ranklist = \app\common\model\EggDo::alias("a")->field("a.user_id,sum(a.price) as money,u.avatar,u.nickname")
            ->join("hx_user u","u.id = a.user_id","inner")
            ->where($where)
            ->group("a.user_id")
            ->order("money","desc")
            ->limit(20)
            ->select();
        if(!$ranklist) $this->success("获取成功!",[]);

        foreach($ranklist as $k => $v) {
            // 查询
            $where["user_id"] = $v["user_id"];
            $ranklist[$k]["gifts"] = \app\common\model\EggDo::alias("a")
                ->field("image,count(id) as number,sum(a.price) as money")
                ->limit(3)
                ->where($where)
                ->group("gift_id")
                ->order("money","desc")
                ->select();
        }

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

    /**
     * 获取砸蛋基本信息
     */
    public function getBaseInfo() {
        $type = input('type',1);

        // 构建数据
        $data = [];
        $data["jewel"] = $this->auth->jewel;
        $data["playdetail"] = config("site.playdetail");

        $data['pay_config'] = Db::name('egg_timesprice')->field('times,price')->where('type',$type)->order('times asc')->select();
        $this->success("获取成功!",$data);
    }
}