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

/**
 * 配置相关
 */
class Treasure extends MY_Controller
{
    public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    //老虎机title
    private $_role_title  = ['关卡','攻击<br/>(概率)','偷袭<br/>(概率)','体力<br/>(概率)','护盾<br/>(概率)','1个金币<br/>(概率,金币)','2个金币<br/>(概率,金币)','3个金币<br/>(概率,金币)','1个钱袋<br/>(概率,金币)','2个钱袋<br/>(概率,金币)','3个钱袋<br/>(概率,金币)','没有奖励<br/>(概率)','活动<br/>(概率)'];
    private $_role_title2 = ['关卡','转盘','小王子*3','狐狸*3','小王子*2','王冠*3','小王子*1','黑桃*3','红桃*3','方块*3','黑桃+红桃+方块','没有奖励','转盘1','转盘2','转盘3','转盘4','转盘5','转盘6','转盘7'];


    private $treasurepro_title = ['关卡','转盘','小王子*3','狐狸*3','小王子*2','王冠*3','小王子*1','黑桃*3','红桃*3','方块*3','黑桃+红桃+方块','没有奖励','转盘1','转盘2','转盘3','转盘4','转盘5','转盘6','转盘7'];

    public function __construct()
    {
//        date_default_timezone_set("Asia/Shanghai");
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->library('pagination');
        $this->env = get_cookie($this->_wenenv);
        $this->_url = $this->config->item('officialUrl');
        //判断model是否存在
        if (file_exists(APPPATH.'models/Common.php'))
        {
            $this->load->model('common');
        }
    }

    /***
     * 配置数据处理
     */
    public function weightGroups()
    {
        $groupsTbl = otable::treasureProGroups();
        $groups = oo::commonOprDb('slavedb')->getAll("select * from {$groupsTbl}");
        $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' => '数数分组',
        ];
        $this->load->view('treasure/weightGroups', ['groups' => $groups, 'headers' => $headers]);
    }
    public function editWeightGroup($id = 0)
    {
        $shushuGroups = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');
        $groupsTbl = otable::treasureProGroups();
        $groups = oo::commonOprDb('slavedb')->getOne("select * from {$groupsTbl} where id=".$id);
        $groups['gids'] = explode(',', $groups['gids']);
        $this->load->view('treasure/editWeightGroups', ['groups' => $groups, 'shushuGroups' => $shushuGroups]);
    }
    public function saveWeightGroup()
    {
        $params = $this->input->post();
        $params['id'] = intval($params['id']);
        $gids = implode(',', $params['gids']);
        $groupsTbl = otable::treasureProGroups();
        $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, '保存失败');


        $sql = "select * from {$groupsTbl}";
        $groups = oo::commonOprDb('slavedb')->getAll($sql,1);
        foreach ($groups as $group){
            oo::commonOprRedis('games')->hset(okeys::treasureProGroupsShushus(),$group['id'], $group['gids']);
        }
        $this->response(1, '保存成功');
    }


    //老虎机权重配置
    public function groupWeights($gid, $page = 0)
    {
        $length = 50;
        $start = (ceil($page/$length)) * $length;
        $title = $this->_role_title2;

        $tb = otable::treasureProGroupsConfig();
        $where = " where gid='{$gid}' ";
        $sql = "SELECT * from {$tb} {$where} LIMIT {$start},{$length}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $arr = [];
        $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;

        $sql = "SELECT COUNT(*) as num from {$tb} {$where} ";
        $rs = oo::commonOprDb('slavedb')->getOne($sql,1);
        $data['title'] = $title;
        $data['page'] = $page/10;
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#treasure/groupWeights/'.$gid);
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $length;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['gid'] = $gid;
        $this->load->view('treasure/groupWeights', $data);
    }

    /**
     * Notes: 设置老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:23
     * @return json
     */
    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:保存老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:24
     * @param $data
     * @return array|int
     */
    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']);
    }

}
