<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 配置相关
 */
class Shop extends MY_Controller
{
    protected $pageNum = 25;//分页

	protected $pageConfig = array(
        'first_tag_open' => '<li>',
        'first_tag_close' => '</li>',
        'last_tag_open' => '<li>',
        'last_tag_close' => '</li>',
        'next_tag_open' => '<li>',
        'next_tag_close' => '</li>',
        'prev_tag_open' => '<li>',
        'prev_tag_close' => '</li>',
        'cur_tag_open' => "<li class='active'><a hef='#'>",
        'cur_tag_close' => "</a></li>",
        'num_tag_open' => "<li>",
        'num_tag_close' => "</li>",
    );

    public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    // 基礎配置
    private $title = [
        '1'=>['商品ID','商品SKU','名称','名称（英文）','描述','描述（英文）','原始奖励','真实奖励','配图','角标','价格','上架(1上架)'],
        '2'=>['商品ID','商品SKU','名称','名称（英文）','描述','描述（英文）','配图','角标','价格','上架(1上架)'],
//        '3'=>['商品ID','名称','名称（英文）','描述','描述（英文）','原始奖励(数量,星级,星级)','真实奖励(数量,星级,星级)','配图','上架(1上架)'],
        '3'=>['商品ID','名称','名称（英文）','描述','描述（英文）','配图','上架(1上架)'],
        '5'=>['商品ID','商品SKU','名称','名称（英文）','描述','描述（英文）','原始奖励','真实奖励','配图','价格','上架(1上架)'],
        '6'=>['商品ID','商品SKU','名称','名称（英文）','描述','描述（英文）','原始(体力,coin3)','真实(体力,coin3)','配图','价格','上架(1上架)'],
        '23'=>['商品ID','价格','sku','折扣'],
    ];

    private $level_title = ['等级ID','coin01','coin02','coin03','coin04','coin05','coin06',];
    private $chest_title = ['等级ID','木质宝箱','白银宝箱','黄金宝箱', '高级黄金宝箱'];
    private $url = "";

    public function __construct()
    {
        date_default_timezone_set("Asia/Shanghai");
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->library('curl');
		$this->load->library('pagination');
        $this->env = get_cookie($this->_wenenv);
        $this->url = $this->config->item('officialUrl');
        
    }

    public function recommend(){
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'getRecommend';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $data['list'] = $retData;
        $this->load->view('shop/recommend', $data);
    }

    public function actionRecommend(){
        $input = $this->input->post();
        $data = [];
        foreach ($input['id'] as $key=>$row){
            $data[] = [
                "id"=>$input['id'][$key],
                "name"=>$input['name'][$key],
                "sort"=>$input['sort'][$key],
                "open"=>$input['open'][$key],
            ];
        }
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'saveRecommend';
        $posts['data'] = json_encode($data,JSON_NUMERIC_CHECK);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        
        oo::logs()->adminlog($this->router->fetch_method());
        
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }


    public function config($type){
        $title = $this->title[$type];
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'config';
        $posts['type'] = $type;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $temp = $retData['data'];
        foreach ($temp as $key=>$row){
            if(in_array($row['gid'],[710,711,712])){
                unset($temp[$key]);
            }
        }
        if(in_array($type,[3])){
            foreach ($temp as $key=>$row){
                $temp[$key]['goriginReward'] = explode(',',$row['goriginReward']);
                $temp[$key]['gbaseReward'] = explode(',',$row['gbaseReward']);
            }
        }else if(in_array($type,[6])){
            foreach ($temp as $key=>$row){
            	if($row['gid'] == 601){
                    $temp[$key]['goriginReward'] = json_decode($row['goriginReward'],true);
                }
                if($row['gid'] == 602){
                    $temp[$key]['goriginReward'] = json_decode($row['goriginReward'],true);
                    $temp[$key]['gbaseReward'] = json_decode($row['gbaseReward'],true);
                }
            }
            $idData = [
                14=>['name'=>'金币', 'data'=>[1=>"数值"]],
                15=>['name'=>'体力', 'data'=>[1=>"数值"]],
                22=>['name'=>'钻石', 'data'=>[1=>"数值"]],
            ];
            $data['idData'] = $idData;
        }else if(in_array($type,[7])){
            foreach ($temp as $key=>$row){
                $temp[$key]['goriginReward'] = json_decode($row['goriginReward'],true);
                if(in_array($row['gid'],[704,705,706])){
                    unset($temp[$key]);
                }
            }
            $idData = [
                22=>['name'=>'钻石', 'data'=>[1=>"数值"]],
            ];
            $data['idData'] = $idData;
        }else if(in_array($type,[9,10,12])){
            foreach ($temp as $key=>$row){
                $temp[$key]['goriginReward'] = json_decode($row['goriginReward'],true);
                $temp[$key]['gbaseReward'] = json_decode($row['gbaseReward'],true);
            }
        }
        if(in_array($type,[9])){
            $idData = [
                1=>['name'=>'金币', 'data'=>[201=>"coins01",202=>"coins02",203=>"coins03",204=>"coins04",205=>"coins05",206=>"coins06"]],
                2=>['name'=>'体力', 'data'=>[1=>"数值"]],
                3=>['name'=>'宝箱', 'data'=>[1=>"木质宝箱",2=>"白银宝箱",3=>"黄金宝箱",4=>"魔幻宝箱"]],
                4=>['name'=>'活动素材', 'data'=>[1=>"收集素材"]],
                5=>['name'=>'宠物相关', 'data'=>[1=>"宠物经验",2=>"宠物饲料"]],
                6=>['name'=>'祈福', 'data'=>[1=>"卡组祈福",2=>"卡片祈福"]],
                7=>['name'=>'VIP', 'data'=>[1=>"3日vip"]],
                9=>['name'=>'消耗品', 'data'=>[1=>"夺宝卷"]]
            ];
            $data['idData'] = $idData;
        }
        if(in_array($type, [21])){
            $idData = [ 1 => ['name' => '金币包', 'value' => 'coins'], 2 => ['name' => '体力', 'value' => 'spins'],3 => ['name' => '通行证经验', 'value' => 'crazyPassExp']];
            $data['idData'] = $idData;
            $data['idData2'] = [
                1 => [
                    ['name' => 'coins01', 'value' => 'coins01'],
                    ['name' => 'coins02', 'value' => 'coins02'],
                    ['name' => 'coins03', 'value' => 'coins03'],
                    ['name' => 'coins04', 'value' => 'coins04'],
                    ['name' => 'coins05', 'value' => 'coins05'],
                    ['name' => 'coins06', 'value' => 'coins06'],
                ],
                2 => [
                    ['name' => '体力', 'value' => 'spins'],
                ],
                3 => [
                    ['name' => '通行证经验', 'value' => 'crazyPassExp'],
                ],
            ];
            $notenough = $exchanges = []; 
            foreach($retData['exchanges'] as $k => $v){
                $v['gbaseReward'] = json_decode($v['gbaseReward'], true);
                if(!isset($exchanges[$v['pid']])){
                    $exchanges[$v['pid']] = [];
                }
                $exchanges[$v['pid']][] = $v; 
            }
            foreach($retData['notenough'] as $k => $v){
                $v['gbaseReward'] = json_decode($v['gbaseReward'], true);
                if(!isset($notenough[$v['pid']])){
                    $notenough[$v['pid']] = [];
                }
                $notenough[$v['pid']][] = $v; 
            }
            
            $data['exchanges'] = $exchanges;
            $data['notenough'] = $notenough;
        }
        $data['title'] = $title;
        $data['list'] = $temp;
        $data['type'] = $type;
        $this->load->view('shop/config'.$type, $data);
    }

