<?php

/**
 * 活动配置相关
 */
defined('IN_WEB') or die('Include Error!');
include_once dirname(__FILE__) . "/Base.php";
class Activitycfg extends Base
{
    private $_config = [];
    private $_max_id = 0;

    function __construct()
    {
        if(file_exists(COM_CFG."config.activity2.php")) {
            $this->_config = include COM_CFG."config.activity2.php";
            $this->_max_id = $max_id ?? 0;
        }
    }

    /**
     * 获取活动配置列表
     */
    public function index($param)
    {
        $actTitleList = oo::commonOprModel('activity')->getActivityTitleList();
        $actBnameList = oo::commonOprModel('activity')->getActivityBnameList();
        $actImgList = oo::commonOprModel('activity')->getActivityImgList();
        $configList = [];
        if(!empty($this->_config) && !empty($actTitleList)) {
            $configList = $this->_config;
            foreach ($configList as $k => &$_v) {//活动列表
                $title = $_v['title'];
                foreach ($actTitleList as $ka => $_va) {//标题语言类别
                    $_v['title_name_'.$ka] = $_va[$title] ?? '';
                }
                //按钮
                $btn = $_v['bname'];
                foreach ($actBnameList as $kb => $_vb) {//按钮语言类别
                    $_v['bname_'.$kb] = $_vb[$btn] ?? '';
                }
                //图片
                $img = $_v['img'];
                foreach ($actImgList as $ki => $_vi) {//活动图片
                    $_v['img_'.$ki] = $_vi[$img] ?? '';
                }

                //活动状态
                $online = $_v['online'];
                $stime = strtotime($_v['stime']);
                $etime = strtotime($_v['etime']);
                $now = time();
                if ($now < $stime || $now > $etime || $online != 1) {
                    $_v['status'] = 0;
                } else {
                    $_v['status'] = 1;
                }
            }
        }
        $list['max_id'] = $this->_max_id;
        $list['configList'] = $this->sortArrByManyField($configList,'status', SORT_DESC,'sort', SORT_ASC);//倒序输出
        $list['showActivity'] =0;//oo::commonOprModel('activity')->isShowActivity();//登录时是否显示活动弹窗
        $id = oo::functions()->uint($param['id']);
        $key = okeys::activityonlinepackage($id);
        $list['packageList'] = oo::commonOprRedis('common')->get($key);
        $list['blindListConfig'] = [];

        die(json_encode($list));
    }

    /**
     * 獲取盲注
     */
    public function getGameLevel()
    {
        $list = [];
        die(json_encode($list));
    }

