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

/**
 * 配置相关
 */
class Slot 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 = ['关卡','攻击<br/>(权重)','偷袭<br/>(权重)','体力<br/>(权重)','护盾<br/>(权重)','1个金币<br/>(权重,金币)','2个金币<br/>(权重,金币)','3个金币<br/>(权重,金币)','1个钱袋<br/>(权重,金币)','2个钱袋<br/>(权重,金币)','3个钱袋<br/>(权重,金币)','没有奖励<br/>(权重)','活动物品1<br/>(权重)','活动物品2<br/>(权重)','活动物品3<br/>(权重)','小玩法物品1<br/>(权重)','小玩法物品2<br/>(权重)','小玩法物品3<br/>(权重)','一个偷<br/>(权重)','两个偷<br/>(权重)','一个打<br/>(权重)','两个打<br/>(权重)','1体力瓶<br/>(权重)','2体力瓶<br/>(权重)'];
    private $_role_title3 =['关卡','攻击<br/>(权重)','偷袭<br/>(权重)','体力<br/>(权重)','护盾<br/>(权重)','金币<br/>(权重)','金币袋<br/>(权重)','收集物<br/>(权重)','事件牌<br/>(权重)','万能福<br/>(权重)'];

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

    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::slotWeightGroups();
        $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('slot/weightGroups', ['groups' => $groups, 'headers' => $headers]);
    }
    public function editWeightGroup($id = 0)
    {
        $shushuGroups = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5),'name','id');
        $groupsTbl = otable::slotWeightGroups();
        $groups = oo::commonOprDb('slavedb')->getOne("select * from {$groupsTbl} where id=".$id);
        $groups['gids'] = explode(',', $groups['gids']);
        $this->load->view('slot/editWeightGroups', ['groups' => $groups, 'shushuGroups' => $shushuGroups]);
    }
    public function saveWeightGroup()
    {
        $params = $this->input->post();
        $params['id'] = intval($params['id']);
        $gids = implode(',', $params['gids']);
        $groupsTbl = otable::slotWeightGroups();
        $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::slotWeightGroupsShushus(),$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::slotWeightGroupsCfg();
        $where = " where gid='{$gid}' ";
        $sql = "SELECT * from {$tb} {$where} LIMIT {$start},{$length}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[$v['levelId']] = json_decode($v['slotpro'],true);
        }
        $sql = "SELECT COUNT(*) as num from {$tb} {$where} ";
        $rs = oo::commonOprDb('slavedb')->getOne($sql,1);
        $retData = [
            'total'=>$rs['num'],
            'data'=>$arr,
        ];

        if($retData['total'] == 0){
            $list = [];
        }else{
            $list = $retData['data'];
        }
        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $retData['total'];
        $data['page'] = $page/10;
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#slot/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('slot/groupWeights', $data);
    }

    /**
     * Notes: 设置老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:23
     * @return json
     */
    public function actionSoltWeightcfg($gid){
        $postData = $this->input->post();
        $data = json_decode($postData['data']);
        $upload = [];
        $level = [];
        foreach ($data as $row){
            $level[] = $row->id;
            $upload[] = [
                'level'=>$row->id,
                'slotpro' =>$row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }

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

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

    /**
     * Notes:保存老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:24
     * @param $data
     * @return array|int
     */
    public function saveSoltWeightCfg($gid, $data){
        $tb = otable::slotWeightGroupsCfg();
        $sql = "SELECT levelId from {$tb} where gid={$gid}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $temp = [];
        foreach ($rs as $row){
            array_push($temp,(int)$row['levelId']);
        }
        $data = json_decode(json_encode($data));
        foreach ($data as $row){
//            $slotPro = [];
//            foreach ($row->slotpro as $k => $items){
//                echo json_encode([$k => $items]);die;
//            }
            $tempData = json_encode($row->slotpro,JSON_UNESCAPED_UNICODE);
//            echo $tempData;die;
            if(in_array($row->level,$temp)){
                $sql = "UPDATE {$tb} SET slotpro='{$tempData}' WHERE levelId={$row->level} and gid={$gid}";
            }else{
                $sql = "INSERT INTO {$tb} (gid, levelId,slotpro) VALUES ({$gid}, {$row->level},'{$tempData}')";
            }
//            echo $sql;die;
            $rs = oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->hset(okeys::slotWeightGroupsCfg(),$gid . '_'.$row->level, $tempData);
        }

        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']);
    }

    //==================真老虎机============================
    public function realWeightGroups(){
        $groupsTbl = otable::realSlotWeightGroups();
        $groups = oo::commonOprDb('slavedb')->getAll("select * from {$groupsTbl}");
        $headers = [
            'id' => 'ID',
            'name' => '组名',
        ];
        $this->load->view('slot/realWeightGroups', ['groups' => $groups, 'headers' => $headers]);
    }
    public function editRealWeightGroup($id = 0){
        $groupsTbl = otable::realSlotWeightGroups();
        $groups = oo::commonOprDb('slavedb')->getOne("select * from {$groupsTbl} where id=".$id);
        $this->load->view('slot/editRealWeightGroups', ['groups' => $groups]);
    }
    public function saveRealWeightGroup(){
        $params = $this->input->post();
        $params['id'] = intval($params['id']);
        $groupsTbl = otable::realSlotWeightGroups();
        $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`) values ('{$params['name']}') ";
        }else{
            $sql = "update {$groupsTbl}  set `name`='{$params['name']}' where id={$params['id']} ";
        }
        $res = oo::commonOprDb('games')->query($sql);
        if(!$res)$this->response(-1, '保存失败');

        $this->response(1, '保存成功');
    }


    //老虎机权重配置
    public function realGroupWeights($gid, $type = 1, $page = 0, $ceProb = "weight")
    {
        $length = 50;
        $title = $this->_role_title3;

        switch ($ceProb) {
            case "weight":
                list("total" => $total, "list" => $list) = self::groupWeightList($gid, $type, $page, $length);
                break;
            case "ceProb":
                list("total" => $total, "list" => $list) = self::ceProConfList($gid, $type);
                break;
            default:
                $total = 0;
                $list = [];
                break;
        }

        $data['title'] = $title;
        $data['list'] = $list;
        $data['total'] = $total;
        $data['page'] = $page/50;
        $data['editUserList'] = $this->editUserList;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#slot/realGroupWeights/'.$gid."/".$type);
        $pageConfig['total_rows'] = $total;
        $pageConfig['per_page'] = $length;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['gid'] = $gid;
        $data['type'] = $type;
        $data['ceProb'] = $ceProb;
        $this->load->view('slot/realGroupWeights', $data);
    }

    private static function groupWeightList($gid, $type, $page,$length): array
    {
        $start = (ceil($page / $length)) * $length;

        $tb = otable::realSlotWeightGroupsCfg();
        $where = " Where gid='{$gid}' and type='{$type}' ";
        $rs = oo::commonOprDb('slavedb')->getAll("SELECT * from {$tb} {$where} LIMIT {$start},{$length}");

        $arr = [];
        foreach ($rs as $k => $v) {
            $arr[$v['levelId']] = json_decode($v['slotpro'], true);
        }

        $sql = "SELECT COUNT(*) as num from {$tb} {$where} ";
        $rs = oo::commonOprDb('slavedb')->getOne($sql, 1);

        return [
            'total' => $rs['num'],
            'list' => $arr,
        ];
    }

    // 老虎机概率干预事件
    private static function ceProConfList($gid, $type):array
    {
        $tb = otable::realSlotCeProConf();
        $where = " Where gid='{$gid}' and type='{$type}' ";
        $rs = oo::commonOprDb('slavedb')->getAll("SELECT * from {$tb} {$where}");

        $arrMap = [];
        foreach ($rs as $k => $v) {
            $arrMap[$v['levelId']] = json_decode($v['slotpro'], true);
        }

        $arr = [];
        for ($i = 1; $i <= 3; $i++) {
            $arr[$i] = $arrMap[$i] ?? [
                ["id" => 1, "v" => 0],
                ["id" => 2, "v" => 0],
                ["id" => 3, "v" => 0],
                ["id" => 4, "v" => 0],
                ["id" => 5, "v" => 0],
                ["id" => 6, "v" => 0],
                ["id" => 7, "v" => 0],
                ["id" => 8, "v" => 0],
                ["id" => 99, "v" => 0]];
        }

        return [
            'total' => 3,
            'list' => $arr,
        ];
    }

    /**
     * Notes: 设置老虎机权重配置
     * User: wsc
     * Time: 2021/2/27 13:23
     * @return json
     */
    public function actionRealSlotWeightcfg($gid, $type, $ceProb)
    {
        $postData = $this->input->post();
        $data = json_decode($postData['data']);

        $upload = [];
        $level = [];
        foreach ($data as $row) {
            $level[] = $row->id;
            $upload[] = [
                'level' => $row->id,
                'slotpro' => $row->data,
            ];
        }
        $nLevel = array_unique($level);
        if(count($nLevel) != count($level)){
            return $this->response(1, 'levelId 重复');
        }
        file_put_contents("/tmp/xzxcmserr.log", json_encode($upload) . PHP_EOL, FILE_APPEND);
        switch ($ceProb) {
            case "weight":
                $retData = $this->saveRealSlotWeightCfg($upload, $gid, $type);
                break;
            case "ceProb":
                $retData = $this->saveRealSlotCeProbCfg($upload, $gid, $type);
                break;
            default:
                return $this->response(1, "cePron 类型错误:{$ceProb}");
        }
        oo::logs()->adminlog($this->router->fetch_method());

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

    /**
     * Notes:保存老虎机权重配置
     */
    public function saveRealSlotWeightCfg($data, $gid, $type)
    {
        $tb = otable::realSlotWeightGroupsCfg();
        $sql = "SELECT levelId from {$tb} where gid={$gid} and type ={$type}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql);

        $temp = [];
        foreach ($rs as $row) {
            $temp[] = (int)$row['levelId'];
        }

        $data = json_decode(json_encode($data, 32));
        foreach ($data as $row) {

            $tempData = json_encode($row->slotpro, JSON_UNESCAPED_UNICODE);
            if (in_array($row->level, $temp)) {
                $sql = "UPDATE {$tb} SET slotpro='{$tempData}' WHERE levelId={$row->level} and gid={$gid} and type ={$type}";
            } else {
                $sql = "INSERT INTO {$tb} (gid, levelId,type,slotpro) VALUES ({$gid}, {$row->level},{$type},'{$tempData}')";
            }
            $rs = oo::commonOprDb('games')->query($sql);
            oo::commonOprRedis('games')->hset(okeys::RealSlotWeightConfig($gid, $row->level), $type, $tempData);
        }

        return $rs ?: 0;
    }

    /**
     * Notes:保存老虎机修正概率配置
     */
    public function saveRealSlotCeProbCfg($data, $gid, $type)
    {
        $tb = otable::realSlotCeProConf();

        $sql = "SELECT levelId from {$tb} where gid={$gid} and type ={$type}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql);

        $temp = [];
        foreach ($rs as $row) {
            $temp[] = (int)$row['levelId'];
        }

        foreach ($data as $row) {
            if (!in_array($row['level'], [1, 2, 3])) {
                return 0;
            }
            $upMap = [];
            foreach ($row['slotpro'] as $item) {
                $upMap[$item->id] = $item->v;
            }
            oo::commonOprRedis('games')->hMset(okeys::RealSloCeProbConfig($gid, $row['level']), $upMap);

            $tempData = json_encode($row['slotpro'], JSON_NUMERIC_CHECK);

            if (in_array($row['level'], $temp)) {
                $sql = "UPDATE {$tb} SET slotpro='{$tempData}' WHERE levelId={$row['level']} and gid={$gid} and type ={$type}";
            } else {
                $sql = "INSERT INTO {$tb} (gid, levelId,type,slotpro) VALUES ({$gid}, {$row['level']},{$type},'{$tempData}')";
            }

            $rs = oo::commonOprDb('games')->query($sql);
        }

        return $rs ?: 0;
    }

    /**
     * Notes:真老虎机金币配置
     * User: wsc
     * Time: 2022/6/9 15:11
     */
    public function realSlotCoin(){
        $tb = otable::realSlotCoinCfg();
        $sql = "SELECT * from {$tb}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql,1);
        $arr = [];
        foreach ($rs as $k=>$v){
            if(!isset($arr[$v['level']])){
                $arr[$v['level']][0] = $v['level'];
            }
            $arr[$v['level']][$v["stype"]] = $v["coins"];
        }
        $data["list"] = $arr;
//        echo "<pre>";
//        print_r($arr);
        $this->load->view('slot/realSlotCoin', $data);
    }

    /**
     * Notes:偷结果配置
     * User: wsc
     * Time: 2023/5/30 18:04
     */
    public function slotStealRet(){
        $data = oo::commonOprModel('config')->SlotWeightChangConfig();
        $data = array_column($data,"config","type");
        foreach ($data as $key=>&$value){
            $value = json_decode($value,true);
        }
        $this->load->view('slot/realSlotSteal', $data);
    }

    /**
     * Notes:设置偷结果配置
     * User: wsc
     * Time: 2023/5/30 18:05
     */
    public function actionSlotStealRet($type){
        $config = $this->input->post('config');
//        stealRetWeight, boxRetWeight, betRetWeight, betBoxRetWeight
        if($type == "stealRetWeightV2"){
            foreach ($config as $row){
                if($row['slv'] > $row['elv']){
                    return $this->response(1, '等级范围异常');
                }
            }
        }
        $data = [];
        $id = 1;
        foreach ($config as $row){
            $temp = $row;
            $temp['id'] = $id;
            if($type == "stealRetWeightV2") {
                foreach ($temp['props'] as $ind=>$item) {
                    $temp['props'][$ind] = json_decode($item,true);
                }
            }
            $data[] = $temp;
            $id ++;
        }
//        return $this->response(0, '操作成功',$data);
        $ret = oo::commonOprModel('config')->actionSlotWeightChangConfig($type,json_encode($data,JSON_NUMERIC_CHECK));
        if($ret){
            return $this->response(0, '操作成功',$data);
        }else{
            return $this->response(1, '操作失败',$data);
        }
    }

    const CONFIG_SlOT_LS_CONF="CONFIG_SlOT_LS_CONF";

    // 概率干预修正区间
    public function ceProConf()
    {
        $data['conf'] = oo::commonOprModel('config')->getCommonConf(self::CONFIG_SlOT_LS_CONF);

        $this->load->view('slot/ceProConf', $data);
    }

    // 概率干预修正区间 更新
    public function ceProConfUpdate()
    {
        $posts =  $this->input->post();

        oo::commonOprModel('config')->saveCommonConf(self::CONFIG_SlOT_LS_CONF, $posts['conf'], "收集活动等级体力分组修正等级配置");

        oo::commonOprRedis('games')->delete(self::CONFIG_SlOT_LS_CONF);

        return $this->response(0, '操作成功');
    }
}
