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

/**
 * 聊天
 */
class Announcement extends MY_Controller
{
    public $postData = array('frombg' => 1, 'lid' => 1, 'sid' => 1);
    public $langType = ['ZH','EN','TW','DE','ES','FR','PT','TH','ID','VN','NO'];
    public function __construct()
    {
        date_default_timezone_set("Asia/Shanghai");
        parent::__construct();
        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->load->library('pagination');
        $this->env = get_cookie($this->_wenenv);

        $this->langType = oo::cfg('lang')['lang_upper2'];
    }

    public $staticPath = "./public/game/config/";
    public $clientIni = "crazycoin/cfg/init.bin";

    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}";
        file_put_contents($filepath, json_encode($data,JSON_NUMERIC_CHECK));

        if(method_exists($this->common,'upToOss')){
            $dir = str_replace("./","",$dir);
            $file_path = str_replace("\\","/",FCPATH . $dir.$filename);

            $this->common->upToOss($dir.$filename,$file_path);
        }
    }
    //系统公告
    public function index($id = 0){
        $tb = otable::announcement();
        if($id){
            $sql = "SELECT * FROM {$tb} WHERE id={$id}";
            $retData = oo::commonOprDb('slavedb')->getOne($sql,MYSQLI_ASSOC);
            $retData['title'] = strtr($retData['title'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData['content'] = strtr($retData['content'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData['time_desc'] = strtr($retData['time_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData['range_desc'] = strtr($retData['range_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
        }else{
            $sql = "SELECT * FROM {$tb}";
            $retData = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
        }

        if($id != 0){
            return $this->response(0, '操作成功',$retData);
        }
        $defaultContent = [];
        foreach ($retData as $k => $v){
            $retData[$k]['title'] = strtr($v['title'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData[$k]['content'] = strtr($v['content'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData[$k]['time_desc'] = strtr($v['time_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData[$k]['range_desc'] = strtr($v['range_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $content = json_decode($retData[$k]['content'], true);
            foreach ($this->langType as $langKey => $lang){
                $content[$langKey] = $content[$langKey] ?? ($content['EN'] ?? '');
                $defaultContent[$langKey] = '';
            }
            $retData[$k]['content'] = json_encode($content);
            $retData[$k]['wlist'] = $v['wlist'] ?? [];
        }
        $date = date('Y-m-d');
        $defaultInfo = [
            'id' => 0,
            'title' => '公告',
            'content' => json_encode($defaultContent),
            'stime' => strtotime($date),
            'etime' => strtotime($date),
            'device' => 0,
            'usertype' => 0,
            'type' => 0,
            'wlist' => '',
            'blist' => '',
            'time_desc' => '',
            'range_desc' => '',
        ];
        $data['list'] = $retData;
        $data['lang'] = $this->langType;
        $data['defaultInfo'] = json_encode($defaultInfo, 256);
        $this->load->view('announcement/index', $data);
    }
    public function save(){
        $postData = $this->input->post();
        $stime = $postData['sdate'].' '.$postData['stime'];
        $etime = $postData['edate'].' '.$postData['etime'];
        $post = [
            'stime'   =>strtotime("$stime"),
            'etime'   =>strtotime("$etime"),
            'type'    =>intval($postData['type']),
            'wlist'  =>$postData['wlist'] ?? '',
            'blist'  =>$postData['blist'] ?? '',
            'usertype'=>$postData['usertype'],
            'device'  =>$postData['device'],
            'title'   =>$postData['title'] ?? '',
            'content' =>json_encode($postData['content'],256),
        ];

        $post['title'] = strtr($post['title'], ["\r\n" => '',"\t" => '',"\n" => '']);
        $post['content'] = strtr($post['content'], ["\r\n" => '',"\t" => '',"\n" => '']);
        $post['wlist'] = strtr($post['wlist'], ["\r\n" => '',"\t" => '',"\n" => '']);
        $post['blist'] = strtr($post['blist'], ["\r\n" => '',"\t" => '',"\n" => '']);

        $w = '';
        if(!empty($postData['id'])){
            $w = " id={$postData['id']}";
        }

        $tb = otable::announcement();
        if(isset($postData['id'])&&intval($postData['id'])>0){
            $sql = funs::db_updateSQL($tb,$post,$w);
            $retData=oo::commonOprDb('games')->query($sql);
            $id = $postData['id'];
        }else{
            $sql = funs::db_insertSQL($tb,$post);
            $retData=oo::commonOprDb('games')->query($sql);
            $id = oo::commonOprDb('games')->insertID();
        }
        $temp = [
            'id'      =>$id,
            'stime'   =>$post['stime'],
            'etime'   =>$post['etime'],
            'type'    =>$post['type'],
            'wlist'  =>$post['wlist'],
            'blist'  =>$post['blist'],
            'usertype'=>$post['usertype'],
            'device'  =>$post['device'],
            'title'   =>$post['title'],
            'content' =>$postData['content'],
        ];

        if(!$retData){
            return $this->response(1, '操作失败');
        }else{
            $hmsetArr = [];
            foreach ($temp as $k => $v){
                if(is_scalar($v))
                    $hmsetArr[$k] = $v;
                else
                    $hmsetArr[$k] = json_encode($v);
            }
            oo::commonOprRedis('games')->hMSet(okeys::announcementNew($id),$hmsetArr);
            oo::commonOprRedis('games')->hSet(okeys::announcement(),$id,json_encode($temp,256));
            return $this->response(0, '操作成功');
        }
    }
    public function del(){
        $postData = $this->input->post();

        $id= intval($postData['id']);
        $tb = otable::announcement();
        $sql = "DELETE FROM {$tb} WHERE id={$id}";
        $ret = oo::commonOprDb('games')->query($sql);
        if(!$ret){
            return $this->response(1, '操作失败'.$id);
        }else{
            oo::commonOprRedis('games')->hDel(okeys::announcement(),$id);
            return $this->response(0, '操作成功');
        }
    }

    //更新公告
    public function indexNew($id = 0){
        $tb = otable::announcement(2);
        if($id){
            $sql = "SELECT * FROM {$tb} WHERE id={$id}";
            $retData = oo::commonOprDb('slavedb')->getOne($sql,MYSQLI_ASSOC);
            $retData['title'] = strtr($retData['title'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData['content'] = strtr($retData['content'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData['time_desc'] = strtr($retData['time_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData['range_desc'] = strtr($retData['range_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
        }else{
            $sql = "SELECT * FROM {$tb}";
            $retData = oo::commonOprDb('slavedb')->getAll($sql,MYSQLI_ASSOC);
        }
        if($id != 0){
            return $this->response(0, '操作成功',$retData);
        }
        foreach ($retData as $k => $v){
            $retData[$k]['title'] = strtr($v['title'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData[$k]['content'] = strtr($v['content'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData[$k]['time_desc'] = strtr($v['time_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
            $retData[$k]['range_desc'] = strtr($v['range_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
        }
        $posts = $this->postData;
        $data['list'] = $retData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'getPropsConfig';
        $url          = $this->config->item('officialUrl');
        $retData      = json_decode($this->curl->req($url, $posts),true);
        $data['lang']      = array_keys(oo::commonOprModel('config')->getCurLangs());
        $data['idData']    = $retData['props'];
        $data['versions']  = oo::commonOprModel('config')->versions;
        $data['chestSkin'] = array_column(oo::commonOprModel('config')->chestSkin(),'name','id');
        $data['href']  = "/filemanager.php?fm_usr=announcement&fm_pwd=announcement&userName=".get_cookie('chinesename');
        $this->load->view('announcement/indexNew', $data);
    }
    public function saveNew() {
        $p = $this->input->post();
        $reward=[];
        if(!empty($p['reward'])&&!empty($p['reward']['props'])){
            foreach($p['reward']['props']['propsId'] as $k=>$v){
                $reward[$k] = [
                    'propsId' => $v,
                    'num' => isset($p['reward']['props']['num'][$k]) ? $p['reward']['props']['num'][$k] : 1,
                ];
                if($v == 19){
                    $reward[$k]['skin'] = isset($p['reward']['props']['skin'][$k]) ? $p['reward']['props']['skin'][$k] : 0;
                }
            }
            $reward = ['props' => array_values($reward)];
        }
        $p['reward'] = empty($reward) ? '[]' : json_encode($reward);
        $p['content'] = json_encode($p['content'], JSON_UNESCAPED_UNICODE);
        $p['time_desc'] = json_encode($p['time_desc'], JSON_UNESCAPED_UNICODE);
        $p['range_desc'] = json_encode($p['range_desc'], JSON_UNESCAPED_UNICODE);
        $p['stime'] = strtotime($p['sdate'].' '.$p['stime']);
        $p['etime'] = strtotime($p['edate'].' '.$p['etime']);
        $p['version'] = json_encode((array)$p['version']);
        $p['title'] = json_encode($p['title'], JSON_UNESCAPED_UNICODE);
        $p['is_force'] = (int)$p['is_force'];
        $p['plat'] = (int)$p['plat'];

        $p['title'] = strtr($p['title'], ["\r\n" => '',"\t" => '',"\n" => '']);
        $p['content'] = strtr($p['content'], ["\r\n" => '',"\t" => '',"\n" => '']);
        $p['time_desc'] = strtr($p['time_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
        $p['range_desc'] = strtr($p['range_desc'], ["\r\n" => '',"\t" => '',"\n" => '']);
        if(!empty($p['img'])){
            if(!file_exists(APPPATH.'../public/game/image/announcement/'.$p['img'])){
                return $this->response(1, '资源不存在');
            }
        } else {
            $p['img'] = '';
        }
        if(empty($p['newVersion'])||empty($p['range_desc'])||empty($p['time_desc'])||empty($p['title'])||empty($p['content'])||empty($p['stime'])||empty($p['etime'])){
            return $this->response(1, '请完整填写信息');
        }
        $tb = otable::Announcement(2);
        $time = time();
        $adminid = $this->session->userdata('username');
        if(!empty($p['id'])){
            $sql = "UPDATE {$tb} SET title='{$p['title']}',content='{$p['content']}',stime='{$p['stime']}',etime='{$p['etime']}',device='{$p['device']}',reward='{$p['reward']}',fansUrl='{$p['fansUrl']}',admin_user='{$adminid}',time_desc='{$p['time_desc']}',range_desc='{$p['range_desc']}',newVersion='{$p['newVersion']}',version='{$p['version']}',topic='{$p['topic']}',is_force='{$p['is_force']}',img='{$p['img']}',plat='{$p['plat']}' WHERE id={$p['id']}";
        }else{
            $sql = "INSERT INTO {$tb} (title,content,stime,etime,device,reward,fansUrl,admin_user,createtime,time_desc,range_desc,version,topic,newVersion,is_force,img,plat) VALUES ('{$p['title']}','{$p['content']}',{$p['stime']},{$p['etime']},'{$p['device']}','{$p['reward']}','{$p['fansUrl']}','{$adminid}','{$time}','{$p['time_desc']}','{$p['range_desc']}','{$p['version']}','{$p['topic']}','{$p['newVersion']}','{$p['is_force']}','{$p['img']}','{$p['plat']}')";
        }
        $ret = oo::commonOprDb('games')->query($sql);
        if(!$ret){
            return $this->response(1, '操作失败');
        }else{
            oo::commonOprRedis('games')->delete(okeys::announcement(2));
            return $this->response(0, '操作成功');
        }
    } 

    //停服公告
    public function stopServiceConfig(){
        $announcementTb = otable::announcement();
        $table = otable::commonConfig();
        $basicKey = okeys::stopServiceConfig();
        $typeKey = $basicKey;
        $config = oo::commonOprRedis('games')->get($basicKey);
        if(empty($config)){
            $config = oo::commonOprDb('slavedb')->getOne("select * from {$table} where type='{$typeKey}' limit 1");
            $config = $config['conf'];
        }
        $config = empty($config) ? [] : (@json_decode($config, true) ?? []);
        $types = [
            1 => '不停服，任何人能进',
            2 => '停服，任何人不能进',
            3 => '半停服，公告白名单能进',
        ];
        $announcements = oo::commonOprDb('slavedb')->getAll("SELECT * FROM {$announcementTb}");
        $announcements = array_column($announcements, 'title', 'id');
        $columns = [
            'type' => $this->inputField('type','停服状态', 'selector', $config['type'] ?? 0, $types),
            'announcement_id' => $this->inputField('announcement_id','关联公告', 'selector', $config['announcement_id'] ?? 0, $announcements),
            'url' => $this->inputField('url','跳转地址', 'text', $config['url'] ?? "", ""),
        ];
        $data = [
            'config' => $config,
            'columns' => $columns,
        ];
        $this->load->view('announcement/stopService', $data);
    }
    public function saveStopServiceConfig(){
        $input = $this->input->post();
        if(empty($input['type']) || empty($input['announcement_id']))$this->response(__LINE__ * -1, '提交参数异常，请重新选择');
        $table = otable::commonConfig();
        $typeKey = okeys::stopServiceConfig();
        $config = json_encode($input);
        $configName = '停服配置';
        $oldData = [];
        if(empty($input['id'])){
            $res = oo::commonOprDb('games')->query("insert into {$table} (`type`, `name`, `conf`)  values ('{$typeKey}', '{$configName}', '{$config}')");
            $input['id'] = oo::commonOprDb('games')->insertID();
            $config = json_encode($input);
        }else{
            $oldData = oo::commonOprDb('slavedb')->getOne("SELECT * FROM {$table} where type='{$typeKey}'");
            $oldData = json_decode($oldData['conf'], true);
        }
        if(!isset($oldData['type']) || ($oldData['type'] != $input['type'])){
            $this->sendNsqMsg('stopservie_config', $config);
        }
        $res = oo::commonOprDb('games')->query("update {$table} set  `conf`='{$config}'  where id={$input['id']} ");
        if(!$res)$this->response(__LINE__ * -1, '保存失败');
        oo::commonOprRedis('games')->set($typeKey, $config);

        // 生成停服动态
        $content = "";
        if($input['type']>1){
            $tb = otable::announcement();
            $sql ="SELECT `title`,`content`,`wlist` FROM {$tb} WHERE id={$input['announcement_id']}";
            $content = oo::commonOprDb('games')->getOne($sql,1);
            $content['content'] = json_decode($content['content'],true);
            if($input['type']==3&&$content['wlist']){
                $content['wlist']=explode(',',$content['wlist']);
            }else{
                $content['wlist'] = [];
            }
        }
        $datas=[
            "type" => $input['type'],
            "content" =>$content,
            "url"=> $input['url'],
        ];
        $filename = "StopConfig".time().".json";
        $ret[0] = oo::commonOprModel("json")->SaveJson($datas, $filename);
        if($ret[0]){
            //更新缓存
            $ret[1]=oo::commonOprModel("json")->setStaticConfig("StopConfig", $filename);
            //刷新CDN
            $ret[2] = oo::commonOprModel('common')->CdnRefreshUrl($filename);
        }
        $this->response(1, '保存成功:'.json_encode($ret));
        $this->response(1, '保存成功'."-cdn结果：{$ret}");
    }
    // 刷新client ini
    public function RefreshClientIni(){
        $ret = oo::commonOprModel('common')->CdnRefreshUrl($this->clientIni);
        $this->response(1, '刷新成功'."-cdn结果：{$ret}");
    }
//===========================停服公告(弃用)================================
    public function announcement(){
        $posts = $this->postData;
        $posts['mod'] = 'Config';
        $posts['act'] = 'actionAnnouncement';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        
        $json = file_get_contents($this->staticPath.$retData);
        if($json){
            $data = json_decode($json,true);
        }
        $data['lang'] = $this->langType;
        $this->load->view('announcement/noice', $data);
    }

    public function actionAnnouncement(){
        $postData = $this->input->post();
        $stime = $postData['sdate'].' '.$postData['stime'];
        $etime = $postData['edate'].' '.$postData['etime'];
        $filename = 'Announcement'.time().'.json';
        $posts = $this->postData;

        $data = [
            'filename'=>$filename,
            'stime'=>strtotime($stime),
            'etime'=>strtotime($etime),
            'content'=>$postData['content'],
            "type"=>1,
            "wlist"=>$postData['wlist'],
        ];

        $posts['mod'] = 'Config';
        $posts['act'] = 'actionAnnouncement';
        $posts['data']= json_encode($data);
//        $posts['filename'] = $filename;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        //1.6.0后弃用json文件形式
        $json = [
            'stime'   =>strtotime($stime),
            'etime'   =>strtotime($etime),
            'content' =>$postData['content'],
        ];

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

    public function sendAnnouncementCmd(){
        $postData = $this->input->post();
        $stime = $postData['sdate'].' '.$postData['stime'];
        $etime = $postData['edate'].' '.$postData['etime'];
        $json = [
            'stime'   =>strtotime($stime),
            'etime'   =>strtotime($etime),
            'content' =>$postData['content'],
        ];
        $posts = $this->postData;
        $posts['mod']  = 'Config';
        $posts['act']  = 'sendAnnouncementCmd';
        $posts['data'] = json_encode($json);
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
            return $this->response(0, '操作成功');
        }
    }



}
