<?php
/**
 * 版本更新管理
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Gameupdate extends MY_Controller{

    public $postData = array('frombg' => 1, 'mod' => '', 'act' => '', 'lid' => 1, 'sid' => 1);
    public $data = array('referer' =>'', 'refresh' => 'false', 'state' => 'error', 'message' => '');
    public $gu_updateurl = array(
        1 => 'https://play.google.com/store/apps/details?id=com.superant.crazygod',
        2 => 'https://itunes.apple.com/us/app/%E0%B9%84%E0%B8%9E-%E0%B9%80%E0%B8%97-%E0%B8%81%E0%B8%8B-%E0%B8%AA%E0%B8%8B-%E0%B9%80%E0%B8%9B%E0%B8%AD%E0%B8%A3/id2017964004965884?l=zh&ls=1&mt=8',
    );
    public $gu_commonurl = array(
        1 => 'https://play.google.com/store/apps/details?id=com.superant.crazygod',
        2 => 'itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=2017964004965884',
    );
    public $gu_hotfix = array(
        1 => 'https://god.superant.cc/hotupdatefile/android/',
        2 => 'https://god.superant.cc/hotupdatefile/ios/',
    );


    public $device = [
        1=>'android',
        2=>'ios',
        3=>'vivo'
    ];

    public $_langList = ['en'=>'英文','de'=>'德语','es'=>'西班牙','fr'=>'法语','pt'=>'葡萄牙','th'=>'泰语','zh'=>'中文','tw'=>'中文（台湾）'];

    public function __construct()
    {
        parent::__construct();

        $this->load->helper('cookie');
        $this->load->library('curl');
        $this->env = get_cookie($this->_wenenv);
        $this->load->database();

        $this->device = oo::commonOprModel('config')->device;
    }

    /**
     * 首页
     */
    public function index(){
//        if(!$this->isAdmin()) {
//            redirect('permission/forbidpage');
//            exit;
//        }
        $data = array('list' => [], 'gu_updateurl' => $this->gu_updateurl, 'gu_commonurl' => $this->gu_commonurl);
        $retData = oo::commonOprModel('common')->CurlApi([
            'mod' => 'Gameupdate',
            'act' => 'getList',
        ]);
        $list = json_decode($retData, TRUE);
        if ( !empty($list) || is_array($list) ) {
            foreach ($list as $key => $value) {
                if ($value['gu_title'] && empty($value['gu_langtitle'])) {
                    $list[$key]['gu_langtitle'] = serialize(json_encode(array('th' => $value['gu_title'])));
                    $list[$key]['gu_langcontent'] = serialize(json_encode(array('th' => $value['gu_content'])));
                }
            }
            $data['list'] = $list;
            array_multisort(array_column($list,'id'),SORT_DESC,$list);
            $last = $list[0];
            $data['last'] = [
                'title'   => json_decode(unserialize($last['gu_langtitle']),true),
                'content' => json_decode(unserialize($last['gu_langcontent']),true),
            ];
        }
        $data['androidPackageList'] = $this->androidPackageList;
        $data['iosPackageList'] = $this->iosPackageList;
        $data['langList'] = array_keys($this->_langList);
        $this->load->view('gameupdate/index', $data);
    }


    /**
     *   添加更新
     */
    public function actionAdd()
    {
//        if(!$this->isAdmin()) {//如果不是管理员没有权限查看用户列表
//            redirect('permission/forbidpage');
//            exit;
//        }
        $data = $this->data;
        $guDeviceArr = $this->input->post('gu_device');
        if(empty($guDeviceArr)){
            $data['state'] = 'error';
            $data['message'] = '添加失败，请选择更新设备';
            $data['refresh'] = false;
            die(json_encode($data));
        }
        $this->postData['gu_version']  = $this->input->post('gu_version');
        $this->postData['gu_force']    = $this->input->post('gu_force');
        $this->postData['gu_isReward'] = $this->input->post('gu_isReward');
        $this->postData['gu_tips']     = $this->input->post('gu_tips');
        $this->postData['gu_reward'] = json_encode($this->input->post('gu_reward'),JSON_NUMERIC_CHECK);
        $reward = $this->input->post('gu_reward');
        if($reward['spins'] > 200){
            $data['state'] = 'error';
            $data['message'] = '添加失败，体力不能超过200';
            $data['refresh'] = false;
            die(json_encode($data));
        }
        $this->postData['gh_news'] = $this->input->post('gh_news');
        $remark = $this->input->post('remark');
        $this->postData['packageList'] = json_encode([$this->postData['gu_device']]);
        $lang = array_keys($this->_langList);
        $langTitle = $langContent = array();//多语言标题和内容
        foreach ($lang as $val) {
            $gu_title = $this->input->post('title_'.$val);
            $gu_content = $this->input->post('content_'.$val);
            $langTitle[$val] = $gu_title;
            $langContent[$val] = $gu_content;
        }

        $this->postData['gu_title'] = serialize(json_encode($langTitle));
        $this->postData['gu_content'] = serialize(json_encode($langContent));
        $this->postData['mod'] = 'Gameupdate';
        $this->postData['act'] = 'actionAdd';
        $url = $this->config->item('officialUrl');
        foreach ($guDeviceArr as $gu_device) {
            $this->postData['gu_device'] = $gu_device;
            $retData = $this->curl->req($url, $this->postData);
            $ret = json_decode($retData, TRUE);
            if( !($ret['code'] > 0) ){
                $data['state'] = 'error';
                $data['message'] = '添加失败';
                $data['refresh'] = false;
                die(json_encode($data));
            }
            $remarkData = array(
                'version_name' => $this->postData['gu_version'],
                'version_device' => $this->postData['gu_device'],
                'version_parent' => 0,
                'version_id' => $ret['id'],
                'remark' => $remark,
                'remark_name' => get_cookie('chinesename'),
                'remark_time' => time(),
            );
            $this->db->insert('updategame_remark', $remarkData);
            $this->postData['gu_tips'] && self::actionSaveJson($this->postData['gu_device']);
        }
        $data['state'] = 'success';
        $data['message'] = '添加成功';
        $data['refresh'] = true;
        die(json_encode($data));
    }

    /**
     *   编辑
     */
    public function edit($id)
    {
//        if(!$this->isAdmin()) {//如果不是管理员没有权限查看用户列表
//            redirect('permission/forbidpage');
//            exit;
//        }
        $this->postData['id'] = $id;
        $this->postData['mod'] = 'Gameupdate';
        $this->postData['act'] = 'getone';
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $this->postData);
        $ret = json_decode($retData, TRUE);
        if( !empty($ret) ){
            $ret['device'] = array_flip($this->device)[$ret['gu_device']];
            $ret['gu_reward'] = json_decode($ret['gu_reward'],true);
            //处理多语言标题, 内容
            $titleContentList = array();
            if ($ret['gu_langtitle']) {
                $gu_langtitle = unserialize($ret['gu_langtitle']);
                $gu_langcontent = unserialize($ret['gu_langcontent']);
                $tempTitleList = json_decode($gu_langtitle, 1);
                $tempContentList = json_decode($gu_langcontent, 1);
                $i = 0;
                foreach ($tempTitleList as $tempLang => $title) {
                    $titleContentList[$i]['lang'] = $tempLang;
                    $titleContentList[$i]['title'] = $title;
                    $titleContentList[$i]['content'] = $tempContentList[$tempLang];
                    $i++;
                }
            }
            $ret['titleContentList'] = $titleContentList;
        }
        $this->load->view('gameupdate/edit', $ret);
    }

    /**
     * 编辑提交
     */
    public function actionEdit()
    {
        $data = $this->data;
        $this->postData['id']          = $this->input->post('id');
        $this->postData['gu_device']   = $this->input->post('gu_device');
        $this->postData['gu_version']  = $this->input->post('gu_version');
        $this->postData['gu_tips']     = $this->input->post('gu_tips');
        $this->postData['gu_force']    = $this->input->post('gu_force');
        $this->postData['gu_isReward'] = $this->input->post('gu_isReward');
        $this->postData['gu_reward']   = json_encode($this->input->post('gu_reward'),JSON_NUMERIC_CHECK);
        $this->postData['gh_news']     = $this->input->post('gh_news');
        $this->postData['packageList'] = json_encode([$this->postData['gu_device']]);
        $gu_lang    = $this->input->post('gu_lang');
        $gu_title   = $this->input->post('gu_title');
        $gu_content = $this->input->post('gu_content');
        $this->postData['mod'] = 'Gameupdate';
        $this->postData['act'] = 'actionUpdate';
        $url = $this->config->item('officialUrl');
        //处理多语言的标题和内容
        $langTitle = $langContent = array();//多语言标题和内容
        if (is_array($gu_title)) {
            foreach ($gu_lang as $key => $val) {
                $langTitle[$val] = $gu_title[$key];
                $langContent[$val] = $gu_content[$key];
            }
        }else{//兼容老版本,只有泰语的情况
            $langTitle['th'] = $gu_title;
            $langContent['th'] = $gu_content;
        }
        $this->postData['gu_title'] = serialize(json_encode($langTitle));
        $this->postData['gu_content'] = serialize(json_encode($langContent));
        $retData = $this->curl->req($url, $this->postData);
        $ret = json_decode($retData, TRUE);
        if( $ret['code'] > 0 ){
            $data['state'] = 'success';
            $data['message'] = '编辑成功';
            $data['refresh'] = true;
        }
        $this->postData['gu_tips'] && self::actionSaveJson($this->postData['gu_device']);
        die(json_encode($data));
    }

    /**
     *   删除
     */
    public function actionDel()
    {
        $this->postData['id'] = $this->input->post('id');
        $this->postData['mod'] = 'Gameupdate';
        $this->postData['act'] = 'getOne';

        if($this->env == 1){
            $url = $this->config->item('officialUrl');
        }else{
            $url = $this->config->item('localUrl');
            $this->postData['demo'] = 1;
        }

        $jsonStr = $this->curl->req($url, $this->postData);
        $data = $jsonStr ? (array)json_decode($jsonStr, true) : [];

        $this->postData['mod'] = 'Gameupdate';
        $this->postData['act'] = 'actionDel';

        $retData = $this->curl->req($url, $this->postData);
        $ret = json_decode($retData, TRUE);
        if(!empty($ret['code']) && !empty($data['gu_device'])){
            $devices = array_flip($this->device);
            isset($devices[$data['gu_device']]) && self::actionSaveJson($devices[$data['gu_device']]);
        }
        die(json_encode($ret));
    }


    /**
     * 添加热更新
     */
    public function addHotFix($id, $device, $version)
    {
        if($device == 'ios'){
            $sid = 2;
        }else{
            $sid = 1;
        }
        $data = $this->data;
        $this->postData['mod'] = 'Gameupdate';
        $this->postData['act'] = 'getHotFix';
        $this->postData['id'] = $id;
        $postUrl = $this->config->item('officialUrl');
        $retData = $this->curl->req($postUrl, $this->postData);
        $ret = json_decode($retData, TRUE);
        $data['version'] = $version;
        $data['id'] = $id;
        $data['list'] = $ret;
        $data['sid']  = $sid;
        $this->load->view('gameupdate/addHotFix', $data);
    }

    public function actionAddHotFix(){
        $input = $this->input->post();
        $verion = explode('.',$input['subversion']);
        $temp = [];
        foreach ($verion as $row){
            if($row != ''){
                $temp[]= $row;
            }
        }
        if(count($verion) != count($temp)){
            return $this->response(2, '版本号异常');
        }
        $posts = $this->postData;
        $posts['mod'] = 'Gameupdate';
        $posts['act'] = 'saveHotFix';
        $posts['id']  = $input['versionid'];
        $posts['version'] = $input['subversion'];
        $posts['remark']  = $input['remark'];
        $posts['isForce'] = $input['isForce'];
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        if($retData == 0){
            return $this->response(1, '操作失败');
        }else{
//            self::actionSaveJson($input['sid']);
            return $this->response(0, '操作成功');
        }
    }

    /**
     *   热更新备注
     */
    public function hotfixremark()
    {
        $versionid = $this->input->post('versionid');
        $versiondevice = $this->input->post('versiondevice');
        $subversion = $this->input->post('subversion');
        $remark = $this->input->post('remark');
        $remarkData = array(
            'version_name' => $subversion,
            'version_device' => $versiondevice == 'android' ? 1 : 2,
            'version_parent' => $versionid,
            'version_id' => $versionid,
            'remark' => $remark,
            'remark_name' => get_cookie('chinesename'),
            'remark_time' => time(),
        );
        $this->db->insert('updategame_remark', $remarkData);
    }


    /**
     * 上传操作
     */
    public function actionAddhu(){
        $post = $this->input->post();
        $file = $_FILES;
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100';
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        if ( ! $this->upload->do_upload('userfile')) {
            $error = array('error' => $this->upload->display_errors());
            print_r($error);
            exit;
        }else{
            $data = array('upload_data' => $this->upload->data());
            print_r($data);
            exit;
        }
        exit;
    }


    /**
     *   主备注列表
     */
    public function remarkList()
    {
        $this->db->order_by('update_time', 'DESC');
        $query = $this->db->get_where('updategame_remark');
        $list = $query->result_array();
        foreach ($list as $key=>$row){
            $list[$key]['version_device'] = $this->device[$row['version_device']];
        }
        $data['list'] = $list;
        $data['time'] = date('Y-m-d H:i');
        $this->load->view('gameupdate/remarkList', $data);
    }

    /**
     *   子版本备注列表
     */
    public function subversionmark($id)
    {
        $query = $this->db->get_where('updategame_remark', array('version_parent' => $id));
        $list = $query->result_array();
        $data['list'] = $list;
        $this->load->view('gameupdate/subversionmark', $data);
    }


    /**
     *   添加备注
     */
    public function addMark()
    {
        $version_name = $this->input->post('version_name');//版本名称
        $version_device = $this->input->post('version_device');//设备
        $content = $this->input->post('content');//内容
        $time = $this->input->post('time');//备注更新时间
        $chinesename = get_cookie('chinesename');
        $now = time();
        $time = empty($time) ? 0 : strtotime($time);
        foreach ($version_device as $value) {
            $remarkData = array(
                'version_name' => $version_name,
                'version_device' => $value,
                'version_parent' => 0,
                'version_id' => 0,
                'remark' => $content,
                'remark_name' => $chinesename,
                'remark_time' => $now,
                'update_time' => $time,
            );
            $this->db->insert('updategame_remark', $remarkData);
        }
        $this->data['message'] = '添加成功';
        $this->data['refresh'] = true;
        $this->data['state'] = 'success';
        die(json_encode($this->data));
    }


    public function actionHotupdate(){
        $subversion = trim($_POST['subversion']);//热更新名称
        $device = $_POST['device'] == 1 ? 'android' : 'ios'; //设备名称
        $stagefile = $_FILES['stagefile']; //上传文件名称名称
        $hotuploadPath = './public/hotupdatefile/'.$device.'/'.$subversion.'/';
        $this->makeDir($hotuploadPath);
        $this->deldir($hotuploadPath);
        foreach ($stagefile['name'] as $k => $fileName){
            if (!$fileName) {
                continue;
            }
            $uploadName = $fileName;
            $filePath = $hotuploadPath.$uploadName;
            $tmpName = $stagefile['tmp_name'][$k];
            move_uploaded_file($tmpName, $filePath);
            $zip = new ZipArchive();
            if ($zip->open($filePath) === true) {
                //解压文件到获得的路径a文件夹下
                $zip->extractTo($hotuploadPath);
                //关闭
                $zip->close();
            }
        }
        die(json_encode(['code'=>1,'msg'=>'ok']));
    }

    public function actionAssets(){
        $stagefile = $_FILES['stagefile']; //上传文件名称名称
        $hotuploadPath = './public/assets/';
        $this->makeDir($hotuploadPath);
        $this->deldir($hotuploadPath);
        foreach ($stagefile['name'] as $k => $fileName){
            if(!$fileName){
                continue;
            }
            $uploadName = $fileName;
            $filePath = $hotuploadPath.$uploadName;
            $tmpName = $stagefile['tmp_name'][$k];
            move_uploaded_file($tmpName, $filePath);
            $zip = new ZipArchive();
            if ($zip->open($filePath) === true) {
                //解压文件到获得的路径a文件夹下
                $zip->extractTo($hotuploadPath);
                //关闭
                $zip->close();
            }
        }
        die(json_encode(['code'=>1,'msg'=>'ok']));
    }

    public function getTitle($version){
        $arr = explode('.', $version);
        array_pop($arr);
        $new = implode('.', $arr);
        return $new;
    }

    public function deldir($path){
        //如果是目录则继续
        if(is_dir($path)){
            $p = scandir($path);
            foreach($p as $val){
                if($val !="." && $val !=".."){
                    if(is_dir($path.$val)){
                        $this->deldir($path.$val.'/');
                        @rmdir($path.$val.'/');
                    }else{
                        unlink($path.$val);
                    }
                }
            }
        }
    }
    public function makeDir($dir){
        if (!is_dir($dir)) {
            $old = umask(0);
            mkdir($dir, true ? 0775 : 0777, true);
            umask($old);
        }
    }

    public function actionSaveJson($sid){
        $posts = $this->postData;
        $name  = $this->device[$sid];
        $filename = ucfirst($name)."Version";
        $filename = $filename.time().'.json';
        $posts['mod'] = 'Config';
        $posts['act'] = 'makeVersionJson';
        $posts['actionSid'] = $sid;
        $posts['lang'] = json_encode(array_keys($this->_langList));
        $posts['filename'] = $filename;
        $url = $this->config->item('officialUrl');
        $retData = $this->curl->req($url, $posts);
        $retData = json_decode($retData,true);
        self::SaveJson($retData,$filename);
        $retData['isForce'] = 1;
        self::SaveJson($retData,str_replace('Version','VersionForce',$filename));
    }

    public function SaveJson($data,$filename){
        $dir = $this->staticPath;
        if (!is_dir($dir)){
            $old = umask(0);
            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);
        }
    }
}