    /**
     * 新增操作
     * @param $param
     */
    public function addAction($param)
    {
        $id = oo::functions()->uint($param['id']);
        $titleList = json_decode($param['titleList'], 1);
        $bnameList = json_decode($param['bnameList'], 1);
        $actType = oo::functions()->uint($param['actType']);
        $bcolor = oo::functions()->uint($param['bcolor']);
        $goto = oo::functions()->uint($param['goto']);
        $online = oo::functions()->uint($param['online']);
        $sort = oo::functions()->uint($param['sort']);
        $reward = json_decode($param['reward'], 1);
        $level = oo::functions()->uint($param['level']);
        $goodsType = oo::functions()->uint($param['goodsType']);
        $payType = oo::functions()->uint($param['payType']);
        $packageList = $param['packageList'];//该或者在这些包上线
//        $img = $param['img'];
        $imgList = json_decode($param['imgList'], 1);
        $stime = $param['stime'];
        $etime = $param['etime'];

        $isChooseDateHour = oo::functions()->uint($param['isChooseDateHour']);//选择了玩牌活动按时间段
        $stimeHour = $param['stimeHour'];//玩牌每天的时间段
        $etimeHour = $param['etimeHour'];
        $blindList = json_decode($param['blindList'], 1);//所选盲注

        if(empty($reward) || !is_array($reward)) {
            $reward = [];
        }
        if(empty($stime) || empty($etime)) {
            die($this->response(2, '活动时间不能为空'));
        }
//        if(empty($img)) {
//            die($this->response(3, '活动图片不能为空'));
//        }

        //设置标题
        $bnameKey = 'activity_bname_'.$id;
        $titleKey = 'activity_title_'.$id;
        $imgKey = 'activity_img_'.$id;
        $res = $this->setActivityTitle($titleList, $titleKey);
        if($res['ret'] !== 0) {
            die(json_encode($res));
        }

        //设置获得图片
        $resImg = $this->setActivityImg($imgList, $imgKey);
        if($resImg['ret'] != 0) {
            die(json_encode($resImg));
        }

        //设置按钮
        if($actType == 1) {
            $res2 = $this->setActivityBname($bnameList, $bnameKey);
            if($res2['ret'] !== 0) {
                die(json_encode($res2));
            }
        }

        //设置活动配置文件
        $config = array(
            'id' => $id,
            'title' => $titleKey,
            'content' => '',
            'bcolor' => $bcolor,//按钮颜色
            'bname' => $bnameKey,//按钮名称
            'goto' => $goto,
            'stime' => $stime,
            'etime' => $etime,
            'isChooseDateHour' => $isChooseDateHour,
            'stimeHour' => $stimeHour,
            'etimeHour' => $etimeHour,
            'blindList' => $blindList,
            'online' => $online,
            'sort' => $sort,
            'img'  => $imgKey,
            "reward" => $reward,
//            'bigwheel' => array(30 => 1),//每玩30局, 奖励一次免费机会
            'actType' => $actType,
        );
        //如果goto类型是5，则设置指定场次level
        if($goto == 5) {
            $config['level'] = $level;
        }
        //如果goto类型是12,则设置goodsType和payType
        if($goto == 12) {
            $config['goodsType'] = $goodsType;
            $config['payType'] = $payType;
        }

        $res = oo::commonOprModel('activity')->setActivityConfig($config, 1);//进行写入配置文件
        if($res) {
            //设置哪些包上线该活动
            if(!empty(json_decode($packageList, 1))) {
                $packageKey = okeys::activityonlinepackage($id);
                oo::commonOprRedis('common')->set($packageKey, $packageList);
            }

            die($this->response(0, '活动新增成功'));
        }
        die($this->response(4, '活动新增失败'));

    }

    /**
     * 设置活动标题
     * @param $titleList
     * @param $titleKey
     * @return array
     */
    public function setActivityTitle($titleList, $titleKey)
    {
        //设置标题
        if(!empty($titleList)) {
            $titleConfig = [];
            foreach ($titleList as $kt => $title) {
//                if(empty($title)) {
//                    return $this->res(1, '活动标题不能为空');
//                }
                $titleConfig[$kt] = [
                    $titleKey => $title
                ];
            }
            $response = oo::commonOprModel('activity')->setActivityTitle($titleConfig);
            if(!$response) {
                return $this->res(2, '活动标题设置失败');
            }
            return $this->res(0, '活动标题设置成功');
        }else {
            return $this->res(3, '活动标题不能为空');
        }
    }


    /**
     * 设置活动标题
     * @param $titleList
     * @param $titleKey
     * @return array
     */
    public function setActivityImg($imgList, $imgKey)
    {
        //设置标题
        if(!empty($imgList)) {
            $imgConfig = [];
            foreach ($imgList as $kt => $img) {
                $imgConfig[$kt] = [
                    $imgKey => $img
                ];
            }
            $response = oo::commonOprModel('activity')->setActivityImg($imgConfig);
            if(!$response) {
                return $this->res(2, '活动图片设置失败');
            }
            return $this->res(0, '活动图片设置成功');
        }else {
            return $this->res(3, '活动图片不能为空');
        }
    }



