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

/**
 *	破产统计相关
 */
class Card extends MY_Controller{

    public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    //宝箱配置
    private $pro_title = ['类型'
        ,'一星级概率'
        ,'二星级概率'
        ,'三星级概率'
        ,'四星级概率'
        ,'五星级概率'
        ,'金卡数量(-1,不设限制)'
        ,'黑金卡数量(-1,不设限制)'];
    //宝箱类型
    private $pro_type = [
        1=>'木质宝箱',2=>'白银宝箱',3=>'黄金宝箱',
        51=>'限时木质宝箱',52=>'限时白银宝箱',53=>'限时黄金宝箱',
        4=>'魔法宝箱',5=>"偷出卡片",6=>'完成任务',10=>"绿宝箱",11=>"蓝宝箱",12=>"红宝箱",19=>"小丑宝箱",
        20=>"狐狸宝箱(弃用)",21=>"钻石宝箱(弃用)",29=>"圣诞宝箱(弃用)",30=>"麋鹿宝箱(弃用)"
    ];

    private $reward_type = ['卡组ID'
        ,'金币奖励'
        ,'体力奖励'];
    private $process_type = ['进度ID'
        ,'金币奖励'
        ,'体力奖励'];


    public $_langList;
    public function __construct(){
        date_default_timezone_set("Asia/Shanghai");
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->env = get_cookie($this->_wenenv);
        $this->_langList = oo::cfg('lang')['en_zh'];
        $this->_langList['rou'] = $this->_langList['ro'];
        unset($this->_langList['ro']);
    }

    /**
     * 宝箱概率配置
     * Created by: Cassie Lee
     * Created on: 2019/6/11 10:38
     * Description:
     */
    public function pro(){
        $title = $this->pro_title;
        $type = $this->pro_type;

        $tb = otable::cardPro_Config();
        $rs = oo::commonOprDb('slavedb')->getAll("SELECT * from {$tb} WHERE 1",1);
        $arr = [];
        foreach ($rs as $k=>$v){
            $arr[] = [
                'type' => $v['type'],
                'pro'  => json_decode($v['star_pro'],true),
                'maxGoldCard' => $v['maxGoldCard'],
                'maxBlackGoldCard' => $v['maxBlackGoldCard'],
            ];
        }

        $data['title'] = $title;
        $data['type'] = $type;
        $data['list'] = $arr;

        $this->load->view('card/pro', $data);

    }
    /**
     * 宝箱概率配置--action
     * Created by: Cassie Lee
     * Created on: 2019/6/11 10:38
     * Description:
     */
    public function actionPro(){
        $postData = $this->input->post();
        $data = json_decode($postData['data'],true);
        $tb = otable::cardPro_Config();
        foreach ($data as $row){
            $temp = json_encode($row['data']);
            $rs = oo::commonOprDb('games')->query("UPDATE {$tb} SET star_pro='{$temp}',maxGoldCard='{$row['maxGoldCard']}',maxBlackGoldCard='{$row['maxBlackGoldCard']}' WHERE type={$row['type']}");
            oo::commonOprRedis('games')->delete(okeys::CardTypePro($row['type']));
            oo::commonOprRedis('games')->delete(okeys::MaxGoldCard($row['type']));
        }
        if($rs == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function reward(){
        $title = $this->reward_type;
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'getReward';

        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        $retData = json_decode($retData,1);

        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }

        $data['title'] = $title;
        $data['list'] = $list;

        $this->load->view('card/reward', $data);
    }

    public function actionReward(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'actionReward';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }

    public function process(){
        $title = $this->process_type;
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'getProcess';

        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        $retData = json_decode($retData,1);

        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }

        $data['title'] = $title;
        $data['list'] = $list;

        $this->load->view('card/process', $data);
    }

    public function actionProcess(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'actionProcess';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $this->actionSyncJson('CardCollect'.time().'.json');
            return $this->response(0, '操作成功');
        }
    }

    public function group($type){
        $title = $group_type = [
            '卡组ID'
        ];

        $_langList = oo::cfg('lang')['lang_card_group'];

        foreach ($_langList as $text){
            $text = strtr($text, ['卡组名称' => '','('=>'',')'=>'']);
            $title[]  = $text;
        }
        $title[] = $group_type[] = '金币奖励';
        $title[] = $group_type[] = '体力奖励';
        $title[] = $group_type[] = '解锁等级';
        $title[] = $group_type[] = "粮食奖励";
        $title[] = $group_type[] = "经验奖励";
        $title[] = $group_type[] = "标题颜色";
        $title[] = $group_type[] = '操作';
        $posts = $this->postData;
        $posts['type'] = $type;
        $posts['mod'] = 'card';
        $posts['act'] = 'getGroup';

        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        $retData = json_decode($retData,1);

        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }

        $data['type'] = $type;
        $data['name'] = $type == 0 ? "常规卡组" : "限时卡组";
        $data['title'] = $title;
        $data['list'] = $list;
        $data['_langList'] = $_langList;
