<?php
/**
* 游戏版本更新相关
*/
defined('IN_WEB') or die('Include Error!');

class Gameupdate
{
	
	public $gameUpdateTable = '';
	public $deviceArr = [];
    public $deviceNameArr = [];

	public function __construct(){
		$this->gameUpdateTable = otable::gameupdate();
		$this->deviceArr       = oo::commonOprModel('config')->getDeviceArr();
        $this->deviceNameArr   = array_flip($this->deviceArr);
	}

	/**
	*	获取版本更新信息
	*/
	public function getList($param){
		$sql = " SELECT * FROM {$this->gameUpdateTable} ORDER BY id DESC ";
		$list = oo::commonOprDb('common')->getAll($sql, MYSQLI_ASSOC);
		return json_encode($list);
	}
    /**
     *	获取单个信息
     */
    public function getone($param){
        $id = oo::functions()->uint($param['id']);
        $sql = " SELECT * FROM {$this->gameUpdateTable} WHERE id = {$id} LIMIT 1 ";
        $one = oo::commonOprDb('common')->getOne($sql, MYSQLI_ASSOC);
        return json_encode($one);
    }

	/**
	*	新增版本
	*/
	public function actionAdd($param){
		$gu_device    = oo::functions()->uint($param['gu_device']);
		$gu_version   = funs::changeVersionLength(oo::functions()->escape($param['gu_version']),3);
		$gu_title     = oo::functions()->escape($param['gu_title']);
		$gu_content   = oo::functions()->escape($param['gu_content']);
		$gu_updateurl = oo::functions()->escape($param['gu_updateurl']);
		$gu_commonurl = oo::functions()->escape($param['gu_commonurl']);
		$gu_hotfix    = oo::functions()->escape($param['gu_hotfix']);
		$gu_force     = oo::functions()->uint($param['gu_force']);
      	$gu_isReward  = oo::functions()->uint($param['gu_isReward']);
      	$gh_news      = oo::functions()->uint($param['gh_news']);
        $gu_reward    = oo::functions()->escape($param['gu_reward']);
        $isFirebasePush   = oo::functions()->uint($param['isFirebasePush']);
        $gu_tips      = oo::functions()->uint($param['gu_tips']);
        $gu_device    = $this->deviceArr[$gu_device];
        $ret = oo::commonOprDb('common')->getOne("SELECT * FROM {$this->gameUpdateTable} WHERE gu_version = '{$gu_version}' AND gu_device = '{$gu_device}' LIMIT 1 ", MYSQLI_ASSOC);
        $code = 0;
        if(empty($ret)){
            $time = time();
            oo::commonOprDb('common')->query("INSERT INTO {$this->gameUpdateTable} VALUES(NULL, '{$gu_version}', '','', '{$gu_force}', '{$gu_updateurl}', '{$gu_commonurl}', '{$gu_hotfix}', '{$time}', '{$gu_device}', '{$gu_title}', '{$gu_content}','{$gu_isReward}','{$gu_reward}','{$gh_news}','{$gu_tips}')");
            $id = oo::commonOprDb('common')->insertID();
            $code = ( $id > 0 ) ? 1 : 0;
            if($code) {
                foreach ($this->deviceArr as $sid=>$name) {
                    oo::commonOprRedis('common')->delete(okeys::gameupdateinfo($sid));
                }
                oo::commonOprRedis('common')->delete(okeys::updateVersionSta());
                $this->actionAddGiftLog($gu_version,$gu_device);
                $isFirebasePush && !IS_DEBUF && oo::commonOprModel('push')->pushByLang("push.title.update","push.content.update",['id'=>2,'content'=>'']);
            }
        }

		return json_encode(array('code' => $code, 'id' => $id));
	}

	/**
	*	更新版本
	*/
	public function actionUpdate($param){
		$id           = oo::functions()->uint($param['id']);
		$gu_device    = oo::functions()->uint($param['gu_device']);
		$gu_version   = funs::changeVersionLength(oo::functions()->escape($param['gu_version']),3);
		$gu_title     = oo::functions()->escape($param['gu_title']);
		$gu_content   = oo::functions()->escape($param['gu_content']);
		$gu_updateurl = oo::functions()->escape($param['gu_updateurl']);
		$gu_commonurl = oo::functions()->escape($param['gu_commonurl']);
		$gu_hotfix    = oo::functions()->escape($param['gu_hotfix']);
		$gu_force     = oo::functions()->uint($param['gu_force']);
      	$gu_isReward  = oo::functions()->uint($param['gu_isReward']);
        $gh_news      = oo::functions()->uint($param['gh_news']);
        $gu_reward    = oo::functions()->escape($param['gu_reward']);
        $gu_tips      = oo::functions()->uint($param['gu_tips']);
        $gu_device    = $this->deviceArr[$gu_device];
		$time = time();
		oo::commonOprDb('common')->query("UPDATE {$this->gameUpdateTable} SET gu_tips = '{$gu_tips}',gu_version = '{$gu_version}', gu_langtitle = '{$gu_title}', gu_langcontent = '{$gu_content}', gu_force = '{$gu_force}', gu_updateurl = '{$gu_updateurl}', gu_commonurl = '{$gu_commonurl}', gu_hotfix = '{$gu_hotfix}', gu_addtime = '{$time}', gu_device = '{$gu_device}',gu_isReward = '{$gu_isReward}', gu_reward = '{$gu_reward}', gh_news = '{$gh_news}' WHERE id = {$id} LIMIT 1");
        foreach ($this->deviceArr as $sid=>$name) {
            oo::commonOprRedis('common')->delete(okeys::gameupdateinfo($sid));
        }
		return json_encode(array('code' => 1));
	}

