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

/**
 * 公会配置
 */
class Club extends MY_Controller{
    public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    public $postdata = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);

    protected $page = 10;//分页
    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 function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->library('pagination');

        $this->env = get_cookie($this->_wenenv);
    }

    /**
     *	公会配置 -- 基础配置
     */
    public function index()
    {
        $table = otable::commonConfig();
        $basicKey = okeys::clubBasicKey();
        $typeKey = $basicKey;
        $config = oo::commonOprRedis('games')->get($basicKey);
        if(empty($config)){
            $config = oo::commonOprDb('slavedb')->getOne("select * from {$table} where type='{$typeKey}' limit 1");
            $config = $config['conf'];
        }
        $config = empty($config) ? [] : (@json_decode($config, true) ?? []);

        $skins = oo::commonOprModel('config')->getActiveImgNameConfig()['club_redpacket'] ?? [];
        $skins = array_column($skins, 'name', 'type');
        $columns = [
            'showIconMiniLv' => $this->inputField('showIconMiniLv','俱乐部图标出现等级', 'text', $config['showIconMiniLv'] ?? ''),
            'openMiniLv' => $this->inputField('openMiniLv','俱乐部开放等级', 'text', $config['openMiniLv'] ?? ''),
            'helpSpinNum' => $this->inputField('helpSpinNum','每次帮助体力数量', 'text', $config['helpSpinNum'] ?? ''),
            'askForSpinNum' => $this->inputField('askForSpinNum','每次索要体力数量', 'text', $config['askForSpinNum'] ?? ''),
            'askForSpinCoolingTime' => $this->inputField('askForSpinCoolingTime','索要体力冷却时间', 'text', $config['askForSpinCoolingTime'] ?? ''),
            'askForCardCoolingTime' => $this->inputField('askForCardCoolingTime','索要卡片冷却时间', 'text', $config['askForCardCoolingTime'] ?? ''),
            'removeMaxNum' => $this->inputField('removeMaxNum','会长每天能移除成员数量', 'text', $config['removeMaxNum'] ?? ''),
            'createWithCoin' => $this->inputField('createWithCoin','创建俱乐部花费金币数量', 'text', $config['createWithCoin'] ?? ''),
            'memberMaxNum' => $this->inputField('memberMaxNum','俱乐部最大人数', 'text', $config['memberMaxNum'] ?? ''),
            'joinCfg[maxStar]' => $this->inputField('joinCfg[maxStar]','加入俱乐部所需最高星数', 'text', $config['joinCfg']['maxStar']?? ''),
            'joinCfg[miniStar]' => $this->inputField('joinCfg[miniStar]','加入俱乐部所需最低星数', 'text', $config['joinCfg']['miniStar']?? ''),
            'joinCfg[regulateStar]' => $this->inputField('joinCfg[regulateStar]','每档调节星数', 'text',$config['joinCfg']['regulateStar']?? ''),
            'club_redpacket' => $this->inputField('club_redpacket','公会红包皮肤选择', MY_Controller::$inputFieldTypeSelector,$config['club_redpacket']?? '', $skins),
        ];
        $data = [
            'config' => $config,
            'columns' => $columns,
        ];
        $this->load->view('club/index', $data);
    }

    public function saveBasicConfig(){
        $input = $this->input->post();
        $table = otable::commonConfig();
        $basicKey = okeys::clubBasicKey();
        $basicConfig = json_encode($input);
        if(empty($input['id'])){
            $res = oo::commonOprDb('games')->query("insert into {$table} (`type`, `name`, `conf`)  values ('{$basicKey}', '公会基础配置', '{$basicConfig}')");
            $input['id'] = oo::commonOprDb('games')->insertID();
            $basicConfig = json_encode($input);
        }
        $res = oo::commonOprDb('games')->query("update {$table} set  `conf`='{$basicConfig}' where id={$input['id']} ");
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->set($basicKey, $basicConfig);
        $this->response(1, '保存成功');
    }

    public function supriseConfig($type = 'spins'){
        if(!in_array($type, ['spins', 'card']))exit('非法操作');
        $table = otable::commonConfig();
        $typeKey = okeys::clubSurpriseKey($type);
        $config = oo::commonOprRedis('games')->get($typeKey);
        if(empty($config)){
            $config = oo::commonOprDb('slavedb')->getOne("select * from {$table} where type='{$typeKey}' limit 1");
            $config = $config['conf'] ?? '';
        }
        $config = json_decode($config, true);
        $columns = [
            'isOpen' => $this->inputField('isOpen','是否开启', 'selector', $config['isOpen'] ?? '', [1 => '开启', 0 => '关闭']),
            'loginDays' => $this->inputField('loginDays','连续登录天数', 'text', $config['loginDays'] ?? ''),
            'prob' => $this->inputField('prob','触发概率(整数)', 'text', $config['prob'] ?? ''),
        ];
        switch ($type){
            case 'spins':
                $columns['moreSpins'] = $this->inputField('moreSpins','额外增加体力数', 'text', $config['moreSpins'] ?? '');
                break;
        }
        $data = [
            'type' => $type,
            'config' => $config,
            'columns' => $columns,
            'props' => array_column(oo::commonOprModel('config')->getPropsConfigFromLocal(), null, 'id'),
        ];
//        echo json_encode($data);die;
        $this->load->view('club/supriseConfig', $data);
    }
    public function saveSupriseConfig($type = 'spins'){
        if(!in_array($type, ['spins', 'card']))exit('非法操作');

        $input = $this->input->post();
        $table = otable::commonConfig();
        $typeKey = okeys::clubSurpriseKey($type);
        $configName = '惊喜事件配置';
        switch ($type){
            case 'spins':$configName .= '-体力';break;
            case 'card' :
                $configName .= '-卡片';
                $input['receiverReward'][0]['skin'] = intval($input['receiverReward'][0]['skin']);
                $input['helperReward'][0]['skin']   = intval($input['helperReward'][0]['skin']);
                $input['receiverReward'] = array_values($input['receiverReward']);
                $input['helperReward'] = array_values($input['helperReward']);
                break;
        }
        $config = json_encode($input);
        if(empty($input['id'])){
            $res = oo::commonOprDb('games')->query("insert into {$table} (`type`, `name`, `conf`)  values ('{$typeKey}', '{$configName}', '{$config}')");
            $input['id'] = oo::commonOprDb('games')->insertID();
            $config = json_encode($input);
        }
        $res = oo::commonOprDb('games')->query("update {$table} set  `conf`='{$config}'  where id={$input['id']} ");
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->set($typeKey, $config);
        $this->response(1, '保存成功');
    }

    public function recommendConfig(){
        $typeKey = okeys::clubRecommendKey();
        $config = oo::commonOprModel('config')->getCommonConf($typeKey);
        $data = [
            'config' => $config
        ];
        $this->load->view('club/recommendConfig', $data);
    }
    public function saveRecommendConfig(){
        $input = $this->input->post();
        $intervals = [];
        $top_num = intval($input['top_num']);
        foreach ($input['start'] as $k => $v){
            $intervals[$v] = [
                'start' => intval($v),
                'end' => intval($input['end'][$k]),
                'num' => intval($input['num'][$k]),
            ];
        }
        krsort($intervals);
        $config = [
            'top_num' => $top_num,
            'intervals' => array_values($intervals)
        ];
        $configName = '公会推荐配置';
        $typeKey = okeys::clubRecommendKey();
        $res = oo::commonOprModel('config')->saveCommonConf($typeKey, $config, $configName);
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->delete($typeKey);
        $this->response(1, '保存成功');
    }

    public function showJoinQuit(){
        $typeKey = okeys::showJpinQuitKey();
        $config = oo::commonOprModel('config')->getCommonConf($typeKey);
        $columns = [
            'minutes' => $this->inputField('minutes','清理时限(分钟)', 'text', $config['minutes'] ?? ''),
            'count' => $this->inputField('count','保留消息数量上限', 'text', $config['count'] ?? ''),
        ];
        $data = [
            'type' => $typeKey,
            'config' => $config,
            'columns' => $columns,
        ];

        $this->load->view('club/showJoinQuit', $data);
    }
    public function saveShowJoinQuit(){
        $input = $this->input->post();
        $config = [
            'minutes' => $input['minutes'],
            'count' => $input['count'],
        ];
        $configName = '加入退出公会消息数配置';
        $typeKey = okeys::showJpinQuitKey();
        $res = oo::commonOprModel('config')->saveCommonConf($typeKey, $config, $configName);
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->delete($typeKey);
        $this->response(1, '保存成功');
    }

    public function memberNumSta(){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $memberNumMap = [
            '1-9',
            '10-19',
            '20-29',
            '30-39',
            '40-49',
            '50',
            'total',
        ];
        $clubMemberStaTabl = otable::clubMemberStatistics();
        $sql = "select * from {$clubMemberStaTabl} where date >= '{$stime}' and  date <= '{$etime}'";
        $records = oo::commonOprDb('clubSta')->getAll($sql);
        $staData = [];
        foreach ($records as $record){
            $staData[$record['date']] = $staData[$record['date']] ?? [];
            $staData[$record['date']][] = $record;
        }
        foreach ($staData as $date => $record){
            $staData[$date] = $record = array_column($record, 'nums', 'member_num_group');
            $staData[$date]['total'] = $record['total'] = array_sum($staData[$date]);
            foreach ($memberNumMap as $nums){
                $percent = empty($staData[$date]['total'])? '0%' : number_format($record[$nums]/$staData[$date]['total']*100, 2).'%';
                $staData[$date][$nums] = [
                    'nums' => $record[$nums],
                    'percent' => $percent,
                ];
            }
        }
        $data = [
            'staData' => $staData,
            'memberNumMap' => $memberNumMap,
            'stime' => $stime,
            'etime' => $etime,
        ];
        $this->load->view('club/memberNumSta', $data);
    }
    public function starNumSta(){
        $stime = get_cookie('stime') ?? date("Y-m-d",strtotime("-7 days 0:0:0"));
        $etime = get_cookie('etime') ?? date("Y-m-d",strtotime("-1 days 0:0:0"));
        $clubStarStaTabl = otable::clubStarStatistics();
        $sql = "select * from {$clubStarStaTabl} where date >= '{$stime}' and  date <= '{$etime}'";
        $records = oo::commonOprDb('clubSta')->getAll($sql);
        $header =[
            'date' =>                    '日期',
            'total_num' =>               '总公会数量',
            'active_num' =>              '正常公会数量',
            'min_num' =>                 '公会星星最小值',
            'max_num' =>                 '公会星星最大值',
            'average_num' =>             '公会星星平均数',
            'above_average_num' =>       '高于星星平均数公会数量',
            'below_average_num' =>       '低于星星平均数公会数量',
            'median_num' =>              '公会星星中位数',
            'above_median_num' =>        '高于星星中位数公会数量',
            'below_median_num' =>        '低于星星中位数公会数量',
            'percent_10_num' =>          '公会星星10%分位数',
            'percent_20_num' =>          '公会星星20%分位数',
            'percent_30_num' =>          '公会星星30%分位数',
            'percent_40_num' =>          '公会星星40%分位数',
            'percent_50_num' =>          '公会星星50%分位数',
            'percent_60_num' =>          '公会星星60%分位数',
            'percent_70_num' =>          '公会星星70%分位数',
            'percent_80_num' =>          '公会星星80%分位数',
            'percent_90_num' =>          '公会星星90%分位数',
        ];
        $data = [
            'records' => $records,
            'header' => $header,
            'stime' => $stime,
            'etime' => $etime,
        ];
        $this->load->view('club/starNumSta', $data);

    }


    // 公会表情配置:
    public function emojis(){
        $openEmojis = [
            101, 102, 103, 104, 105, 106, 107, 108,
            201, 202, 203, 204,
        ];
        $typeKey = okeys::clubConfigKeyByType('EMOTICONS');
        $config = oo::commonOprModel('config')->getCommonConf($typeKey);
        $columns = [
            'minLv' => $this->inputField('minLv','表情开放等级', MY_Controller::$inputFieldTypeText, $config['minLv'] ?? ''),
//            'emoIds' => $this->inputField('emoIds[]','开放表情ID', MY_Controller::$inputFieldTypeSelectorMultiple, $config['emoIds'] ?? [], $openEmojis),
        ];
        foreach ($openEmojis as $emoji){
            $columns["emojiSort[{$emoji}]"] = $this->inputField("emojiSort[{$emoji}]","{$emoji}号表情排序权重", MY_Controller::$inputFieldTypeText,  $config['emojiSort'][$emoji] ?? '', '权重越小越靠前');
        }
        $data = [
            'title' => '公会表情配置',
            'type' => $typeKey,
            'config' => $config,
            'columns' => $columns,
            'saveUrl' => 'saveEmojis',
        ];

        $this->load->view('club/clubCommonConfig', $data);
    }
    public function saveEmojis(){
        $input = $this->input->post();
        $config = $input;
        $emojiArray = array_filter($config['emojiSort']);// 过滤权重为空的
        $emojiCount = array_count_values($emojiArray);    // 校验是否有权重相同的
        foreach ($emojiCount as $k => $value){
            if($value > 1)$this->response(__LINE__ * -1, "权重 {$k} 重复");
        }
        $emojiSort = array_flip($emojiArray);    //权重为key
        ksort($emojiSort );
        $config['emoIds'] = array_values($emojiSort);
        $configName = '公会表情配置';
        $typeKey = okeys::clubConfigKeyByType('EMOTICONS');
        $res = oo::commonOprModel('config')->saveCommonConf($typeKey, $config, $configName);
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->delete($typeKey);
        $this->response(1, '保存成功', $emojiSort);
    }

    public function redPacket(){
        $packetTypes = [
            1 => '限制型',
            2 => '开放型',
        ];
        $triggerTypes = [
            1 => '激活通行证',
            2 => '岛屿过关',
            3 => '公会锦标赛活动开始',
            4 => '公会花园活动开始',

        ];
        $statusMap = [
            0 => '关闭',
            1 => '打开',

        ];
        $typeKey = okeys::clubConfigKeyByType('RED_PACKET_TRIGGER');
        $config = oo::commonOprModel('config')->getCommonConf($typeKey);

        $postData= array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);;
        $postData['mod'] = 'Activitynew';
        $postData['act'] = 'getTypeConf';
        $types = $this->getDateFromServer($postData);
        $data = [
            'config' => $config,
            'packetTypes' => $packetTypes,
            'triggerTypes' => $triggerTypes,
            'statusMap' => $statusMap,
        ];
        $data['reward_type'] = json_encode($types['reward_type']);//活动奖品
        $skins = oo::commonOprModel('config')->getPropsConfigFromLocal() ;
        $skinsArr = [];
        foreach ($skins as $k => $v){
            if(!empty($v['skinList']) && is_array($v['skinList'])){
                $skinsArr[$v['id']] = array_column($v['skinList'], 'name', 'id');
            }
        }
        $data['skinsArr']  = $skinsArr;
        $data['chestSkin']  = array_column(oo::commonOprModel('config')->chestSkin(),'name','id');
        $actProps = [
            "architecture"=>["propsId"=>25,"version"=>"1.7.5"],//建筑大师
            "balloon"=>["propsId"=>26,"version"=>"1.7.5"],//气球
            "speed_spins"=>["propsId"=>27,"version"=>"1.8.5"],//体力加速
            "coin_blast"=>["propsId"=>28,"version"=>"1.7.7"],//金币爆炸
            "crazy_bet"=>["propsId"=>31,"version"=>"1.7.7"],//疯狂倍率
            "discounts_architecture"=>["propsId"=>32,"version"=>"1.7.7"],//建筑打折
            "card"=>["propsId"=>33,"version"=>"1.7.7"],//卡片爆炸
            "shop_promotion"=>["propsId"=>34,"version"=>"1.7.7"],//商场优惠券
            "super_collect"=>["propsId"=>35,"version"=>"3.0.0"],//道具型超级收集活动
            "super_balloon"=>["propsId"=>36,"version"=>"1.14.1"],//超级气球
            "traffic_permit_bet"=>["propsId"=>39,"version"=>"1.8.1"],//通行证倍率
            "collect_bet"=>["propsId"=>40,"version"=>"1.8.4"],//收集翻倍
            EASTER_EGG=>["propsId"=>41,"version"=>"1.8.4"],//复活节彩蛋
            "treasure"=>["propsId"=>43,"version"=>"2.1.5"],//金币老虎机
            "crazy_card_group"=>["propsId"=>46,"version"=>"2.1.6"],//疯狂卡组
        ];
        $actPropsIds = [];
        foreach ($actProps as $act => $items){
            $actPropsIds[] = $items['propsId'];
        }
        $data['actPropsIds'] = $actPropsIds;
        $this->load->view('club/clubRedPackets', $data);
    }
    public function saveRedPacket(){
        $input = $this->input->post();
        foreach ($input['redPackets'] as &$packet){
            $packet['userLevelsStr'] = strtr($packet['userLevelsStr'], ['，' => ',', ' '=>'']);
            $packet['userLevels'] = explode(',', $packet['userLevelsStr']);
            $packet['userLevels'] = array_map(function ($v){return intval($v);}, $packet['userLevels']);
            $packet['userLevels'] = array_filter(array_unique($packet['userLevels']));
            if(empty($packet['type']))$this->response(-1, '红包类型为必填',  $packet);
            if(empty($packet['triggerType']))$this->response(-1, '红包触发类型为必填',  $packet);
            if($packet['triggerType'] == 2 && empty($packet['userLevels']))$this->response(-1, '红包触发类型为岛屿过关时，过关等级为必填',  $packet);
            $packet['prizes'] = @json_decode(urldecode($packet['prizes']), true) ?? [];
            if(empty($packet['prizes']))$this->response(-1, '红包触奖励不能为空',  $packet);
            foreach ($packet['prizes'] as $k => $prize){
                $packet['prizes'][$k]['propsId'] = $prize['type'];
            }
            $packet['userLevelsStr'] = implode(',', $packet['userLevels']);
        }
        $config = array_values($input['redPackets']);
        $configName = '公会红包配置';
        $typeKey = okeys::clubConfigKeyByType('RED_PACKET_TRIGGER');
        $res = oo::commonOprModel('config')->saveCommonConf($typeKey, $config, $configName);
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->delete($typeKey);
        $this->response(1, '保存成功',  $input);
    }
}