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

/**
 * 配置相关
 */
class LuckyDice extends MY_Controller
{
    private $postData;

    private $_role_title2 = ['任务阶段', '转盘1', '转盘2', '转盘3', '转盘4', '转盘5', '转盘6'];
    private $_role_title3 = ['任务阶段', '1点(权重)', '2点(权重)', '3点(权重)', '4点(权重)', '5点(权重)', '6点(权重)', '万能符(权重)'];

    public function __construct()
    {
        parent::__construct();
        $this->postData = $this->input->post();
    }

    //region 骰子结果配置

    /***
     * 配置数据处理
     */
    public function diceWeightGroup()
    {
        $groupsTbl = otable::luckyDicePointGroups();

        $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('luckyDice/diceWeightGroup', ['groups' => $groups, 'headers' => $headers]);
    }

    public function diceWeightGroupEdit($id = 0)
    {
        $shushuGroups = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5), 'name', 'id');
        $groupsTbl = otable::luckyDicePointGroups();
        $groups = oo::commonOprDb('slavedb')->getOne("select * from {$groupsTbl} where id=" . $id);
        $groups['gids'] = explode(',', $groups['gids']);
        $this->load->view('luckyDice/diceWeightGroupEdit', ['groups' => $groups, 'shushuGroups' => $shushuGroups]);
    }

    public function diceWeightGroupSave()
    {
        $params = $this->input->post();
        $params['id'] = intval($params['id']);
        $gids = implode(',', $params['gids']);
        $groupsTbl = otable::luckyDicePointGroups();
        $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, '保存失败');

        oo::commonOprRedis('games')->delete(okeys::LuckyDicePointGroups());

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

    //老虎机权重配置
    public function diceGroupWeights($gid, $type = 1, $page = 0)
    {
        $length = 50;
        $start = (ceil($page / $length)) * $length;
        $title = $this->_role_title3;
        $tb = otable::luckyDicePointGroupsConf();
        $where = " where gid='{$gid}' and type='{$type}' ";
        $sql = "SELECT * from {$tb} {$where} LIMIT {$start},{$length}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql, 1);
        $arr = [];
        foreach ($rs as $k => $v) {
            $arr[$v['taskId']] = json_decode($v['pro'], 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 / 50;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#luckyDice/diceGroupWeights/' . $gid . "/" . $type);
        $pageConfig['total_rows'] = $data['total'];
        $pageConfig['per_page'] = $length;
        $this->pagination->initialize($pageConfig);
        $pageurl = $this->pagination->create_links();
        $data['pageurl'] = $pageurl;
        $data['gid'] = $gid;
        $data['type'] = $type;
        $this->load->view('luckyDice/diceGroupWeights', $data);
    }

    /**
     * Notes: 设置老虎机权重配置
     */
    public function diceGroupWeightsSave($gid, $type)
    {
        $data = json_decode($this->postData['data'], true);

        $upload = [];
        $level = [];
        foreach ($data as $row) {
            $level[] = $row["id"];
            $upload[] = [
                'level' => $row["id"],
                'pro' => $row["data"],
            ];
        }
        $nLevel = array_unique($level);
        if (count($nLevel) != count($level)) {
            return $this->response(1, 'levelId 重复');
        }

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

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

    /**
     * Notes:保存老虎机权重配置
     */
    public function saveDiceGroupWeights($gid, $type, $data)
    {
        $tb = otable::luckyDicePointGroupsConf();
        $sql = "SELECT taskId from {$tb} where gid={$gid} and type ={$type}";
        $rs = oo::commonOprDb('slavedb')->getAll($sql, 1);
        $temp = [];
        foreach ($rs as $row) {
            array_push($temp, (int)$row['taskId']);
        }
        $data = json_decode(json_encode($data, 32));
        foreach ($data as $row) {

            $tempData = json_encode($row->pro, JSON_UNESCAPED_UNICODE);
            if (in_array($row->level, $temp)) {
                $sql = "UPDATE {$tb} SET pro='{$tempData}' WHERE taskId={$row->level} and gid={$gid} and type ={$type}";
            } else {
                $sql = "INSERT INTO {$tb} (gid, taskId,type,pro) VALUES ({$gid}, {$row->level},{$type},'{$tempData}')";
            }

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

        oo::commonOprRedis('games')->delete(okeys::LuckyDicePointGroupsConfig());

        return $rs ? $rs : 0;
    }

    //endregion

    //region 转盘权重倍率配置

    /***
     * 配置数据处理
     */
    public function winWeightGroup()
    {
        $groupsTbl = otable::luckyDiceWheelGroups();

        $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('luckyDice/winWeightGroup', ['groups' => $groups, 'headers' => $headers]);
    }

    public function winWeightGroupEdit($id = 0)
    {
        $shushuGroups = array_column(oo::commonOprModel('config')->getUserGroupConfigByCid(5), 'name', 'id');
        $groupsTbl = otable::luckyDiceWheelGroups();
        $groups = oo::commonOprDb('slavedb')->getOne("select * from {$groupsTbl} where id=" . $id);
        $groups['gids'] = explode(',', $groups['gids']);
        $this->load->view('luckyDice/winWeightGroupEdit', ['groups' => $groups, 'shushuGroups' => $shushuGroups]);
    }

    public function winWeightGroupSave()
    {
        $params = $this->input->post();
        $params['id'] = intval($params['id']);
        $gids = implode(',', $params['gids']);
        $groupsTbl = otable::luckyDiceWheelGroups();
        $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, '保存失败');

        oo::commonOprRedis('games')->delete(okeys::LuckyDiceWheelGroups());

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

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

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

        $ret = [];
        foreach ($rs as $key => $row) {
            $ret[$row['taskId']]['pro'] = json_decode($row['pro'], true);
        }
        $data['list'] = $ret;

        $data['title'] = $title;
        $data['page'] = $page / 10;
        $data['total'] = 1;
        $pageConfig = $this->pageConfig;
        $pageConfig['base_url'] = base_url('#luckyDice/winGroupWeights/' . $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('luckyDice/winGroupWeights', $data);
    }

    /**
     * Notes: 设置老虎机权重配置
     */
    public function winGroupWeightsSave($gid)
    {
        $data = json_decode($this->postData['data']);

        $upload = [];
        $taskIds = [];
        foreach ($data as $row) {
            $taskIds[] = $row->taskId;
            $upload[] = [
                'taskId' => $row->taskId,
                'pro' => $row->pro,
            ];
        }
        $ntaskIds = array_unique($taskIds);
        if (count($ntaskIds) != count($taskIds)) {
            return $this->response(1, 'taskId 重复');
        }

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

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

    /**
     * Notes:保存老虎机权重配置
     */
    public function saveWinGroupWeights($gid, $data)
    {
        $tb = otable::luckyDiceWheelGroupsConf();
        $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, JSON_NUMERIC_CHECK));
        foreach ($data as $row) {
            $proJson = json_encode($row->pro, JSON_UNESCAPED_UNICODE);

            if (in_array($row->taskId, $taskIds)) {
                $sql = "UPDATE {$tb} SET pro='{$proJson}' WHERE taskId={$row->taskId} and gid={$gid}";
            } else {
                $sql = "INSERT INTO {$tb} (gid, taskId,pro) VALUES ({$gid}, {$row->taskId},'{$proJson}')";
            }
            $rs = oo::commonOprDb('games')->query($sql);
        }

        oo::commonOprRedis('games')->delete(okeys::LuckyDiceWheelGroupsConfig());

        return $rs ? $rs : 0;
    }

    //endregion
}