	public function actionDel($param){
		$id  = oo::functions()->uint($param['id']);
		$sql = "DELETE FROM {$this->gameUpdateTable} WHERE id = {$id} LIMIT 1";
        $num = oo::commonOprDb('common')->query($sql);
        //删除sid和版本对应的表
        $tableSid = otable::gameupdatesid();
        $sqlSid = "DELETE FROM {$tableSid} WHERE guid = {$id}";
        $numSid = oo::commonOprDb('common')->query($sqlSid);

		$code = ( $num > 0 && $numSid > 0 ) ? 1 : 0;
        if($code) {
            foreach ($this->deviceArr as $sid=>$name) {
                oo::commonOprRedis('common')->delete(okeys::gameupdateinfo($sid));
            }
        }
		return json_encode(array('code' => $code));
	}


	/**
	*	添加热更新版本
	*/
	public function addHotFix($param){
		$data = array('code' => -1, 'ver' => '', 'stage' => '');
		$device = oo::functions()->escape($param['device']);
		$version = oo::functions()->escape($param['version']);

		if (empty($device) || empty($version)) {
			return json_encode($data);
		}

		$hotFixFile = WWWROOT.'hotupdatefile/'.$device.'/flist'.$version;
		if (file_exists($hotFixFile)) {
			$file = file_get_contents($hotFixFile);
		}
		
		if( !$file ){
			$data['code'] = -2;
			return json_encode($data);
		}

		//开始正则匹配
		$data['code'] = 1;

		$verP = '#{ver\W=\W"(.*?)",#i';
		preg_match_all($verP, $file, $verArr);
		if (empty($verArr)) {
			$data['code'] = -3;
			return json_encode($data);
		}
		$data['ver'] = $verArr[1][0];

		$p = '#size="(\d{1,})",act="(.*)",name="(.*)",code="(.*)",silent="(.*)"#iU';
		preg_match_all($p, $file, $stageArr);
		if (empty($stageArr)) {
			$data['code'] = -4;
			return json_encode($data);
		}

		$sizeList = $stageArr[1];
		$actList = $stageArr[2];
		$nameList = $stageArr[3];
		$codeList = $stageArr[4];
		$silentList = $stageArr[5];

		$list = array();
		foreach ($sizeList as $key => $value) {
			$list[$key] = array('size' => $value, 'act' => $actList[$key], 'name' => $nameList[$key], 'code' => $codeList[$key], 'silent' => $silentList[$key]);
		}
		$data['stage'] = $list;

		return json_encode($data);
	}

    public function getHotFix($param){
	    $id  = $param['id'];
        $tb  = otable::GameHotFix();
        $sql = "SELECT * FROM {$tb} WHERE id={$id}";
        $ret = oo::commonOprDb('admin')->getAll($sql,MYSQLI_ASSOC);
        return json_encode($ret);
    }

	public function saveHotFix($param){
        $id = $param['id'];
        $version = $param['version'];
        $remark = $param['remark'];
        $isForce = $param['isForce'];
        $tb = otable::gameupdate();
        $sql = " SELECT * FROM {$tb} WHERE id={$id}  LIMIT 1 ";
        $ret = oo::commonOprDb('admin')->getOne($sql,MYSQLI_ASSOC);
        if($ret['gu_device'] == 'android'){
            oo::commonOprRedis('server')->delete(okeys::GameUpdateHotFix(1,$ret['gu_version']));
        }else if($ret['gu_device'] == 'ios'){
            oo::commonOprRedis('server')->delete(okeys::GameUpdateHotFix(2,$ret['gu_version']));
        }
	    $tb = otable::GameHotFix();
        $sql = " INSERT INTO {$tb} (id, version,remark,isForce) VALUES ({$id},'{$version}','{$remark}','{$isForce}')";
        return oo::commonOprDb('admin')->query($sql);
    }

    public function actionAddGiftLog($gu_version,$gu_device){
        $lasttime = time() - 7 * 24*60*60;
        $tb = otable::userinfo();
	    if(in_array($gu_device,['android','ios'])){
            $gu_device = $this->deviceNameArr[$gu_device];
            $ret = oo::commonOprDb('userinfo')->getAll("SELECT uid FROM {$tb} WHERE version >= '{$gu_version}' AND login_plat='{$gu_device}' AND lasttime > '{$lasttime}' AND channel=0",MYSQLI_ASSOC);
	    }else if(in_array($gu_device,['vivo'])){
            $gu_device = $this->deviceNameArr[$gu_device] - 2;
            $ret = oo::commonOprDb('userinfo')->getAll("SELECT uid FROM {$tb} WHERE version >= '{$gu_version}' AND lasttime > '{$lasttime}' AND channel={$gu_device}",MYSQLI_ASSOC);
        }
        if(!empty($ret)){
            $time = time();
            foreach ($ret as $row){
                $uid = $row['uid'];
                $versionGiftLog = otable::versionGitfLog($uid);
                $sql  = "INSERT INTO {$versionGiftLog}(id, uid, version, time, reward) VALUES ";
                $sql .= "(NULL,'{$uid}','{$gu_version}','{$time}','{}'),";
            }
            $sql  = trim($sql,',');
            oo::commonOprDb('common')->query($sql);
        }
    }
}