    /**
     * 返回数据
     * @param int $ret
     * @param string $msg
     * @return array
     */
    private  function res($ret = 0, $msg = '')
    {
        $result = [
            'ret'  => $ret,
            'msg'  => $msg
        ];

        return $result;
    }


    /**
     * 设置活动按钮
     * @param $bnameList
     * @param $bnameKey
     * @return array
     */
    public function setActivityBname($bnameList, $bnameKey)
    {
        //设置活动按钮
        if(!empty($bnameList)) {
            $bnameConfig = [];
            foreach ($bnameList as $kb => $bname) {
//                if(empty($bname)) {
//                    return $this->res(1, '活动按钮名称不能为空');
//                }
                $bnameConfig[$kb] = [
                    $bnameKey => $bname
                ];
            }
            $response = oo::commonOprModel('activity')->setActivityBname($bnameConfig);
            if(!$response) {
                return $this->res(2, '活动按钮名称设置失败');
            }
            return $this->res(0, '活动按钮名称设置成功');
        }else {
            return $this->res(3, '活动按钮名称不能为空');
        }
    }

    /**
     * 编辑操作
     * @param $param
     */
    public function editAction($param)
    {
        $id = oo::functions()->uint($param['id']);
        $titleList = json_decode($param['titleList'], 1);
        $bnameList = json_decode($param['bnameList'], 1);
        $actType = oo::functions()->uint($param['actType']);
        $bcolor = oo::functions()->uint($param['bcolor']);
        $goto = oo::functions()->uint($param['goto']);
        $online = oo::functions()->uint($param['online']);
        $sort = oo::functions()->uint($param['sort']);
        $reward = json_decode($param['reward'], 1);
        $level = oo::functions()->uint($param['level']);
        $goodsType = oo::functions()->uint($param['goodsType']);
        $payType = oo::functions()->uint($param['payType']);
        $packageList = $param['packageList'];
        $isChooseDateHour = oo::functions()->uint($param['isChooseDateHour']);//选择了玩牌活动按时间段
        $stimeHour = $param['stimeHour'];//玩牌每天的时间段
        $etimeHour = $param['etimeHour'];

        $blindList = json_decode($param['blindList'], 1);//所选盲注
        $imgList = json_decode($param['imgList'], 1);
//        $img = $param['img'];
        $stime = $param['stime'];
        $etime = $param['etime'];
        if(empty($reward) || !is_array($reward)) {
            $reward = [];
        }
        if(empty($stime) || empty($etime)) {
            die($this->response(2, '活动时间不能为空'));
        }
//        if(empty($img)) {
//            die($this->response(3, '活动图片不能为空'));
//        }

        //设置标题和按钮
        $bnameKey = 'activity_bname_'.$id;
        $titleKey = 'activity_title_'.$id;
        $imgKey = 'activity_img_'.$id;
        $res = $this->setActivityTitle($titleList, $titleKey);
        if($res['ret'] !== 0) {
            die(json_encode($res));
        }

        //设置获得图片
        $resImg = $this->setActivityImg($imgList, $imgKey);
        if($resImg['ret'] != 0) {
            die(json_encode($resImg));
        }

        if($actType == 1) {
            $res2 = $this->setActivityBname($bnameList, $bnameKey);
            if($res2['ret'] !== 0) {
                die(json_encode($res2));
            }
        }


        //设置活动配置文件
        $config = array(
            'id' => $id,
            'title' => $titleKey,
            'content' => '',
            'bcolor' => $bcolor,//按钮颜色
            'bname' => $bnameKey,//按钮名称key
            'goto' => $goto,
            'stime' => $stime,
            'etime' => $etime,
            'isChooseDateHour' => $isChooseDateHour,
            'stimeHour' => $stimeHour,
            'etimeHour' => $etimeHour,
            'blindList' => $blindList,
            'online' => $online,
            'sort' => $sort,
            'img'  => $imgKey,
            "reward" => $reward,
//            'bigwheel' => array(30 => 1),//每玩30局, 奖励一次免费机会
            'actType' => $actType,
        );
        //如果goto类型是5，则设置指定场次level
        if($goto == 5) {
            $config['level'] = $level;
        }
        //如果goto类型是12,则设置goodsType和payType
        if($goto == 12) {
            $config['goodsType'] = $goodsType;
            $config['payType'] = $payType;
        }

        $res = oo::commonOprModel('activity')->setActivityConfig($config, 2);//进行编辑写入配置文件
        if($res) {
            //设置哪些包上线该活动
            $packageKey = okeys::activityonlinepackage($id);
            oo::commonOprRedis('common')->set($packageKey, $packageList);
            die($this->response(0, '活动编辑成功'));
        }
        die($this->response(4, '活动编辑失败'));

    }

