<?php
class JsonModel extends CI_Model
{
    public $staticPath = "./public/game/config/";
    public function __construct(){
        parent::__construct();
        $this->load->model('oo');
    }

    public function SaveJson($data,$filename){
        $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}";
        $data = json_decode(json_encode($data,JSON_NUMERIC_CHECK), true);
        $ret = file_put_contents($filepath, json_encode($data,JSON_UNESCAPED_UNICODE));

        $dir = str_replace("./","",$dir);
        $file_path = str_replace("\\","/",FCPATH . $dir.$filename);
        oo::commonOprModel('common')->upToOss($dir.$filename,$file_path);

        return $ret;
    }

    /**
     * 获取静态配置文件内容
     * @param $configName string
     * @return string
     */
    public function getStaticConfig($configName){
        $dir = $this->staticPath;
        $filename = oo::commonOprRedis('games')->hGet(okeys::StaticConfig(), $configName);
        if(empty($filename)){
            $tb = otable::StaticConfig();
            $sql = "SELECT path FROM {$tb} WHERE config='{$configName}'";
            $ret = oo::commonOprDb('slavedb')->getOne($sql, 1);
            if(empty($ret['path'])){
                return '';
            }
            $filename = $ret['path'];
            oo::commonOprRedis('games')->hSet(okeys::StaticConfig(), $configName, $filename);
        }
        $filepath = "{$dir}{$filename}";
        $ret = file_get_contents("{$filepath}");
        return $ret ? (array)json_decode($ret, true) : '';
    }

    /**
     * 設置静态配置文件
     * @param $configName
     * @param $filename
     * @return mixed
     * Created by: Owen
     * Created on: 2020/4/29 19:56
     */
    public function setStaticConfig($configName,$filename){
        $tb  = otable::StaticConfig();
        $sql1 = "SELECT * FROM {$tb} where config='{$configName}'";
        $res = oo::commonOprDb('games')->getOne($sql1,1);
        if(!empty($res)){
            $sql = "UPDATE {$tb} SET path='{$filename}' WHERE config='{$configName}'";
            $ret = oo::commonOprDb('games')->query($sql);
        }else{
            $sql = funs::db_insertSQL($tb,["config"=>$configName,"path"=>$filename]);
            $ret = oo::commonOprDb('games')->query($sql);
        }
        $cache = oo::commonOprRedis('games')->hSet(okeys::StaticConfig(),$configName,$filename);
        return min($ret,$cache);
    }

    /**
     * 礼包配置
     * Created by: Owen
     * Created on: 2020/7/6 19:12
     */
    public function giftWeightsJson(){
        $tb = otable::GiftTrigger();
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $json['condition'] = $ret;
        $tb = otable::goodsCrazy();
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb} WHERE gtype=16",MYSQLI_ASSOC);
        $good = [];
        foreach ($ret as $row){
            $reward = json_decode($row['gbaseReward'],true);
            $propsTemp = $reward['props'];
            foreach ($propsTemp as $key=>$p){
                $pConfig = oo::commonOprModel('config')->getChestData($p['propsId']);
                if($pConfig){
                    $propsTemp[$key]['value'] = $pConfig;
                }
            }
            $temp = [
                'gid'        => $row['gid'],
                'pid'        => $row['gpid'],
                'coins'      => [
                    'gid'  => oo::commonOprModel('config')->coinsToGid($reward['coins']['coins']),
                    'bet'  => $reward['coins']['bet']
                ],
                'spins'      => $reward['spins'],
                'props'      => $propsTemp,
                'price'      => "$".$row['gprice'] ,
                'priceNum'   => (string)$row['gprice'],
                'sku'        => $row['gsku'],
                'isoSku'     => str_replace('gworld.cc','astak.crazyspin',$row['gsku']),
                'ggameid'    => $row['ggameid'],
                'gdiscount'  => $row['gdiscount'],
                'priceDollar'=> '$',
                'addRatio'   => $row['gaddRatio'],
                'expire'     => $row['gExpire'],
                'max'        => $row['gMax'],
            ];
            if(!empty($row['gShowCountry'])){
                $temp['countryCode'] = explode(',',$row['gShowCountry']);
            }
            if(!empty($row['gShowGroup'])){
                $temp['gShowGroup'] = explode(',',$row['gShowGroup']);
            }
            if(!empty($row['gShowGroupSS'])){
                $temp['gShowGroupSS'] = explode(',',$row['gShowGroupSS']);
            }
            $good[] = $temp;
        }
        $json['goods'] = $good;
        $tb = otable::GiftWeights();
        $ret= oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        foreach ($ret as $key=>$row){
            $ret[$key]['data'] = json_decode($row['data'],true);
        }
        $json['weights'] = $ret;
        $json['openGiftPack'] = oo::commonOprModel('config')->getSysCon("giftPack","openGiftPack");
        $configName = "GiftPackageConfig";
        $filename   = "GiftPackageConfig".time().".json";
        self::SaveJson($json,$filename) && self::setStaticConfig($configName,$filename);
    }

    /**
     * 建筑价格
     * Created by: Owen
     * Created on: 2020/7/6 19:13
     */
    public function levelCoinConfig(){
        $tb = otable::coinConfig();
        $ret = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}");
        $json = [];
        foreach ($ret as $row) {
            $stage_reward = json_decode($row['stage_reward'],true);
            foreach ($stage_reward as &$item) {
                foreach ($item as &$item2) {
                    foreach ($item2 as &$item3) {
                        $item3 = [
                            "propsId" => $item3['propsId'],
                            "num" => $item3['num'],
                            "jokerCardExpireTime" => 0,
                            "cards" => null,
                            "chestProps" => null,
                            "skinResourceId" => 0,
                            "skin" => 0,
                        ];
                    }
                }
            }
            $json[] = [
                'level' => $row['levelId'],
                'data' => json_decode($row['coinConfig'],true),
                'stage_reward' => $stage_reward,
            ];
        }
        $filename   = "levelConfig".time().".json";
        self::SaveJson($json,$filename) && self::setStaticConfig("Level",$filename);
    }

    public static function saveShareConfigJson(){
        $tb  = otable::shareConfig();
        $baseTb  = otable::shareBaseConfig();
        $ret  = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$tb}",MYSQLI_ASSOC);
        $ret  = array_column($ret,NULL,"key");
        $ret2  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$baseTb}",MYSQLI_ASSOC);
        $tbConf2 = otable::shareConfig2();
        $retInvite  = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$tbConf2} WHERE `type`='invite'",MYSQLI_ASSOC);

        //$inviteConf = oo::commonOprDb('slavedb')->getOne("SELECT * FROM ");

        foreach ($ret as $key=>$row){
            $reward = json_decode($row['reward'],true);
            $track  = json_decode($row['track'],true);
            $abTest = json_decode($row['abTest'],true);
            $actImg = $row['actImg'] ? (array)json_decode($row['actImg'],true) : [];
            $json[$key] = [
                //'maxTimes'     => $row['maxTimes'],
                //'reward'       => $reward,
                //'intervalTime' => $row['intervalTime'],
                //'show'         => $row['show'],
                'shareType'    => $row['shareType'],
                'abTest'       => $abTest,
                'track'        => $track,
                'actImg'       => $actImg,
                'intervalTime' => $row['intervalTime'],
            ];
            if($row['key'] == 'INVITE_FRIEND'){
                $json[$key]['reward'] = (array)json_decode($retInvite['reward'], true);
                $json[$key]['intervalTime'] = $retInvite['intervalTime'];
                $json[$key]['maxTimes'] = $retInvite['maxTimes'];
                $json[$key]['show'] = $retInvite['show'];
            }
        }
        $json['maxTimes'] = (int)$ret2['maxTimes'];
        $json['reward'] = [["propsId"=>15,"num" => (int)$ret2['reward']]];
        $json['show'] = (int)$ret2['show'];
        $json['intervalTime'] = (int)$ret2['intervalTime'];

        //删除公共配置
        oo::commonOprRedis('games')->delete(okeys::shareBaseConfig());
        //删除
        oo::commonOprRedis('games')->delete(okeys::shareConfig(3));

        $filename = "ShareConfig".time().".json";
        oo::commonOprModel("json")->SaveJson($json,$filename) && oo::commonOprModel("json")->setStaticConfig("Share",$filename);
        oo::commonOprModel("language")->setLangJson();
    }
}
