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

/**
 * 配置相关
 */
class Jackpot extends MY_Controller
{
    static $headers = [
        '没有奖励',
        '黑桃+红桃+方块',
        '黑桃*3',
        '红桃*3',
        '方块*3',
        '胡萝卜*3',
        '彩蛋*3',
        '篮子*1',
        '篮子*2',
        '篮子*3',
        'Jackpot*1',
        'Jackpot*2',
        'Jackpot*3',
    ];
    /***
     * 配置数据处理
     */
    public function groups()
    {
        $groups = JackpotModel::getGroups();

        $shushuGroups = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');
        foreach ($groups as &$group){
            $groupIds = explode(',', $group['gids']);
            $html = '';
            foreach ($groupIds as $groupId){
                if(empty($shushuGroups[$groupId]))continue;
                $html .= "<span class='shushuGroupText'>{$shushuGroups[$groupId]}</span>";
            }
            $group['groups'] = $html;
        }

        $headers = [
            'id' => 'ID',
            'name' => '分组名',
            'groups' => '数数分组',
        ];
        $data = [
            'title' => 'Jackpot老虎机权重分组',
            'headers' => $headers,
            'config' => $groups,
            'js' => 'jackpot',
            'topOperators' => [
                '<button type="button" class="btn btn-outline btn-info" onclick="addGroup()"  >新增分组</button>',
                '<input type="file" style="display: none" id="import-file" onchange="commonImport(this)" data-href="/import/jackpotGroups">',
            ],
            'operators' => [
                '<button type="button" class="btn btn-outline btn-primary" onclick="editGroup(this)"  >编辑</button>',
                '<button type="button" class="btn btn-outline btn-success" onclick="groupWeightsDetail(this)"  >权重配置</button>',
            ],
        ];
        $this->load->view('common/commonTable', $data);
    }
    public function saveGroup()
    {
        $groupsTbl = otable::jackpotGroups();
        $params = $this->input->post();
        $params['id'] = intval($params['id']);
        $gids = implode(',', $params['gids']);
        $groups = oo::commonOprDb('slavedb')->getOne("select * from {$groupsTbl} where `name`='{$params['name']}' and  id<>".$params['id']);
        if($groups){
            $this->response(-1, '分组名已存在');
        }
        if(empty($params['id'])){
            $sql = "insert into {$groupsTbl} (`name`, `gids`) values ('{$params['name']}', '{$gids}') ";
        }else{
            $sql = "update {$groupsTbl}  set `name`='{$params['name']}' , `gids` = '{$gids}' where id={$params['id']} ";
        }
        $res = oo::commonOprDb('games')->query($sql);
        if(!$res)$this->response(-1, '保存失败');

        $this->response(0, '保存成功', [$sql]);
    }


    // 老虎机权重配置
    public function groupWeights($gid, $page = 0)
    {
        $rs = JackpotModel::getGroupsWeights($gid);
        $ret = [];
        foreach ($rs as $key=>$row){
            $ret[$row['taskId']]['pro'] = json_decode($row['pro'],true);
            $ret[$row['taskId']]['superBet'] = json_decode($row['superBet'],true);
        }
        $data['list'] = $ret;
        $data['title'] = self::$headers;
        $data['gid'] = $gid;
        $this->load->view('jackpot/groupWeights', $data);
    }

    /**
     * Notes: 设置老虎机权重配置
     */
    public function actionWeightcfg($gid){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);
        $upload = [];
        $taskIds = [];
        foreach ($data as $row){
            $taskIds[] = $row->taskId;
            $upload[] = [
                'taskId'=>$row->taskId,
                'pro' =>$row->pro,
                'superBet' =>$row->superBet,
            ];
        }
        $ntaskIds = array_unique($taskIds);
        if(count($ntaskIds) != count($taskIds)){
            return $this->response(1, 'taskId 重复');
        }

        $retData = $this->saveWeightCfg($gid, $upload);
        oo::logs()->adminlog($this->router->fetch_method());

        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    /**
     * Notes:保存老虎机权重配置
     */
    public function saveWeightCfg($gid, $data){
        $tb = otable::treasureProGroupsConfig();
        $sql = "SELECT taskId from {$tb} where gid={$gid}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $taskIds = [];
        foreach ($rs as $row){
            array_push($taskIds,(int)$row['taskId']);
        }
        $data = json_decode(json_encode($data));
        foreach ($data as $row){
            $proJson = json_encode($row->pro,JSON_UNESCAPED_UNICODE);
            $superBetJson = json_encode($row->superBet,JSON_UNESCAPED_UNICODE);
//            echo $tempData;die;
            if(in_array($row->taskId,$taskIds)){
                $sql = "UPDATE {$tb} SET pro='{$proJson}',`superBet`='{$superBetJson}' WHERE taskId={$row->taskId} and gid={$gid}";
            }else{
                $sql = "INSERT INTO {$tb} (gid, taskId,pro,superBet) VALUES ({$gid}, {$row->taskId},'{$proJson}','{$superBetJson}')";
            }
            $rs = oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->hset(okeys::treasureProGroupsCfg(),$gid . '_'.$row->taskId, json_encode($row));
        }

        return $rs ? $rs : 0;
    }

    public function makeBeginGuideJson(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeBeginGuideJson';
        $retData = $this->curl->req($this->config->item('officialUrl'), $posts);
        $retData = json_decode($retData,true);
        self::SaveJson($retData['data'],$retData['filename']);
    }

}