    /**
     * 设置登录时是否弹出活动弹窗
     * @param $param
     */
    public function showActivity($param)
    {
//        oo::logs()->debug3('param111:'.json_encode($param), 'Activity.php');
        $showActivity = oo::functions()->uint($param['showActivity']);
        $keys = okeys::showactivity();

//        if($showActivity > 0) {
//            $data = oo::commonOprModel('activity')->getList([]);
//            oo::logs()->debug3('data:'.json_encode($data));
//            $list = $data['list'] ?? [];
//            if(empty($list)) {
//                die($this->response(1, '活动列表为空，设置登录弹出获得弹窗失败'));
//            }
//        }
        $re = oo::commonOprRedis('common')->set($keys, $showActivity);
        if($re) {
            die($this->response(0, '设置成功'));
        }
        die($this->response(1, '设置失败'));
    }

    public function getActivity($param){
        $tb = otable::activity();
        if(isset($param['id'])){
            $sql = "SELECT * FROM {$tb} WHERE id={$param['id']}";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $ret['pro'] = oo::commonOprRedis('common')->get(okeys::ActivityPro($param['id']));
        }else{
            $sql = "SELECT * FROM {$tb} WHERE 1";
            $ret = oo::commonOprDb('common')->getAll($sql,1);
        }
        return json_encode($ret,JSON_NUMERIC_CHECK);
    }