    public function actionConfig(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'saveConfig';
        $specialType  = [6,7,8,9,10,11,12,13,14,21];
        if(in_array($postData['type'],$specialType)){
            if($postData['type'] == 9){
                foreach ($postData['good'] as $key=>$row){
                    $reward = [];
                    foreach ($row['gbaseReward']['type'] as $x=>$y){
                        $reward[] = [
                            'type'=>$y,
                            'id'  =>$row['gbaseReward']['id'][$x],
                            'num' =>$row['gbaseReward']['num'][$x],
                        ];
                    }
                    $postData['good'][$key]['gbaseReward'] = json_encode($reward,JSON_NUMERIC_CHECK);
                }
                $postData['data'] = json_encode($postData['good'],JSON_NUMERIC_CHECK);
            }elseif($postData['type'] == 7){
            	foreach ($postData['good'] as $key=>$row){
                    if(!is_array($row['goriginReward'])){
                        continue;
                    }
                    $reward = [];
                    foreach ($row['goriginReward']['propsId'] as $x=>$y){
                        $reward[] = [
                            'propsId'=>$y,
                            'num' =>$row['goriginReward']['num'][$x],
                        ];
                    }
                    $postData['good'][$key]['goriginReward'] = json_encode($reward,JSON_NUMERIC_CHECK);
                }
                $postData['data'] = json_encode($postData['good'],JSON_NUMERIC_CHECK);
            }elseif($postData['type'] == 6){
                foreach ($postData['good'] as $key=>$row){
                    if(!is_array($row['gbaseReward'])){
                        continue;
                    }
                    $reward = [];
                    foreach ($row['gbaseReward']['propsId'] as $x=>$y){
                        $reward[] = [
                            'propsId'=>$y,
                            'num' =>$row['gbaseReward']['num'][$x],
                        ];
                    }
                    $postData['good'][$key]['gbaseReward'] = json_encode($reward,JSON_NUMERIC_CHECK);
                }
                foreach ($postData['good'] as $key=>$row){
                    if(!is_array($row['goriginReward'])){
                        continue;
                    }
                    $reward = [];
                    foreach ($row['goriginReward']['propsId'] as $x=>$y){
                        $reward[] = [
                            'propsId'=>$y,
                            'num' =>$row['goriginReward']['num'][$x],
                        ];
                    }
                    $postData['good'][$key]['goriginReward'] = json_encode($reward,JSON_NUMERIC_CHECK);
                }
                $postData['data'] = json_encode($postData['good'],JSON_NUMERIC_CHECK);
            }elseif($postData['type'] == 21){
                $notenough = $exchanges = [];
                foreach ($postData['diamond'] as $key=>$row){
                    $row['gbaseReward'] = json_encode([$row['gbaseReward']['type'] => $row['gbaseReward']['num']]);
                    $exchanges[] = $row;
                }
                $posts['exchanges'] = json_encode($exchanges);
                foreach($postData['enough'] as $key=>$row){
                    if($row['gbaseReward']['type'] != 'spins'){
                        $row['gbaseReward'] = json_encode(['coins' => $row['gbaseReward']['type'], 'num' => $row['gbaseReward']['num']]);
                    }else{
                        $row['gbaseReward'] = json_encode(['spins' => $row['gbaseReward']['num']]);
                    }
                    $notenough[] = $row;
                }
                $posts['notenough'] = json_encode($notenough);
                $postData['data'] = json_encode($postData['good']);
            }else{
                foreach ($postData['diamond'] as $key=>$row){
                    $postData['good'][$key]['gbaseReward'] = json_encode($row['gbaseReward'],JSON_NUMERIC_CHECK);
                }
                $postData['data'] = json_encode($postData['good'],JSON_NUMERIC_CHECK);
            }
        }
        $posts['type'] = $postData['type'];
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        
        oo::logs()->adminlog($this->router->fetch_method());
        
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function level(){
        $title = $this->level_title;
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'level';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $data['title'] = $title;
        $data['list'] = $retData['data'];
        $this->load->view('shop/level', $data);
    }

    public function actionLevel(){
        $postData = $this->input->post('data');
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'saveLevel';
        $posts['data'] = $postData;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        
        oo::logs()->adminlog($this->router->fetch_method());
        
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function chest(){
        $title = $this->chest_title;
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'CardChest';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $data['title'] = $title;
        $data['list'] = $retData['data'];
        $this->load->view('shop/chest', $data);
    }

    public function actionChest(){
        $postData = $this->input->post('data');
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'saveCardChest';
        $posts['data'] = $postData;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        
        oo::logs()->adminlog($this->router->fetch_method());
        
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function payDistributed($type = 2){
        date_default_timezone_set('UTC');
        if($sdate = get_cookie('sta_np_stime')) {
            $data['stime'] = $sdate;
        }else {
            $data['stime'] = date('Y-m-d',strtotime("-7 days"));
        }

        if($edate = get_cookie('sta_np_etime')) {
            $data['etime'] = $edate;
        }else {
            $data['etime'] = date('Y-m-d',  strtotime('-1 days'));
        }

        $dateTemp = [];
        $stime = $data['stime'];
        for($i=0;$i<=$this->diffBetweenTwoDays($data['stime'],$data['etime']);$i++){
            $dateTemp[] = date('Ymd', strtotime("$stime + $i days"));
        }

        $data['date'] = $dateTemp;

        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'payDistributed';
        $posts['stime'] = $data['stime'];
        $posts['etime'] = $data['etime'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,true);

        if($type == 1 || $type == 2){
            $tempData = $retData['data'];
            $out = $outGroup = $goodGroup =[];
            $pidGroup = [
                1    => ['gname'=>'能量'],
                2    => ['gname'=>'金币'],
                3    => ['gname'=>'宝箱'],
                5    => ['gname'=>'摇奖转盘'],
                6    => ['gname'=>'首充'],
                7    => ['gname'=>'限定礼包'],
                22   => ['gname'=>'超级连环礼包'],
                8    => ['gname'=>'会员订阅'],
                9    => ['gname'=>'节日礼包'],
                10   => ['gname'=>'体力月卡'],
                11   => ['gname'=>'卡组祝福'],
                12   => ['gname'=>'夺宝卷'],
                13   => ['gname'=>'n袋口粮&经验'],
                14   => ['gname'=>'n点经验药水'],
                1810 => ['gname' => "二选一商品奖励"],
                306  => ['gname' => "每日宝箱"],
                1501 => ['gname'=>'金币不足弹框'],
                ////////////////////////////////////////
                1502 => ['gname'=>'体力不足弹框'],
                1511 => ['gname'=>'钻石不足弹框'],
                ////////////////////////////////////////
                161  => ['gname'=>'Ice Cold Pack'],
                162  => ['gname'=>'Hot Vocation Pack'],
                163  => ['gname'=>'Royal Treasure Pack'],
                164  => ['gname'=>'Pay Bet & moon pack'],
                165  => ['gname'=>'superstar pack'],
                166  => ['gname'=>'bumper harvest'],
                167  => ['gname'=>'升级礼包'],
                168  => ['gname'=>'Keep Playing'],
                169  => ['gname'=>'Treasure Quest Pack'],
                170  => ['gname'=>'限时特惠'],
                201  => ['gname'=>'通行证'],
                220  => ['gname'=>'钻石'],
                171  => ['gname'=>'Thailand'],
                172  => ['gname'=>'T3 country'],
                174  => ['gname'=>'超值礼包'],
                999  => ['gname'=>'连环礼包'],//特殊处理 老板需求
                1000 => ['gname'=>'其他'],
                1813 => ['gname'=>'基金'],
            ];

            if(1){
                $specialArr = [710,711,712,221,1772,1773,1774,1775,1776,1502,1503,1504,1505,1506,1507,1508,1509,1510,1511,1512,1513,1514,1515,1516,1810,1811,306,1811,1812];
                $added1 = $added2 = $added3 = $added4 = [];
                //分组
                $goodsPid = [];
                foreach($tempData['good'] as $row){
                    $goodsPid[$row['gid']] = $row['gpid'];
                }
                foreach ($tempData['data'] as $key=>$day){
                    foreach ($day as $d){
                        $gpid = $goodsPid[$d['sl_gid']];
                        if(!in_array($d['sl_gid'],$specialArr)){
                            if(isset($pidGroup[$gpid])){
                                $out[$gpid][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                            }else{
                                $out[1000][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                            }
                        }else if($gpid == 15 && in_array($d['sl_gid'],[1501,1503,1504,1505,1506,1507])){
                            //金币不足
                            !in_array($d['id'], $added3) && $out[1501][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                            $added3[] = $d['id'];
                        }else if($gpid == 15 && in_array($d['sl_gid'],[1502,1508,1509,1510])){
                            //体力不足
                            !in_array($d['id'], $added1) && $out[1502][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                            $added1[] = $d['id'];
                        }else if($gpid == 15 && in_array($d['sl_gid'],[1511,1512,1513,1514,1515,1516])){
                            //钻石不足
                            !in_array($d['id'], $added2) && $out[1511][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                            $added2[] = $d['id'];
                        }else if(in_array($d['sl_gid'],[710,711,712])){
                            //连环礼包
                            $out[999][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                        }else if(in_array($d['sl_gid'],[1772,1773,1774,1775,1776])){
                            //钻石
                            $out[220][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                        }else if(in_array($d['sl_gid'], [1810, 1811])){
                            //二选一
                            $out[1810][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                        }else if(in_array($d['sl_gid'], [306])){
                            //每日宝箱
                            $out[306][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                        }else if(in_array($d['sl_gid'], [1812,1813])){
                            //基金
                            $out[1813][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                        }
                    }
                }

                //获取第一天排序
                $temp = $sortData = [];
                foreach($pidGroup as $gpid => $row){
                    $sortData[$gpid] = empty($out[$gpid][end($dateTemp)])?0:$out[$gpid][end($dateTemp)];
                }
                arsort($sortData);
                foreach($sortData as $gpid => $num){
                    $temp[$gpid] = $pidGroup[$gpid];
                }

                $data['good'] = $temp;
            }else{
                foreach ($tempData['good'] as $row){
                    foreach ($tempData['data'] as $key=>$day){
                        $out[$row['gid']][$key] = 0;
                        foreach ($day as $d){
                            if($row['gid'] == $d['sl_gid']){
                                $out[$row['gpid']][date("Ymd",$d['sl_pay_time'])] += $d['sl_pusd'];
                            }
                        }
                    }
                }
                $data['good'] = $tempData['good'];
            }
            $data['out']  = $out;
            $this->load->view('shop/sta'.($type == 2?'2':''), $data);
        }else if($type == 2){
            $tempData = $retData['data'];
            $out = [];
            foreach ($tempData['good'] as $row){
                foreach ($tempData['data'] as $key=>$day){
                    $out[$row['gid']][$key] = 0;
                    foreach ($day as $d){
                        if($row['gid'] == $d['sl_gid']){
                            $out[$row['gid']][$key] += $d['sl_pusd'];
                        }
                    }
                }
            }
            $temp = [];
            foreach ($tempData['good'] as $row){
                $temp[] = [
                    'name'=>$row['gname'],
                    'data'=>$out[$row['gid']],
                ];
            }
            $data['data'] = $temp;
            $this->load->view('shop/sta2', $data);
        }else if($type == 3){
        	//饼图
            $tempData = $retData['data'];
            //分类
            $out = [];
            //归类
            $out2 = [];
            foreach($tempData['data'] as $data_k => $data_v){
            	
            	foreach($tempData['good'] as $good_k => $good_v){
            		$out[$data_k][$good_v['gid']] = 0;
            		$out2[$data_k][$good_v['gpid']] = isset($out2[$data_k][$good_v['gpid']])?$out2[$data_k][$good_v['gpid']]:0;
            		foreach($data_v as $d){
            			if($d['sl_gid'] == $good_v['gid']){
            				$out[$data_k][$good_v['gid']] += $d['sl_pusd'];
            				$out2[$data_k][$good_v['gpid']] += $d['sl_pusd'];
            			}
            		}
            	}
            }
            
            $goods = [];
            $goodsSumName = ["1"=>"能量","2"=>"金币","3"=>"宝箱","5"=>"转盘","6"=>"首冲","7"=>"充值活动","8"=>"会员订阅","9"=>"节日礼包","10"=>"体力月卡","11"=>"卡片祝福","12"=>"夺宝卷x1","13"=>"夺宝卷x5"];
            $goodsSum = [];
            foreach($tempData['good'] as $good_k => $good_v){
            	$goods[$good_v['gid']] = $good_v['gname'];
            	$goodsSum[$good_v['gpid']] = $goodsSumName[$good_v['gpid']];
            }
            krsort($dateTemp);
            krsort($out);
            krsort($out2);
            $data['date'] = $dateTemp;
            $data['shopPercent'] = $out;
            $data['shopPercentSum'] = $out2;
            $data['good'] = $goods;
            $data['goodsSum'] = $goodsSum;
            $this->load->view('shop/sta3', $data);
        }else if($type == 4){
        	//饼图
            $tempData = $retData['data'];
            //分类
            $out = [];
            //归类
            $out2 = [];
            
            foreach($tempData['data'] as $data_k => $data_v){
            	
            	foreach($tempData['good'] as $good_k => $good_v){
            		$out[$good_v['gid']] = isset($out[$good_v['gid']])?$out[$good_v['gid']]:0;
            		$out2[$good_v['gpid']] = isset($out2[$good_v['gpid']])?$out2[$good_v['gpid']]:0;
            		foreach($data_v as $d){
            			if($d['sl_gid'] == $good_v['gid']){
            				$out[$good_v['gid']] += $d['sl_pusd'];
            				$out2[$good_v['gpid']] += $d['sl_pusd'];
            			}
            		}
            	}
            }
            
            $goods = [];
            $goodsSumName = ["1"=>"能量","2"=>"金币","3"=>"宝箱","5"=>"转盘","6"=>"首冲","7"=>"充值活动","8"=>"会员订阅","9"=>"节日礼包","10"=>"体力月卡","11"=>"卡片祝福","12"=>"夺宝卷x1","13"=>"夺宝卷x5"];
            $goodsSum = [];
            foreach($tempData['good'] as $good_k => $good_v){
            	$goods[$good_v['gid']] = $good_v['gname'];
            	$goodsSum[$good_v['gpid']] = $goodsSumName[$good_v['gpid']];
            }
            
            $data['date'] = $dateTemp;
            $data['shopPercent'] = $out;
            $data['shopPercentSum'] = $out2;
            $data['good'] = $goods;
            $data['goodsSum'] = $goodsSum;
            $this->load->view('shop/sta4', $data);
        }else if($type == 5){ //钻石消耗条形图
            $stime = strtotime($data['stime']) ? date('Ymd', strtotime($data['stime'])) : '';
            $etime = strtotime($data['etime']) ? date('Ymd', strtotime($data['etime'])) : '';
            $tmp = oo::commonOprModel('diamondconsume')->diamondConsumeData($stime, $etime);
            $data['data'] = $tmp['data'];
            $data['title'] = $tmp['title'];
            $this->load->view('shop/sta5', $data);
        }
    }

    public function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }

    public function pet(){
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'config';
        $posts['type'] = 13;
        $feedConfig = json_decode($this->curl->req($this->url, $posts),true);
        $posts['type'] = 14;
        $expConfig = json_decode($this->curl->req($this->url, $posts),true);
        $data = [
            'feed' => $feedConfig['data'],
            'exp'  => $expConfig['data'],
        ];
        $this->load->view('shop/config13_14', $data);
    }

    public function serialPack(){
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'config';
        $posts['type'] = 7;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $temp = [];
        foreach ($retData['data'] as $row){
            if(in_array($row['gid'],[710,711,712])){
                $gsku        = json_decode($row['gsku'],true);
                $row['gsku'] = is_array($gsku) ? "" : $row['gsku'];
                $row['gsku1']= is_array($gsku) ? $gsku : ['coins'=>'coins01','bet'=>0];
                $row['gbaseReward']  = json_decode($row['gbaseReward'],true);
                $row['goriginReward']= json_decode($row['goriginReward'],true);
                $temp[]      = $row;
            }
        }
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $data['idData'] = $retData['props'];
        $data['list'] = $temp;
        $data['chestSkin']  = array_column(oo::commonOprModel('config')->chestSkin(),'name','id');
        $this->load->view('shop/configSerialPack', $data);
    }

    public function actionSerialPack(){
        $input = $this->input->post("good");
        foreach ($input as $key=>$row){
            if(empty($row['gsku'])){
                $row['gsku'] = json_encode([
                    'coins'  => $row['coins'],
                    'bet'    => $row['bet'],
                ],JSON_NUMERIC_CHECK);
            }
            if(empty($row['gbaseReward']['props'])){
                $row['gbaseReward']['props'] = [];
            }else{
                $temp = [];
                foreach ($row['gbaseReward']['props']['propsId'] as $propsKey=>$propsId){
                    $tProps = [
                        'propsId' => $propsId,
                        'num'     => $row['gbaseReward']['props']['num'][$propsKey]
                    ];
                    if($propsId == 19){
                        $tProps['skin'] = !empty($row['gbaseReward']['props']['skin'][$propsKey]) ? $row['gbaseReward']['props']['skin'][$propsKey] : 1;
                    }
                    $temp[] = $tProps;
                }
                $row['gbaseReward']['props'] = $temp;
            }
            $row['gbaseReward'] = json_encode($row['gbaseReward'],JSON_NUMERIC_CHECK);
            unset($row['coins']);
            unset($row['bet']);
            unset($row['gid']);
            $input[$key] = $row;
        }

        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'setSerialPack';
        $posts['data'] = json_encode($input);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        
        oo::logs()->adminlog($this->router->fetch_method());
        
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function gift($pid = 161,$type = 16){
        $data = $this->getGiftData($pid,$type);
        if($type == 18){
        	//升级礼包等级配置
            $posts = $this->postData;
        	$posts['mod'] = 'Config';
	        $posts['act'] = 'getGiftUpLevelConfig';
	        $url = $this->config->item('officialUrl');
	        $retData = json_decode($this->curl->req($url, $posts),true);
	        $uplevel = [];
	        foreach ($retData as $k => $v){
	        	$uplevel[$v['gid']] = $v;
	        }
	        $data['uplevel'] = $uplevel;
	        
	        $this->load->view('shop/configGift2', $data);
        }else if($type==27){
            $userGroup = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(2),'name','id');
            $data['userGroup'] = $userGroup;
            $this->load->view('shop/configGift3', $data);
        }else{
        	$this->load->view('shop/configGift', $data);
        }
    }

    //修改该方法注意顺便修改Export 下的同名方法
    public function getGiftData($pid = 161,$type = 16){
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'config';
        $posts['type'] = $type;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        $temp = [];
        $name = [];
        foreach ($retData['data'] as $row){
            $name[$row['gpid']] = $row['gname'];
            if($pid != $row['gpid']){
                continue;
            }
            $row['gbaseReward']  = json_decode($row['gbaseReward'],true);
            $row['goriginReward']= json_decode($row['goriginReward'],true);
            if(!empty($row['ext'])){
                $row['ext'] =json_decode($row['ext'],1);
            }
            $temp[]      = $row;
        }
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url = $this->config->item('officialUrl');
        $retData = json_decode($this->curl->req($url, $posts),true);
        $data['idData'] = $retData['props'];
        $data['list'] = $temp;
        $data['name'] = $name;
        $data['type'] = $type;
        //sku价格配置
        $data['skuPrice'] = oo::commonOprModel('Payment')->getSkuPrice();
        $posts['mod'] = 'config';
        $posts['act'] = 'getAllCountry';
        $retData = $this->curl->req($url, $posts);
        $data['country'] = json_decode($retData,true);
        $data['userGroup2'] = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(2),'name','id');
        $data['chestSkin']  = array_column(oo::commonOprModel('config')->chestSkin(),'name','id');
        $data['easterEggSkin']  = array_column(oo::commonOprModel('config')->getActivityActionList('easter_egg'),'name','id');//四选一
        $data['treasureSkin']  = array_column(oo::commonOprModel('config')->getActivityActionList('treasure'),'name','id');//宝藏活动
        $data['crazyCardGroup']  = array_column(oo::commonOprModel('config')->getActivityActionList('crazy_card_group'),'name','id');
        $data['userGroup5'] = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');//数数分组
        $data['gpid'] = $pid;
        return $data;
    }

    public function actionGift(){
        $input = $this->input->post("good");
        foreach ($input as $key=>$row){
            if(empty($row['gbaseReward']['props'])){
                $row['gbaseReward']['props'] = [];
            }else{
                $temp = [];
                foreach ($row['gbaseReward']['props']['propsId'] as $propsKey=>$propsId){
                    $tProps = [
                        'propsId' => $propsId,
                        'num'     => $row['gbaseReward']['props']['num'][$propsKey]
                    ];
                    if(in_array($propsId,[19,41])){
                        $tProps['skin'] = !empty($row['gbaseReward']['props']['skin'][$propsKey]) ? $row['gbaseReward']['props']['skin'][$propsKey] : 1;
                    }
                    $temp[] = $tProps;
                }
                $row['gbaseReward']['props'] = $temp;
            }
            $row['gShowGroup'] = !empty($row['gShowGroup']) ? implode(',', $row['gShowGroup']) : '';
            $row['gShowGroupSS'] = !empty($row['gShowGroupSS']) ? implode(',', $row['gShowGroupSS']) : '';
//            $cache[$key]['gbaseReward'] =$row['gbaseReward'];
            $row['gbaseReward'] = json_encode($row['gbaseReward'],JSON_NUMERIC_CHECK);
            if(!empty($row['ext'])){
                $row['ext'] = json_encode($row['ext']);
//                $cache[$key]['ext'] = json_decode($row['ext'],1);
            }
            unset($row['gid']);
            $input[$key] = $row;
//            $cache[$key] = json_encode($row);
        }
        $posts = $this->postData;
        $posts['mod'] = 'Shop';
        $posts['act'] = 'setSerialPack';
        $posts['data'] = json_encode($input);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        if($this->input->post('type') == 18){
        	$input = $this->input->post('uplevel');
        	$posts['mod'] = 'Config';
	        $posts['act'] = 'setGiftUpLevelConfig';
	        $filename = 'GiftUpLevelConfig'.time().'.json';
        	$posts['filename'] = $filename;
	        $posts['data'] = json_encode($input);
	        $retData2 = $this->curl->req($url, $posts);
	        $config['list'] = $input;
	        $config['expiryTime'] = 60 * 5;
	        $this->SaveJson($config,$filename);
        }else if($this->input->post('type') == 27){
            $this->setCallBackGiftJson();
            $retData2 = 1;
        }else{
        	$retData2 = 1;
        }
        
        oo::logs()->adminlog('修改'.$this->input->post('type').'礼包配置'.$this->router->fetch_method());
        
        if($retData == 0 && $retData2 == 0){
            return $this->response(1, '操作失败');
        }else{
            if($this->input->post('type') == 16){
                oo::commonOprModel('Json')->giftWeightsJson();
            }
            return $this->response(0, '操作成功');
        }
    }

    public function setCallBackGiftJson($ret=[]){
        if(empty($ret)){
            $tb = otable::goodsCrazy();
            $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE gtype=27",MYSQLI_ASSOC);
        }
        $good = [];
        foreach ($ret as $row){
            $reward = json_decode($row['gbaseReward'],true);
            $propsTemp = $reward['props'];
            foreach ($propsTemp as $key=>$p){
                $pConfig = oo::commonOprModel('config')->getChestData($p['propsId']);
                if($pConfig){
                    $propsTemp[$key]['value'] = $pConfig;
                }
            }
            $temp = [
                'gid'        => $row['gid'],
                'pid'        => $row['gpid'],
                'coins'      => [
                    'gid'  => oo::commonOprModel('config')->coinsToGid($reward['coins']['coins']),
                    'bet'  => $reward['coins']['bet']
                ],
                'spins'      => $reward['spins'],
                'props'      => $propsTemp,
                'price'      => "$".$row['gprice'] ,
                'priceNum'   => (string)$row['gprice'],
                'sku'        => $row['gsku'],
                'isoSku'     => str_replace('gworld.cc','astak.crazyspin',$row['gsku']),
                'ggameid'    => $row['ggameid'],
                'gdiscount'  => $row['gdiscount'],
                'priceDollar'=> '$',
                'addRatio'   => $row['gaddRatio'],
                'expire'     => $row['gExpire'],
                'max'        => $row['gMax'],
                'ext'        => json_decode($row['ext'],1),
            ];
            if(!empty($row['gShowCountry'])){
                $temp['countryCode'] = explode(',',$row['gShowCountry']);
            }
            if(!empty($row['gShowGroup'])){
                $temp['gShowGroup'] = explode(',',$row['gShowGroup']);
            }
            $good[] = $temp;
            $cache[$row['gid']] = json_encode($temp);
        }
        $key =okeys::callbackGift();
        oo::commonOprRedis('games')->hMset($key,$cache);
        $filename = 'GiftCallBackConfig'.time().'.json';
        $posts['filename'] = $filename;
        $res1 =$this->SaveJson($good,$filename);
        if($res1){
            $tb = otable::StaticConfig();
            $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='GiftCallBackConfig'";
            oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->hSet(okeys::StaticConfig(),'GiftCallBackConfig',$filename);
        }
    }

    public function trigger(){
        $tb = otable::GiftTrigger();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $this->load->view('shop/configTrigger', ['list'=>$ret]);
    }

    public function actionTrigger(){
        $data = json_decode($this->input->post('data'),true);
        $tb = otable::GiftTrigger();
        foreach ($data as $row){
            $sql = "UPDATE {$tb} SET `name`='{$row['name']}',`x`='{$row['x']}',`y`='{$row['y']}',`max`='{$row['max']}',`rand`='{$row['rand']}',`interval`='{$row['interval']}' WHERE id='{$row['id']}'";
            $retData = oo::commonOprDb('games')->query($sql);
        }
        
        oo::logs()->adminlog($this->router->fetch_method());
        
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            oo::commonOprModel('Json')->giftWeightsJson();
            return $this->response(0, '操作成功');
        }
    }

    public function weights($type = 1){
        $tb  = otable::GiftWeights();
        $ret = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE type={$type}",MYSQLI_ASSOC);
        $out = ['type'=>$type,'list'=>json_decode($ret['data'],true)];
        if($type == 1){
            $out['name'] = ['有效期长','有效期中','有效期短'];
        }else if($type == 2){
            $goodTb = otable::goodsCrazy();
            $ret    = oo::commonOprDb('slavedb')->getAll("SELECT DISTINCT gpid , gname FROM {$goodTb} WHERE gtype=16",MYSQLI_ASSOC);
            $out['name'] = array_column($ret,NULL,'gpid');
        }else if($type == 4){
            $out['name'] = ['0.03折扣','0.02折扣','0.016折扣'];
        }else if($type == 3){

        }else{
            $name = [
                5=>"等级",
                6=>"积分",
                7=>"体力",
                8=>"购买天数",
            ];
            $out['name'] = $name[$type];
            $this->load->view('shop/weightsCommon', $out);
            return ;
        }
        $this->load->view('shop/weights'.$type, $out);
    }

    public function actionWeights(){
        $data = $this->input->post('data');
        $type = $this->input->post('type');
        $tb  = otable::GiftWeights();
        $weights = json_decode($data,true);
        $ret = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE type={$type}",MYSQLI_ASSOC);
        $dbData = json_decode($ret['data'],true);
        if($type == 1){
            foreach ($dbData as $key=>$row){
                $dbData[$key]['weights'] = $weights[$key];
            }
        }else if($type == 2){
            foreach ($dbData as $key=>$row){
                $dbData[$key]['weights'] = $weights[$key]['weights'];
            }
        }else if($type == 3){
            $max = [-1,1000,5000,10000];
            $lMax = [10,30,50,-1];
            foreach ($dbData as $key=>$row){
                $dbData[$key]['pointMin']     = $weights[$key]['pointMin'];
                $dbData[$key]['pointMax']     = max(0,$max[$key]);
                $dbData[$key]['pointWeights'] = $weights[$key]['pointWeights'];
                $dbData[$key]['levelMax']     = max(0,$lMax[$key]);
                $dbData[$key]['levelMin']     = $weights[$key]['levelMin'];
                $dbData[$key]['levelWeights'] = $weights[$key]['levelWeights'];
                $dbData[$key]['notPayDay']    = $weights[$key]['notPayDay'];
                $dbData[$key]['arppuMin']     = $weights[$key]['arppuMin'];
                $dbData[$key]['arppuWeights'] = $weights[$key]['arppuWeights'];
            }
        }else if($type == 4){
            foreach ($dbData as $key=>$row){
                $dbData[$key]['weights'] = $weights[$key];
            }
        }else{
            foreach ($dbData as $key=>$row){
                $dbData[$key]['weights'] = $weights[$key]['weights'];
            }
        }
        $temp = stripslashes(json_encode($dbData));
        $retData = oo::commonOprDb('games')->query("UPDATE {$tb} SET `data`='{$temp}' WHERE type={$type} LIMIT 1");
		
		oo::logs()->adminlog($this->router->fetch_method());
		
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            oo::commonOprModel('Json')->giftWeightsJson();
            return $this->response(0, '操作成功');
        }
    }

    public function bullet(){
        $tb  = otable::goodsCrazy();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE gtype=15",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['gbaseReward'] = json_decode($row['gbaseReward'],true);
        }
        
        $configTb = otable::shopNotEnoughConfig();
        $configRet = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$configTb}",MYSQLI_ASSOC);
        $config = [];
        foreach($configRet as $row){
        	$config[$row['gid']] = $row;
        }
        
        $this->load->view('shop/bullet', ['list'=>$ret,'config'=>$config]);
    }

    public function actionBullet(){
        $data = $this->input->post('good');
        $tb   = otable::goodsCrazy();
        foreach ($data as $gid=>$row){
            if(in_array($gid,[1501,1503,1504,1505,1506,1507])){
                $data[$gid]['gbaseReward'] = json_encode($row['gbaseReward'],JSON_NUMERIC_CHECK);
            }
            unset($data[$gid]['gid']);
            $set = "";
            foreach ($data[$gid] as $key=>$value){
                $set .= "`{$key}`='{$value}',";
            }
            $set = trim($set,',');
            $sql = "UPDATE {$tb} SET {$set} WHERE gid={$gid}";
            $ret = oo::commonOprDb('games')->query($sql);
        }
        
        $config = $this->input->post('config');
        $tb   = otable::shopNotEnoughConfig();
        foreach ($config as $gid=>$row){
        	$set = "";
            foreach ($config[$gid] as $key=>$value){
                $set .= "`{$key}`='{$value}',";
            }
            $set = trim($set,',');
            $sql = "UPDATE {$tb} SET {$set} WHERE gid={$gid}";
            $ret = oo::commonOprDb('games')->query($sql);
        }
        oo::logs()->adminlog($this->router->fetch_method());
        if($ret == 0){
            return $this->response(1, '操作失败');
        }else{
        	oo::commonOprRedis('games')->delete(okeys::shopNotEnoughConfig('money'));
        	oo::commonOprRedis('games')->delete(okeys::shopNotEnoughConfig('spins'));
            return $this->response(0, '操作成功');
        }
    }
    
    
    //宝藏探索积分配置
    public function treasurePointConfig(){
    	$tb   = otable::treasureQuestPointConfig();
    	$sql = "SELECT * FROM {$tb}";
    	$ret = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
    	$this->load->view('shop/treasurePointConfig', ['list'=>$ret]);
    }
    
    //宝藏探索积分配置 修改
    public function actionTreasurePointConfig(){
    	$data = $this->input->post('data');
    	$data = json_decode($data,1);
    	$tb   = otable::treasureQuestPointConfig();
    	foreach($data as $row){
    		$sql = "UPDATE {$tb} SET point={$row['point']} WHERE gid={$row['gid']}";
            $ret = oo::commonOprDb('games')->query($sql);
    	}
    	if($ret == 0){
            return $this->response(1, '操作失败');
        }else{
        	$jsonFile['list'] = $data;
        	$configName = "TreasurePointConfig";
            $filename   = "TreasurePointConfig".time().".json";
            self::SaveJson($jsonFile,$filename);
            oo::commonOprModel('Json')->setStaticConfig($configName,$filename);
            
            //删除缓存配置
            oo::commonOprRedis('games')->delete(okeys::treasureQuestPointConfig());
            
            return $this->response(0, '操作成功');
        }
    }

    public function safeBox(){
        $tb  = otable::goodsCrazy();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE gtype=23",MYSQLI_ASSOC);
        $data['title'] = $this->title[23];
        $data['list']  = $ret;
        $this->load->view('shop/safeBox',$data);
    }

    public function actionSafeBox(){
        $data = $this->input->post('data');
        $data = json_decode($data,true);
        $tb  = otable::goodsCrazy();
        foreach($data as $row){
            $ret = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tb} WHERE gsku='{$row['gsku']}' ORDER BY gid LIMIT 1",MYSQLI_ASSOC);
            $gprice = $ret['gprice'];
            oo::commonOprDb('games')->query("UPDATE {$tb} SET `gsku`='{$row['gsku']}',`gprice`='{$gprice}',`gdiscount`='{$row['gdiscount']}' WHERE gid={$row['gid']}");
        }
        return $this->response(0, '操作成功');
    }

    public function freeBar(){
        $data['conf']   = json_decode(oo::commonOprModel('config')->getSysCon('Shop',"freeBar"),true);
        $data['idData'] = oo::commonOprModel('config')->getPropsConfig();
        $this->load->view('shop/freeBar',$data);
    }

    public function actionFreeBar(){
        $data = $this->input->post();
        $reward = [];
        foreach ($data['conf']['reward']['propsId'] as $key=>$row){
            $reward[] = [
                'propsId' => $row,
                'num'     => $data['conf']['reward']['num'][$key]
            ];
        }
        $data['conf']['reward'] = $reward;
        oo::commonOprModel('config')->setSysCon('Shop',"freeBar",json_encode($data['conf'],JSON_NUMERIC_CHECK));
        return $this->response(0, '操作成功');
    }

    /**
     * 每日小抽小丑宝箱活动宝箱id统计
     */
    public function dailyChest($limit = 0){
        $tb = otable::daliyChestLog();

        $totalSql = "SELECT COUNT(*) AS total FROM {$tb}";
        $total = oo::commonOprDb('slavedb')->getOne($totalSql, MYSQLI_ASSOC);
        $sql = "SELECT day,chest1,chest2,chest3,chest4,chest5,chest6,chest7,chest8,chest9,chest10 FROM {$tb} ORDER BY day DESC LIMIT {$limit},{$this->pageNum}";
        $arr            = oo::commonOprDb('statistics')->getAll($sql,1);
        $data['list']   = $arr;
        $data['total']  = $total['total'];

        //分页
        $pageConfig               = $this->pageConfig;
        $pageConfig['base_url']   = base_url('#user/userDiamond');
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page']   = $this->pageNum;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['page'] = $page;

		$this->load->view('shop/dailychest', $data);
    }

    public $gTypeImg =[
        6=>"firstPay"
    ];
}