//        echo json_encode($list);die;
        $data['tableColumnMapping'] = array_merge(['cgid'], (array)array_keys($_langList), ['cg_coin_reward','cg_spin_reward','cg_lock_rank','cg_petFeed_reward','cg_petExp_reward','cg_title_img_id']);
        $this->load->view('card/group', $data);
    }

    //限时卡组主题配置
    public function limitGroupTheme()
    {
        $data = [];

        $tb = otable::cardgroup_limit_theme_config();
        $sql = "SELECT * FROM {$tb} WHERE 1";
        $data['list'] = oo::commonOprDb('slavedb')->getAll($sql);

        $tb2 = otable::cardgroup_config();
        $sql = "SELECT `cgid`,`cg_name_zh` FROM {$tb2} WHERE cg_type= 1";
        $data['cgidList'] = oo::commonOprDb('slavedb')->getAll($sql);

        $this->load->view('card/limitGroupTheme', $data);
    }

    //限时卡组主题配置
    public function limitGroupThemeUpdate()
    {
        $postData = $this->input->post('config');

        $tb = otable::cardgroup_limit_theme_config();
        $sql = "SELECT `id` from {$tb} WHERE 1";
        $ret = oo::commonOprDb('games')->getAll($sql, 1);
        $idList = array_column($ret, 'id');

        foreach ($postData as $oneConfig) {
            $id = $oneConfig['id'];
            $cgids = json_encode($oneConfig['cgids']??[], JSON_NUMERIC_CHECK);
            if (in_array($id, $idList)) {
                $sql = "UPDATE {$tb} SET theme_res='{$oneConfig['theme_res']}',cgids='{$cgids}' WHERE id={$id}";
                oo::commonOprRedis('games')->delete(okeys::limitGroupCardThemeConfig($id));
            } else {
                $sql = "INSERT INTO {$tb} (`id`,`theme_res`, `cgids`) VALUES ({$id},'{$oneConfig['theme_res']}','{$cgids}')";
            }

            $flag = oo::commonOprDb('games')->query($sql);
            if (!$flag) {
                return $this->response(1, '操作失败');
            }
        }
        return $this->response(0, '操作成功');
    }

    public function exclusivegroup(){
        $title = [
            '卡组ID'
        ];
        foreach ($this->_langList as $text){
            $title[]  = $text;
        }
        $title[] = '奖励头像框ID';
        $title[] = '操作';

        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'getExclusiveGroup';

        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);

        $retData = json_decode($retData,1);

        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }

        $data['title'] = $title;
        $data['list'] = $list;
        $data['_langList'] = $this->_langList;
        $this->load->view('card/exclusivegroup', $data);
    }

    public function actionGroup($type)
    {
        $postData = $this->input->post();

        $data = json_decode($postData['data'], true);
        $tb = otable::cardgroup_config();
        $sql = "SELECT `cgid` from {$tb} WHERE cg_type={$type}";
        $ret = oo::commonOprDb('slavedb')->getAll($sql);
        $cgids = array_column($ret, 'cgid');

        foreach ($data as $row) {
            if (!in_array($row['cgid'], $cgids)) {
                continue;
            }
            $sql = funs::db_updateSQL($tb, $row['data'], "cgid={$row['cgid']}");
            $flag = oo::commonOprDb('games')->query($sql);
            if (!$flag) {
                return $this->response(1, "更新失败，卡组ID：{$row['cgid']}");
            }
        }
        oo::commonOprRedis('games')->delete(okeys::CardGroupConfig());

        $this->actionSyncJson('CardCollect' . time() . '.json');
        return $this->response(0, '操作成功');
    }

    public function actionExclusiveGroup(){
        $postData = $this->input->post();
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'actionExclusiveGroup';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $this->actionSyncJson('CardCollect'.time().'.json');
            return $this->response(0, '操作成功');
        }
    }

    public function card($cgid){
        $title = ['卡片ID'
        ];
        $_langList = oo::cfg('lang')['lang_card'];

        foreach ($_langList as $text){
            $text = strtr($text, ['卡片名称' => '','('=>'',')'=>'']);
            $title[]  = $text;
        }

//        $title[] = '卡组ID';
        $title[] = '卡片位置';
        $title[] = '卡片星级';
        $title[] = '解锁等级';
        $title[] = '图片ID';
        $title[] = '金卡(1普通2金3黑金)';
        $title[] = '权重';
        $title[] = '配图';
//        $title[] = '上传图片';

        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'getCard';
        $posts['cgid'] = $cgid;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);

        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }

        $data['title'] = $title;
        $data['list'] = $list;
        $data['cgid'] = $cgid;
        $data['_langList'] = $_langList;
        $data['tableColumnMapping'] = array_merge(['ciid'], (array)array_keys($_langList), ['cgposition','ci_star_rank','ci_lockRank','ci_picture','grade','weights']);
        $this->load->view('card/card', $data);
    }

    public function exclusivecard($cgid){
        $title = ['卡片ID'
        ];

        foreach ($this->_langList as $text){
            $title[]  = $text;
        }
        $title[] = '卡组ID';
        $title[] = '卡片位置';
        $title[] = '卡片星级';
        $title[] = '解锁等级';
        $title[] = '图片ID';

        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'getExclusiveCard';
        $posts['cgid'] = $cgid;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);

        if(!empty($list)){
            $list = [];
        }else{
            $list = $retData['data'];
        }

        $data['title'] = $title;
        $data['list'] = $list;
        $data['cgid'] = $cgid;
        $data['_langList'] = $this->_langList;
        $this->load->view('card/exclusivecard', $data);
    }

    public function actionCard()
    {
        $postData = $this->input->post();
        $data = json_decode($postData['data'], true);

        $temp = [];
        foreach ($data as $key => $row) {
            if (empty($temp[$row['data']['cgposition']])) {
                $temp[$row['data']['cgposition']] = 1;
            } else {
                return $this->response(1, '' . $row['ccid'] . '卡片位置重复');
            }
        }

        $tb = otable::cardinfo_config();
        foreach ($data as $row) {
            $sql = funs::db_updateSQL($tb, $row['data'], "ciid={$row['ciid']}");
            $rs = oo::commonOprDb('games')->query($sql);
            if (!$rs) {
                return $this->response(1, "数据更新失败，ID：{$row['ciid']}");
            }
        }

        self::updateCardCache();
        $this->actionSyncJson('CardCollect' . time() . '.json');
        return $this->response(0, "操作成功");
    }

    private function updateCardCache()
    {
        $tb = otable::cardinfo_config();
        $sql = "SELECT * FROM {$tb}";
        $ret = oo::commonOprDb('slavedb')->getAll($sql, 1);
        if (!empty($ret)) {
            $cacheKey = okeys::CardConfig();
            oo::commonOprRedis('games')->delete($cacheKey);
            foreach ($ret as $k => $v) {
                $arr[$v['ciid']] = $v;
                $cache[$v['ciid']] = json_encode($v);
            }
            oo::commonOprRedis('games')->hMset($cacheKey, $cache);
        }
    }

    public function actionExclusiveCard(){
        $postData = $this->input->post();
        $val = json_decode($postData['data'],true);
        $temp = [];

        foreach ($val as $key=>$row){
            if(empty($temp[$row['data']['cgposition']])){
                $temp[$row['data']['cgposition']] = 1;
            }else {
                return $this->response(1, ''.$row['ccid'].'卡片位置重复');
            }
        }
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'actionExclusiveCard';
        $posts['data'] = $postData['data'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            $this->actionSyncJson('CardCollect'.time().'.json');
            return $this->response(0, '操作成功');
        }
    }

    public function actionSyncJson($filename = "CardCollect.json"){
        $posts = $this->postData;
        $posts['mod'] = 'card';
        $posts['act'] = 'makeCardJson';
        $posts['filename'] = $filename;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,1);
        if($retData['code'] == 1){
            $data = $retData['data'];

            $dir = $this->staticPath;
            if (!is_dir($dir))
            {
                $old = umask(0);
                //mkdir($dir, PRODUCTION_SERVER ? 0775 : 0777, true);
                mkdir($dir,0775 , true);
                umask($old);
            }
            $filepath = "{$dir}{$filename}";
            file_put_contents($filepath, json_encode($data));
        }
    }

    public function refreshCardMd5(){
        oo::commonOprModel('Filemd5')->makeCardMd5();
        return $this->response(0, '操作成功');
    }

    public function getGoldenCard(){
        $tb = otable::CardInfo();
        $rs = oo::commonOprDb('slavedb')->getAll("SELECT * from {$tb} WHERE grade >= 2",MYSQLI_ASSOC);
        return $this->response(0, '操作成功',$rs);
    }
}