    public function saveActivity($param){
        $id = intval($param['id']);
        $tb = otable::activity();
        $updateKey = ['name', 'name_en', 'package', 'start_time', 'end_time', 'sort', 'is_online', 'actType', 'bname', 'bname_en', 'bcolor', 'openlv'];
        foreach ($updateKey as $row){
            $updateInfo[$row] = $param[$row];
        }
        $updateInfo['status'] = $param['is_online'];
        $image = array_filter(json_decode($param['image'],true));
        if(!empty($image)){
            $updateInfo['image'] = $param['image'];
        }

        if(in_array($param['id'],[2,3,6,7,13,14,15,16])){
            $sql = "SELECT imgName,textColor FROM {$tb} WHERE id={$id}";
            $ret = oo::commonOprDb('common')->getOne($sql,1);
            $imgName   = json_decode($ret['imgName'],true);
            $textColor = json_decode($ret['textColor'],true);
            $imgName[$param['img']]   = $param['imgName'];
            $textColor[$param['img']] = explode(',',$param['textColor']);
            $imgName   = json_encode($imgName);
            $textColor = json_encode($textColor);
            $updateInfo['img']         = $param['img'];
            $updateInfo['imgName']     = $imgName;
            $updateInfo['action_time'] = $param['action_time'];
            $updateInfo['lock_time']   = $param['lock_time'];
            $updateInfo['reward_time'] = $param['reward_time'];
            $updateInfo['textColor']   = $textColor;
        }
        oo::commonOprRedis('common')->set(okeys::ActivityPro($id),$param['pro']);
        $set = "";
        foreach ($updateInfo as $key=>$value){
            $set .= "`$key`='$value',";
        }
        $set = trim($set,',');
        if(!empty($set) && oo::commonOprDb('common')->query("UPDATE {$tb} SET {$set} WHERE id = {$id} LIMIT 1")){
            $onLine  = oo::commonOprModel('activity')->isOnLine($id);
            if($param['is_online']){
                $cacheKey= ['name','name_en','package','sort','actType','bname','bname_en','activityType','openlv','start_time','end_time'];
                foreach ($cacheKey as $row){
                    if($row == "activityType"){
                        $temp[$row] = $updateInfo['img'];
                    }else{
                        $temp[$row] = $updateInfo[$row];
                    }
                }
                if(in_array($id,[2,3,6,7,13,14,15,16])){
                    $temp['activityName'] = $param['imgName'];
                    $temp['reward_time']  = $param['reward_time'];
                }
                if(in_array($id,[2,3,6])){ // 循环启动类活动
                    $time = time();
                    if($param['action_time'] > 0){
                        if($time > $param['start_time']){
                            $end_time = $param['action_time']*60*60 + $time;
                        }else{
                            $end_time = $param['action_time']*60*60 + $param['start_time'];
                        }
                        $end_time = min($end_time,$param['end_time']);
                    }else{
                        $end_time = $param['end_time'];
                    }

                    $end_time = min($end_time,$param['end_time']);

                    oo::commonOprRedis('common')->hSet(okeys::Activity(),$id."#".$param['start_time']."#".$end_time."#".$param['openlv'],json_encode($temp));
                    $temp['start_time'] =  $param['start_time'];
                    $temp['end_time']   =  $param['end_time'];
                    $temp['openlv']     =  $param['openlv'];
                    $temp['last_time']  =  $end_time;
                    $temp['action_time']=  $param['action_time'];
                    $temp['lock_time']  =  $param['lock_time'];
                }else{
                    oo::commonOprRedis('common')->hSet(okeys::Activity(),$id."#".$param['start_time']."#".$param['end_time']."#".$param['openlv'],json_encode($temp));
                }
                oo::commonOprRedis('common')->hSet(okeys::ActivityData(),$id,json_encode($temp));
                !$onLine && oo::commonOprModel('activity')->refreshActivity($id);
            }else{
                oo::commonOprModel('activity')->outLine($id);
                $onLine && oo::commonOprModel('activity')->activityChangeStatus(['actId'=>$id,'status'=>0,'startTime'=>0]);
            }
            return 1;
        }
        return 0;
    }


    public function getLevel($param){
        $type = intval($param['type']);
        if($type == 1){
            $tb = otable::activityLevel();
        }else if($type == 2){
            $tb = otable::payLevel();
        }
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $ret = oo::commonOprDb('common')->getAll($sql,MYSQLI_ASSOC);
        return json_encode($ret);
    }

    public function saveLevel($param){
        $type = intval($param['type']);

        if($type == 1){
            $tb = otable::activityLevel();
        }else if($type == 2){
            $tb = otable::payLevel();
        }

        $data = json_decode($param['data'],true);
        foreach ($data as $row){
            $sql = "REPLACE INTO {$tb} (`id`, `level`, `num`, `mean`) VALUES ({$row['id']}, {$row['level']}, '{$row['num']}', '{$row['mean']}')";
            $ret = oo::commonOprDb('common')->query($sql);
        }
        return $ret?$ret:0;
    }
  
  	/**
     * 刷新活动
     * @param $param
     * @return int
     * Created by: Owen
     * Created on: 2019/9/30 17:55
     */
    public function refreshActivity($param){
        $id = intval($param['id']);
        oo::commonOprModel('activity')->refreshActivity($id);
        return 1;
    }
  
  	public function activitySta($param){
        $id   = intval($param['id']);
        $start = ($param['page'] -1)*10;
        $length = $param['page_size'];
        $tb  = otable::activitySta();
        $sql = "SELECT * from {$tb} WHERE activtityId={$id} ORDER BY time DESC LIMIT {$start},{$length} ";
        $rs = oo::commonOprDb('statistics')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[] = $v['time'];
        }
        $sql = "SELECT COUNT(*) as num from {$tb} WHERE activtityId={$id}";
        $num = oo::commonOprDb('statistics')->getOne($sql,1);
        if(isset($param['time'])){
            $sql = "SELECT data from {$tb} WHERE activtityId={$id} AND time='{$param['time']}'";
            $ret = oo::commonOprDb('statistics')->getOne($sql,1);
            $data = json_decode($ret['data'],true);
        }else{
            if($id == 2){
                $tb = otable::Symbol();
                $sql = "SELECT uid,stage FROM {$tb} WHERE stage != 1 AND stage != 0";
                $ret = oo::commonOprDb('activity')->getAll($sql,MYSQLI_ASSOC);
                $activtity = [];
                foreach ($ret as $row){
                    $activtity[$row['uid']] = $row['stage'];
                }
                $data = $activtity;
            }else if($id == 3){
                $data = oo::commonOprRedis('common')->hGetAll(okeys::BalloonCount());
            }else if($id == 6){
	            //偷打活动统计
	            $data = [];
	            $keys = oo::commonOprRedis('common')->hGetAll(okeys::StealAttackNum());
	            foreach ($keys as $uid=>$row){
	                $data[$uid] = $row;
	            }
            }else if($id == 13){
            	//排行榜活动统计
                $roomId   = oo::commonOprModel('activity')->getRankCurMaxRoomId();
                $activity = ['number'=>[],'rank'=>[],'progress'=>[]];//排行榜活动统计
	            $data = [];
                for ($i=1;$i<=$roomId;$i++){
	                $result = oo::commonOprRedis('common')->zRange(okeys::ActivityRank($i),0,-1,true);
	                foreach ($result as $uid => $num){
                        $data['number'][$uid] = $num;
                        $data['rank'][$i][$uid] = oo::commonOprModel('activity')->getCurUserRank($uid);
                        $data['progress'][$uid] = oo::commonOprModel('activity')->getRankProgressId($uid);
	                }
	            }
            }
        }
        if($id == 2 || $id==6){
        	if($id==2){
        		$tb = otable::SymbolConfig();
        	}else if($id==6){
        		$tb  = otable::StealAttackConfig(2);
        	}
            
            $sql = "SELECT MAX(stage) as stage from {$tb} LIMIT 1";
            $rs = oo::commonOprDb('config')->getOne($sql,MYSQLI_ASSOC);
            for ($i=1;$i<=$rs['stage'];$i++){
                $Interval[] = $i;
            }
        }else if($id==3 || $id==13){
            $Interval = [1, 5, 10, 40, 80, 110, 180, 260, 360, 500, 1000, 2000, 3000];
        }
        
        $returnData = [
            'total'=>$num['num'],
            'list'=>$arr,
            'data'=>$data,
            'interval'=>$Interval,
        ];
        return json_encode($returnData);
    }


    public function clearBuyNum($param){
        $id   = intval($param['id']);
        if($id == 7){
            oo::commonOprRedis('User')->delete(okeys::GoodBuyNum());
        }
        return 1;
    }

    public function config($param){
        $id   = intval($param['id']);
        $data = [];
        if($id == 6){
            $tb  = otable::StealAttackConfig(2);
            $sql = "SELECT * FROM {$tb} WHERE 1 ";
            $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            $data['reward'] = $ret;
        }

        if($id == 7){
            $tb  = otable::HolidayCollectConfig();
            $sql = "SELECT * FROM {$tb} WHERE 1 ";
            $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            $data['reward'] = $ret;
            $data['title'] = oo::commonOprModel('readconfig')->getSysCon('activtity7',"title");
            $data['titleCard'] = oo::commonOprModel('readconfig')->getSysCon('activtity7',"titleCard");
        }

        if($id == 8){
            $tb  = otable::BuildMasterConfig();
            $sql = "SELECT * FROM {$tb} WHERE 1 ";
            $ret = oo::commonOprDb('config')->getAll($sql,MYSQLI_ASSOC);
            $data['reward'] = $ret;
        }

        if($id == 13){
            return json_encode([
                'model'      => oo::commonOprModel('readconfig')->getSysCon('activtity13',"model"),
                'rankConfig' => oo::commonOprModel('config')->getActivityRankConfig(),
                'rankProgressConfig' => oo::commonOprModel('config')->getActivityRankProgressConfig(0,'1.6.1',0,false),
            ]);
        }

        if($id == 14){
            return json_encode([
                'speedUp' => oo::commonOprModel('config')->getSpeedUpSpins(),
            ]);
        }

        return json_encode($data);
    }

    public function saveConfig($param){
        $id   = intval($param['id']);
        if($id == 6){
            $tb  = otable::StealAttackConfig(2);
            $data = json_decode($param['data'],true);
            foreach ($data as $row){
                $sql = "UPDATE {$tb} SET max='{$row['max']}',type='{$row['type']}',num='{$row['num']}' WHERE stage='{$row['stage']}'";
                oo::commonOprDb('common')->query($sql);
            }
            oo::commonOprRedis('common')->delete(okeys::StealAttackConfig(2));
//            if(!empty($param['filename'])){
//                $filename = $param['filename'];
//                $tb = otable::StaticConfig();
//                $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='StealAttack'";
//                oo::commonOprDb('common')->query($sql);
//                oo::commonOprRedis('common')->hSet(okeys::StaticConfig(),'StealAttack',$filename);
//            }
        }
        if($id == 7){
            $tb  = otable::HolidayCollectConfig();
            $data = json_decode($param['data'],true);
            foreach ($data['reward'] as $row){
                $chest = json_encode($row['chest']);
                $sql = "UPDATE {$tb} SET max='{$row['max']}',money='{$row['money']}',spins='{$row['spins']}',chest='{$chest}' WHERE stage= '{$row['stage']}'";
                oo::commonOprDb('common')->query($sql);
            }
            oo::commonOprModel('readconfig')->setSysCon('activtity7',"title",json_encode($data['title'],JSON_UNESCAPED_UNICODE));
            oo::commonOprModel('readconfig')->setSysCon('activtity7',"titleCard",json_encode($data['titleCard'],JSON_UNESCAPED_UNICODE));
            if(!empty($param['filename'])){
                $filename = $param['filename'];
                $tb = otable::StaticConfig();
                $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='HolidayCollect'";
                oo::commonOprDb('common')->query($sql);
                oo::commonOprRedis('common')->hSet(okeys::StaticConfig(),'HolidayCollect',$filename);
            }
        }

        if($id == 8){
            $tb  = otable::BuildMasterConfig();
            $data = json_decode($param['data'],true);
            foreach ($data as $row){
                $sql = "UPDATE {$tb} SET money='{$row['money']}',spins='{$row['spins']}',chest='{$row['chest']}',exp='{$row['exp']}' WHERE levelId='{$row['levelId']}'";
                oo::commonOprDb('common')->query($sql);
            }
            $filename = "BuildMasterConfig".time().".json";
            $tb = otable::StaticConfig();
            $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='BuildMaster'";
            oo::commonOprDb('common')->query($sql);
            oo::commonOprRedis('common')->hSet(okeys::StaticConfig(),'BuildMaster',$filename);
            foreach ($data as $row){
                $coins =  oo::commonOprModel('goods')->getGoodCoinsByLevelId($row['levelId'],$row['money']);
                $chest = json_decode($row['chest'],true);
                $chest['type'] = 3;
                $temp =[
                    'levelId'=> $row['levelId'],
                    'reward' => [
                        [
                            'type'=>1,
                            'num' =>$coins/2,
                        ],[
                            'type'=>2,
                            'num' =>$row['spins'],
                        ],$chest,
                    ]
                ];
                $json[] = $temp;
            }
            return json_encode([
                'filename'=>$filename,
                'json'    =>$json,
            ]);
        }

        if($id == 13){
            $data = json_decode($param['data'],true);
            if($param['type'] == 'rank'){
                $configName ="ActivityRankConfig";
                $ret = oo::commonOprModel('config')->setActivityRankConfig($data);
            }else if($param['type'] == 'progress'){
                $configName ="ActivityRankProgressConfig";
                $ret = oo::commonOprModel('config')->setActivityRankProgressConfig($data);
                $ret = false;
            }
            if($ret){
                $filename = $param['filename'];
                $tb = otable::StaticConfig();
                $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='{$configName}'";
                oo::commonOprDb('common')->query($sql);
                oo::commonOprRedis('common')->hSet(okeys::StaticConfig(),$configName,$filename);
            }
        }

        if($id == 14){
            $data = json_decode($param['data'],true);
            oo::commonOprModel('config')->setSpeedUpSpins($data);
        }

        return 1;
    }

    public function setRankModel($param){
        return oo::commonOprModel('readconfig')->setSysCon('activtity13',"model",$param['model']);
    }


    public function setActSpinsLimit($param){
        if(!empty($param['filename'])){
            $filename = $param['filename'];
            $tb = otable::StaticConfig();
            $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='CrazyBetConfig'";
            oo::commonOprDb('common')->query($sql);
            oo::commonOprRedis('common')->hSet(okeys::StaticConfig(),'CrazyBetConfig',$filename);
        }
        return oo::commonOprModel('readconfig')->setSysCon('activtity14',"actSpinsLimit",$param['actSpinsLimit']);
    }

    /**
     * 获得收集物
     * @param $param
     * @return false|string
     * Created by: Owen
     * Created on: 2020/4/17 18:57
     */
    public function getCollection($param){
        $tb = otable::ActivityCollection();
        $ret= oo::commonOprDb('common')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $return = [];
        foreach ($ret as $row){
            $return[$row['activityId']][] = $row;
        }
        return json_encode($return);
    }

    /**
     * 保存收集物
     * @param $param
     * @return int
     * Created by: Owen
     * Created on: 2020/4/22 17:07
     */
    public function setCollection($param){
        $data = json_decode($param['data'],true);
        if(!empty($data)){
            $activityId = $data[0]['activityId'];
            $tb = otable::ActivityCollection();
            $collection = oo::commonOprDb('common')->getAll("SELECT * FROM {$tb} WHERE activityId={$activityId}",MYSQLI_ASSOC);
            $dbCollection = array_column($collection,'collectionId');
            $curCollection= array_column($data,'collectionId');
            $deleteArr = implode(',',array_diff($dbCollection,$curCollection));
            if(!empty($deleteArr)){
                oo::commonOprDb('common')->query("DELETE FROM {$tb} WHERE activityId={$activityId} AND collectionId IN ({$deleteArr})");
            }

            foreach ($data as $row){
                if(!in_array($row['collectionId'],$dbCollection)){
                    oo::commonOprDb('common')->query("INSERT INTO {$tb} VALUES({$activityId}, {$row['collectionId']}, '{$row['name']}', '{$row['path']}')");
                }
            }
        }
        return 1;
    }

    /**
     * 保存活动排期
     * @param $param
     * @return mixed
     * Created by: Owen
     * Created on: 2020/4/20 20:34
     */
    public function saveSchedule($param){
        $tb     = otable::ActivitySchedule();
        $insert = json_decode($param['data'],true);
        $keys   = implode(',',array_keys($insert));
        $value  = "'".implode("','",array_values($insert))."'";
        $ret    = oo::commonOprDb('common')->query("INSERT INTO {$tb} ({$keys}) VALUES({$value})");
        $scheduleId = oo::commonOprDb('common')->insertID();
        oo::commonOprRedis('common')->zAdd(okeys::ActivitySchedule(),time(),$scheduleId);
        return $ret;
    }
}
