//=============================================================================
// 第1版 - 初版
// 第2版 - 中断スイッチに関する動作を変更
// 第3版 - 対局中ボイスに対応
// 第4版 - 供託棒と積み棒の処理を変更
// 第5版 - CPUの刷新に伴いCPU設定関連の項目を更新
// 第6版 - 麻雀イベントプラグイン用に一部処理を改変
//         槍槓対象牌の指定の処理を修訂
// 第7版 - カン関連の不具合を修訂
// 第9版 - 自家の最終得点を変数にとるように変更
// 第9版3刷 - 副露後聴牌時 プレイヤーの待ち牌ウィンドウが表示されない不具合修訂
// 第10版 - 二人麻雀に対応
//          和了で終局時に供託立直棒が初期化されていない不具合を修訂
//          積み符の上家取りの設定変更に対応
// 第11版 - 返り東無効化コマンドに対応
//
// 
//=============================================================================

/*:
 * @target MZ
 * @plugindesc 麻雀 (ゲーム進行)
 * @author 
 * @base AP1S_MajiangCore
 * @orderAfter AP1S_MajiangCore
 * 
 * @help
 * 
 * 麻雀
 * 
 * 詳細な使用方法は 同梱の説明書をご覧ください
 */



function MajiangManager ()
{
	throw new Error("This is a static class");
}


(function() 
{
	"use strict";
	
	
	
	
	
	
	
	MajiangManager.start = function()
	{
		this.saveBgmAndBgs();
		
		AudioManager.stopAll();
		this.prepareSetting();
		this.setBattlers();
		
		this._wait = 0;
		this._requests = [];
		
		
		this._methods = [];
		
		this.setGame();
		this.startCPU();
		this.startGame();
	};
	
	MajiangManager.saveBgmAndBgs = function() 
	{
    	this._mapBgm = AudioManager.saveBgm();
    	this._mapBgs = AudioManager.saveBgs();
	};
	
	MajiangManager.replayBgmAndBgs = function() 
	{
    	if (this._mapBgm) 
    	{
    	    AudioManager.replayBgm(this._mapBgm);
    	}
    	else
    	{
    	    AudioManager.stopBgm();
    	}
    	if (this._mapBgs) 
    	{
    	    AudioManager.replayBgs(this._mapBgs);
    	}
	};
	
	MajiangManager.push = function(methodName) 
	{
    	const methodArgs = Array.prototype.slice.call(arguments, 1);
    	this._methods.push({ name: methodName, params: methodArgs });
	};
	
	MajiangManager.callNextMethod = function() 
	{
    	if (this._methods.length > 0) 
    	{
    	    const method = this._methods.shift();
    	    if (method.name && this[method.name]) 
    	    {
    	        this[method.name].apply(this, method.params);
    	    } 
    	    else 
    	    {
    	        throw new Error("Method not found: " + method.name);
    	    }
    	}
	};
	
	MajiangManager.prepareSetting = function()
	{
		$gameMajiangBattlers = new Game_MajiangBattlers();
		$gameMajiangPaishan = new Game_MajiangPaishan();
	};
	MajiangManager.startCPU = function()
	{
		for(const unit in $gameMajiangCPU)
		{
			$gameMajiangCPU[unit].start?.();
		}
	};
	
	MajiangManager.setTerminate = function()
	{
		
		$gameMajiangSystem.terminate();
		this._methods = [];
		this._finalResult = [];
		this.clearAll();
		for(const unit in $gameMajiangCPU)
		{
			$gameMajiangCPU[unit].terminate?.();
		}
		$gameMajiangPaishan = null;
		$gameMajiangBattlers = null;
		$dataMajiangSystem.temp = {};
	};
	
	
	MajiangManager.setBattlers = function()
	{
		const actorId = $gameMajiangSystem.actorId();
		
		$gameMajiangBattlers.setGameBattlers(...actorId);
	};
	
	//ゲーム初期設定
	MajiangManager.setGame = function()
	{
		this.clearGame();
		
		this.setInitialPoint();
	};
	
	MajiangManager.clearGame = function()
	{
		this._dealerPosition = -1;
		this._heleJia = [];
		this._quanfeng = 1; //場風ID
		this._ju = 0; // 局
		this._juCount = 0;
		this._tsumibo = 0; //積み棒
		this._lizhibo = []; //立直棒 立直者のIDの配列
		this._nextTsumibo = null;
		this._nextLizhibo = null;
		this._lianzhuang = false;
		this._restart = false;
		this._allLastPrinted = false;
		this._cancelLines = false;
		this._messageWindow = null;
	};
	
	MajiangManager.clearAll = function()
	{
		this.clearGame();
		this.clearYiju();
	};
	
	MajiangManager.setInitialPoint = function()
	{
		for(const battler of $gameMajiangBattlers.allBattlers())
		{
			let point = (this.scoreSettings().basePoint);
			if($gameMajiangSystem.config.initialPoint)
			{
				const position = battler.gpPosition();
				const varId = $gameMajiangSystem.config.initialPoint[position];
				if(varId)
				{
					point = $gameVariables.value(varId);
				}
			}
			battler.gainPoint(point);
		}
	};
	
	
	
	//一局初期設定
	MajiangManager.setYiju = function()
	{
		$gameMajiangBattlers.clearYiju();
		
		this.clearMajiangPai();
		
		this.setTembo();
		
		
		this.clearYiju();
		
		this.setNextju();
		
		this._restart = false;
		
		this._turn = $gameMajiangBattlers.dealer().position(); 
	};
	
	MajiangManager.setTembo = function()
	{
		if(this._nextTsumibo === "add")
		{
			this._tsumibo++;
		}
		else if(this._nextTsumibo === "clear")
		{
			this._tsumibo = 0;
		}
		
		if(this._nextLizhibo === "clear")
		{
			this._lizhibo = [];
		}
		this._nextTsumibo = null;
		this._nextLizhibo = null;
	};
	
	
	MajiangManager.clearYiju = function()
	{
		this._phase = "start";
		this._gangCount = 0;
		this._lizhiCount = 0;
		this._sikaigang = false;
		this._heleJia = []
		this._requestLizhi = null;
		this._fangchongjia = null;
		this._isRong = false;
		this._dapai = null;
		this._queryFulu = [];
		this._liuju = "";
		this._sifengLiandaChecked = false;
		this._afterZimo = false;
	};
	
	
	MajiangManager.setNextju = function()
	{
		if(!this._lianzhuang && !this._restart)
		{
			this._ju++;
			this._juCount++;
			if(this._ju > this.numBattlers())
			{
				this._quanfeng++;
				
				this._ju = 1;
			}
			if(this._quanfeng > this.numBattlers())
			{
				this._quanfeng = 1;
			}
			if(this._dealerPosition === -1)
			{
				this.oyagime();
			}
			else
			{
				this._dealerPosition = this.nextPositionId(this._dealerPosition);
			}
			this.setDealer();
		}
	};
	
	MajiangManager.dealerPosition = function()
	{
		return this._dealerPosition;
	};
	
	MajiangManager.setDealer = function()
	{
		$gameMajiangBattlers.setFeng(this._dealerPosition);
	};
	
	
	
	
	
	//一局開始
	MajiangManager.startYiju = function()
	{
		this.playAudio("duijuBgm");
		this._phase = "zimo";
	};
	
	MajiangManager.nextTurn = function()
	{
		this._turn = this.nextPositionId(this._turn); //現在の席ID
	};
	
	MajiangManager.nextPositionId = function(positionId)
	{
		let ret = (positionId + 1) % 4;
		if(!this.quartet())
		{
			if(!this.checkPosition(ret))
			{
				ret = (positionId + 2) % 4
			}
		}
		return ret;
	};
	
	MajiangManager.prevPositionId = function(positionId)
	{
		let ret = (positionId + 3) % 4;
		if(!this.quartet())
		{
			if(!this.checkPosition(ret))
			{
				ret = (positionId + 2) % 4;
			}
		}
		
		return ret;
		
	};
	MajiangManager.numBattlers = function()
	{
		return $gameMajiangSystem.numBattlers();
	};
	MajiangManager.samma = function()
	{
		return $gameMajiangSystem.samma();
	};
	MajiangManager.duo = function()
	{
		return $gameMajiangSystem.duo();
	};
	MajiangManager.quartet = function()
	{
		return (!this.samma() && !this.duo());
	};
	MajiangManager.emptyPositions = function()
	{
		return $gameMajiangSystem.emptyPositions();
	};
	MajiangManager.sammaEmptyPosition = function()
	{
		if(this.samma())
		{
			return $gameMajiangSystem.emptyPositions()[0];
		}
		return -1;
	};
	MajiangManager.checkPosition = function(position)
	{
		return $gameMajiangSystem.checkPosition(position);
	};
	
	
	
	MajiangManager.currentBattler = function()
	{
		return $gameMajiangBattlers.battler(this._turn);
	};
	MajiangManager.currentQuanfeng = function()
	{
		return this._quanfeng;
	};
	MajiangManager.currentJu = function()
	{
		return this._ju;
	};
	
	MajiangManager.lizhibo = function()
	{
		return this._lizhibo.length;
	};
	
	MajiangManager.tsumibo = function()
	{
		return this._tsumibo;
	};
	
	MajiangManager.fanshiba = function()
	{
		if($gameMajiangSystem.config.fanshiba)
		{
			return $gameMajiangSystem.config.fanshiba;
		}
		if($gameMajiangSystem.gamerule.liangfan === 1)
		{
			const liangfanHomba = $gameMajiangSystem.settings.liangfanHomba || 0;
			if(this.tsumibo() >= liangfanHomba)
			{
				return 2;
			}
		}
		return 1;
	};
	
	MajiangManager.crearYifaYishun = function()
	{
		const all = $gameMajiangBattlers.allBattlers();
		all.forEach(b => {b.setYishun(false); b.setYifa(false)})
	};
	
	
	
	
	
	MajiangManager.peipai = function()
	{
		$gameMajiangPaishan.qipai();
		const wait = $dataMajiangSystem.params.dapaiWait;
		for (let i = 0 ; i < 3 ; i++)
		{
			this.push("peipaiProcess",4);
			this.push("playAudio","dapai");
			this.push("setWait",wait);
		}
		this.push("peipaiProcess",1);
		
		this.push("setTingpaiMachi");
		
		this.push("peipaiProcess",1);
		
		this.push("setWait",wait);
		
		this.push("peipaiCompleted");
		
	};
	
	MajiangManager.peipaiProcess = function(num)
	{
		const peipai = $gameMajiangPaishan.peipai();
		
		for(const battler of $gameMajiangBattlers.allBattlers())
		{
			for (let i = 0 ; i < num ; i++)
			{
				const pai = peipai[battler.position()].shift();
				if(pai)
				{
					battler.pushTehai(pai);
				}
			}
		}
		this.requestSync();
	};
	
	MajiangManager.setTingpaiMachi = function()
	{
		$gameMajiangBattlers.allBattlers().forEach(b => b.setTingpaiMachi());
	};
	
	MajiangManager.peipaiCompleted = function()
	{
		this.push("setWait",$dataMajiangSystem.params.dapaiWait);
		
		this.initDora();
		$gameMajiangBattlers.allBattlers().forEach(b => {
			b.tehaiLipai();
			
			b.callCPU("peipai");
		});
		
		this.requestSync();
		this.push("startYiju");
	};
	
	MajiangManager.initDora = function()
	{
		$gameMajiangPaishan.nextDora();
		if($gameMajiangSystem.config.addDora)
		{
			for(let i = 0; i < $gameMajiangSystem.config.addDora; i++)
			{
				$gameMajiangPaishan.nextDora();
			}
		}
	};
	
	MajiangManager.lotQijiaPosition = function(value)
	{
		if(this.samma())
		{
			return this.nextPositionId(this.sammaEmptyPosition());
		}
		else if(this.duo())
		{
			if(value === 4)
			{
				return (Math.randomInt(2) === 0) ? 0 : 2;
			}
			else if(value === 0)
			{
				return 0;
			}
			else
			{
				return 2;
			}
			
		}
		else
		{
			if(value === 4)
			{
				return Math.randomInt(this.numBattlers());
			}
			else
			{
				return value;
			}
		}
	};
	
	MajiangManager.oyagime = function()
	{
		const settingValue = $gameMajiangSystem.condition.dealerPosition;
		this._dealerPosition = this.lotQijiaPosition(settingValue);
		$gameMajiangBattlers.battler(this._dealerPosition).setQijia();
	};
	
	
	MajiangManager.updateStart = function() 
	{
		this.push("requestFadeIn");
		this.push("startGameProcess_1");
		this.push("startGameProcess_2");
		this.push("startGameProcess_3");
	};
	
	MajiangManager.startGameProcess_1 = function() 
	{
		this.playAudio("startDuiju");
		const textArray = this.makeChangStatusText(true);
		this.startMessage(textArray , null, $dataMajiangSystem.params.messageWait);
	};
	
	MajiangManager.makeChangStatusText = function(execute) 
	{
		const ret = [];
		ret.push(this.textCurrentChangStatus());
		let status = "";
		const tsumibo = this.tsumibo();
		if($dataMajiangSystem.text.homba && tsumibo)
		{
			status += $dataMajiangSystem.text.homba.format(tsumibo);
		}
		if($dataMajiangSystem.text.allLast && !this._allLastPrinted && this.currentAllLast())
		{
			if(status) status += " ";
			status += $dataMajiangSystem.text.allLast;
			if(execute)
			{
				this._allLastPrinted = true;
			}
		}
		if(status)
		{
			ret.push(status);
		}
		return ret;
	};
	
	
	MajiangManager.startGameProcess_2 = function() 
	{
		this.requestOpenAllWindows();
		this.setWait($dataMajiangSystem.params.wait);
	}
	MajiangManager.startGameProcess_3 = function() 
	{
		this.playAudio("duijuBgm");
		this.peipai();
		
		
	};
	
	MajiangManager.setMessageWindow = function(messageWindow) 
	{
		this._messageWindow = messageWindow;
	};
	
	MajiangManager.startMessage = function(message,battler,wait,audioKey) 
	{
		if(this._messageWindow && message && message.length > 0)
		{
			this._messageWindow.setMessage(message,battler,wait,audioKey);
		}
	};
	MajiangManager.startLines = function(key,battler) 
	{
		const data = this.actorLines(battler,key);
		const wait = $dataMajiangSystem.params.linesWait;
		if(!this._cancelLines)
		{
			this.startMessage(data.text,battler,wait,data.audio);
		}
		this._cancelLines = false;
	};
	MajiangManager.setCancelLines = function()
	{
		this._cancelLines = true;
	}
	
	MajiangManager.actorLines = function(battler,key)
	{
		return battler.lines(key);
	};
	
	
	MajiangManager.canCalledGameEndMenu = function()
	{
		return (!["start","end"].includes(this._phase) && !this.eventRunning());
	};
	
	MajiangManager.update = function(timeActive)
	{
		if(timeActive)
		{
			if (!this.updateWait()) 
			{
				this.updateEvent();
				if(!this.eventRunning())
				{
        			this.callNextMethod();
        			if (!this.isBusy())
					{
        				this.updatePhase();
    				}
    			}
    		}
    	}
	};
	
	MajiangManager.updateWait = function()
	{
		
    	if (this._wait > 0) 
    	{
    	    this._wait -= this.isFastForward() ? 3 : 1;
			if (this._wait < 0) 
    	    {
           		this._wait = 0;
        	}
    	    return true;
    	}
    	else
    	{
        	return false;
    	}
	};
	
	MajiangManager.isFastForward = function()
	{
		return (
        	Input.isLongPressed("ok") ||
        	Input.isPressed("shift") ||
        	TouchInput.isLongPressed()
    	);
	};
	
	MajiangManager.updateEvent = function()
	{
		//
	};
	
	MajiangManager.isBusy = function()
	{
		return (this._methods.length > 0 || this.eventRunning()) ;
	};
	
	MajiangManager.eventRunning = function()
	{
		return false;
	};
	
	MajiangManager.setWait = function(wait)
	{
		this._wait += Math.max( 0 , wait - 1); ;
	};
	
	MajiangManager.updatePhase = function()
	{
		
		switch(this._phase)
		{
			case "start" : 
				this.updateStart();
			break;
			
			case "zimo" : //自摸開始
				this.updateZimo(false);
			break;
			case "lingshangZimo" : //嶺上自摸開始
				this.updateZimo(true);
			break;
			case "moda" : //打牌待機
				this.updateModa();
			break;
			case "dapai" : //打牌後
				this.updateDapai();
			break;
			
			case "liuju" : //流局
				this.updateLiuju();
			break;
		}
	};
	
	
	MajiangManager.updateZimo = function(lingshang)
	{
		this._dapai = null;
		const battler = this.currentBattler();
		battler.setFuriten(false);
		if(!(battler.yishun() && battler.isDealer()))
		{
			battler.zimo(lingshang);
		}
		battler.makeCanTingpaiResult();
		battler.callCPU("zimo");
		
		this.requestSync();
		this.zimoEvent();
		if(!battler.operatePlayer() || battler.isLizhi())
		{
			this.push("setWait",$dataMajiangSystem.params.zimoWait);
		}
		this.push("startQueryZimoAction");
		this._afterZimo = true;
	};
	MajiangManager.zimoEvent = function()
	{
		//
	};
	
	MajiangManager.updateModa = function()
	{
		const battler = this.currentBattler();
		battler.startModa(this._afterZimo);
		this._afterZimo = false;
		this.requestSync();
		if(battler.isLizhi())
		{
			const dapai = battler.tehai().find(p => p.isZimoPai());
			this.applyDapai(dapai);
		}
		else if(battler.operatePlayer())
		{
			this.queryDapaiPlayer();
		}
		else
		{
			this.queryDapaiCPU();
		}
	};
	
	MajiangManager.queryDapaiPlayer = function()
	{
		const battler = this.currentBattler();
		battler.queryDapaiPlayer();
		this.startInput();
		this.requestInputDapai();
	};
	
	MajiangManager.applyDapaiPlayer = function(pai)
	{
		
		this.applyDapai(pai);
	};
	
	MajiangManager.queryDapaiCPU = function()
	{
		const battler = this.currentBattler();
		const dapai = battler.queryDapaiCPU();
		
		this.applyDapai(dapai);
	};
	
	MajiangManager.applyDapai = function(pai)
	{
		const battler = this.currentBattler();
		if(this._requestLizhi)
		{
			const isDouble = (this._requestLizhi.isDouble);
			this.setLizhiLines(battler,isDouble);
			const lizhiBgm = battler.lizhiBgm();
			this.push("playAudio",lizhiBgm);
		}
		battler.dapai(pai,!!this._requestLizhi);
		
		this.requestSync();
		this.playAudio("dapai");
		
		this._dapai = pai;
		this._phase = "dapai";
		
		this.push("setWait",$dataMajiangSystem.params.dapaiWait);
	};
	MajiangManager.recentDapai = function()
	{
		return dapai;
	};
	
	MajiangManager.setLizhiLines = function(battler,isDouble)
	{
		const linesKey = (isDouble) ? "doubleLizhi" : "lizhi";
		this.push("startLines",linesKey,battler);
	};
	
	
	MajiangManager.updateDapai = function()
	{
		this.currentBattler().modaEnd();
		this.startQueryFulu();
	};
	
	
	MajiangManager.startQueryFulu = function()
	{
		this._queryFulu = [];
		for(const battler of this.kamijiaArray())
		{
			battler.makeCanFuluResult(this._dapai,this.currentBattler());
			this.push("queryFulu",battler);
			//this.setOverlook(battler);
		};
		this.push("checkFulu");
	};
	/*
	MajiangManager.setOverlook = function(battler)
	{
		if(this._dapai)
		{
			battler.addOverlook(this._dapai);
		}
	};*/
	/*
	MajiangManager.clearOverlook = function(battler)
	{
		battler.clearTempActual();
	};*/
	
	MajiangManager.setPlayerFuluRequest = function(req)
	{
		const battler = $gameMajiangBattlers.player();
		this._queryFulu.push({"battler" : battler, "fuluReq" : req});
	};
	
	
	MajiangManager.queryFulu = function(battler)
	{
		if(battler.canFuluActions().length > 0 )
		{
			if(battler.operatePlayer())
			{
				this.queryFuluPlayer(battler);
			}
			else
			{
				this._queryFulu.push( 
				{
					"battler" : battler,
					"fuluReq" : battler.queryFuluCPU(this.currentBattler())
				});
			}
		}
		
	};
	
	MajiangManager.queryFuluPlayer = function(battler)
	{
		battler.queryFuluPlayer(this.currentBattler());
		
		this.startInput();
		const items = [];
		for(const item of battler.canFuluActions())
		{
			const ret = {};
			ret.name = this.fuluText(item.kind);
			ret.item = item;
			ret.paizi = [...item.paizi , this._dapai].sort((a,b) => a.paiId() - b.paiId());
			items.push(ret);
		}
		this.setChoiceCondition(items,"setPlayerFuluRequest");
		this.requestStartChoice();
	};
	
	MajiangManager.fuluText = function(kind) 
	{
		let key = kind;
		if(key === "daminggang")
		{
			key = "gang";
		}
		
		return $dataMajiangSystem.text[key];
		
	};
		
	MajiangManager.dapaiSuccess = function()
	{
		
		this.push("checkLiuju");
		this.push("checkRequestLizhi");
		
		
		
	}
	MajiangManager.checkRequestLizhi = function()
	{
		if(this._requestLizhi && !this._liuju)
		{
			this._lizhiCount++;
			
			this.applyLizhi();
			this._requestLizhi = null;
			
			if(this.checkSijiaLizhi())
			{
				this._liuju = "sijiaLizhi";
				
				this.push("checkLiuju");
			}
		}
	};
	MajiangManager.checkSijiaLizhi = function()
	{
		return ( $gameMajiangSystem.gamerule.sijiaLizhi
			&& this.quartet()
			&& (this._lizhiCount >= 4)
		);
	};
	
	MajiangManager.checkFulu = function()
	{
		this._queryFulu = this._queryFulu.filter(f => f.fuluReq);
		
		const rongReq = this._queryFulu.filter(f => f.fuluReq.kind === "rong");
		const pengReq = this._queryFulu.filter(f => ["peng" , "daminggang"].includes(f.fuluReq.kind));
		const chiReq = this._queryFulu.filter(f => f.fuluReq.kind === "chi");
		
		if(rongReq.length > 0)
		{
			this.startRong(rongReq);
		}
		else
		{ 
			this.setDapaiFuriten(this._dapai,false);
			if(pengReq.length > 0)
			{
				this.startFulu(pengReq[0]);
			}
			else if(chiReq.length > 0)
			{
				this.startFulu(chiReq[0]);
			}
			else 
			{
				this.dapaiPassed();
			}
		}
	};
	
	MajiangManager.setDapaiFuriten = function(dapai,qianggang)
	{
		const code = dapai.code();
		this.kamijiaArray().forEach(b => 
		{
			b.setDapaiFuriten(code,qianggang)
		});
	};
	
	MajiangManager.startRong = function(reqs)
	{
		this.stopBgm();
		
		this._phase = "end";
		if($gameMajiangSystem.gamerule.atamahane)
		{
			reqs = [reqs[0]];
		}
		
		for(const req of reqs)
		{
			
			const battler = req.battler;
			
			battler.setHele(req.fuluReq.dapai);
			this.setActionLines(battler,req.fuluReq);
			
			this.addHelejia(battler);
		}
		if($gameMajiangSystem.gamerule.sanjiahe && reqs.length === 3 )
		{
			this._liuju = "sanjiahe";
			this.push("checkLiuju");
		}
		else
		{
			this._fangchongjia = this.currentBattler();
			this._fangchongjia.setFangchong();
			this._isRong = true;
			this.push("startHele" , [reqs[0].fuluReq.dapai]);
		}
	};
		
	
	
	
	
	
	MajiangManager.startFulu = function(req)
	{
		
		
		const battler = req.battler;
		//const text = this.actorLines(battler,kind);
		this.setActionLines(battler,req.fuluReq);
		
		
		this.push("applyFulu",req)
	};
	MajiangManager.setActionLines = function(battler,action)
	{
		const kind = action.kind;
		this.push("startLines",kind,battler);
	};
	
	MajiangManager.applyFulu = function(req)
	{
		this.checkRequestLizhi();
		this.crearYifaYishun();
		const battler = req.battler;
		battler.applyFulu(req.fuluReq,this.currentBattler());
		this._turn = battler.position();
		if(req.fuluReq.kind === "daminggang")
		{
			$gameMajiangPaishan.nextDora();
			this._phase = "lingshangZimo";
			this.addGang();
		}
		else
		{
			battler.callCPU("afterFulu");
			this._phase = "moda";
		}
		if($gameMajiangSystem.gamerule.kuigae)
		{
			battler.setKuigaeSelect(req.fuluReq);
		}
		this.requestSync();
		this.push("setWait",$dataMajiangSystem.params.dapaiWait);
	};
	
	
	
	
	
	MajiangManager.dapaiPassed = function()
	{
		if($gameMajiangPaishan.shengyu() === 0)
		{
			this._liuju = "huangpaiPingju";
		}
		else
		{
			this.nextTurn();
			this._phase = "zimo";
		}
		this.dapaiSuccess();
		
		
		this.push("setWait",$dataMajiangSystem.params.dapaiWait);
	};
	
	
	// 現在のbattlerの下家から 上家まで順の配列 上家取などで使用
	MajiangManager.kamijiaArray = function()
	{
		const ret = $gameMajiangBattlers.allBattlers(this._turn);
		return ret.slice(1);
	};
	// 起家から順の配列
	MajiangManager.qijiaArray = function()
	{
		const qijia = $gameMajiangBattlers.allBattlers().find(b => b.isQijia());
		const qijiaPosition = qijia.position();
		
		return $gameMajiangBattlers.allBattlers(qijiaPosition);
	};
	
	MajiangManager.startQueryZimoAction = function()
	{
		const battler = this.currentBattler();
		battler.makeZimoActionResult();
		
		if(battler.zimoActions().length > 0)
		{
			if(battler.operatePlayer())
			{
				this.queryZimoActionPlayer();
			}
			else
			{
				this.checkZimoAction(battler.queryZimoActionCPU());
			}
		}
		else
		{
			this._phase = "moda";
		}
		
	};
	
	MajiangManager.checkZimoAction = function(req)
	{
		if(req)
		{
			this.applyZimoAction(req);
		}
		else
		{
			this._phase = "moda";
		}
	};
	
	MajiangManager.queryZimoActionPlayer = function()
	{
		this.startInput();
		const items = [];
		const battler = this.currentBattler();
		
		battler.queryZimoActionPlayer();
		
		for(const item of battler.zimoActions())
		{
			const ret = {};
			ret.name = this.zimoActionText(item.kind);
			ret.item = item;
			ret.paizi = item.paizi || [];
			items.push(ret);
		}
		
		this.setChoiceCondition(items,"setPlayerZimoActionRequest");
		this.requestStartChoice();
	};
	
	MajiangManager.zimoActionText = function(kind)
	{
		let key = kind;
		if(key === "doubleLizhi")
		{
			key = "lizhi";
		}
		if(key === "angang" || key === "jiagang")
		{
			key = "gang";
		}
		return $dataMajiangSystem.text[key];
		
	};	
	MajiangManager.setPlayerZimoActionRequest = function(req)
	{
		this.checkZimoAction(req);
	};
	
	MajiangManager.applyZimoAction = function(req)
	{
		const battler = this.currentBattler();
		//const text = this.actorLines(battler,req.kind);
		const linesKind = req.kind;
		
		switch(req.kind)
		{
			case "lizhi" : 
				this.startLizhiSelect();
			break;
			
			case "angang" :
				this.setActionLines(battler,req);
				this.push("applyZimogang",battler,req);
			break;
			case "jiagang" :
				this.setActionLines(battler,req);
				this.push("applyZimogang",battler,req);
			break;
			case "zimo" :
				this.startZimoHele(battler,req);
			break;
			case "jiuzhongJiupai" :
				this._liuju = "jiuzhongJiupai";
				this.setActionLines(battler,req);
				this.push("checkLiuju");
			break;
			
			
		}
	};
	
	
	MajiangManager.applyZimogang = function(battler,req)
	{
		
		const isAngang = (req.kind === "angang");
		if(isAngang)
		{
			battler.applyAngang(req);
			this._dapai = req.paizi[1];
		}
		else
		{
			battler.applyJiagang(req);
			this._dapai = req.paizi.find(p => p.isJiagangPai());
		}
		this.addGang();
		this.push("setWait",$dataMajiangSystem.params.dapaiWait);
		
		this.push("startQueryQianggang",battler,req);
		this.requestSync();
		
		
	};
	MajiangManager.addGang = function()
	{
		this._gangCount++;
		this.checkSikaigang();
		
	};
	MajiangManager.checkSikaigang = function()
	{
		if(this._gangCount >= 4 && !$gameMajiangBattlers.allBattlers().some(b => b.gangCount() === 4))
		{
			this._sikaigang = true;
		}
	}
	MajiangManager.sikaigang = function()
	{
		return this._sikaigang;
	}
	
	MajiangManager.startQueryQianggang = function(battler,req)
	{
		this._queryFulu = [];
		const pai = this._dapai;
		const isAngang = (req.kind === "angang");
		for(const tajia of this.kamijiaArray())
		{
			tajia.makeCanQianggangResult(pai,battler,isAngang);
			this.push("queryFulu",tajia);
		};
		this.push("checkQianggang",isAngang);
	};
	
	MajiangManager.checkQianggang = function(isAngang)
	{
		this._queryFulu = this._queryFulu.filter(f => f.fuluReq);
		
		
		if(this._queryFulu.length > 0)
		{
			this.startRong(this._queryFulu);
		}
		else
		{
			$gameMajiangPaishan.nextDora();
			if(this._dapai)
			{
				const qianggangType = (isAngang) ? "angang" : "jiagang"
				this.setDapaiFuriten(this._dapai,qianggangType);
			}
			this._phase = "lingshangZimo";
			this.crearYifaYishun();
			this.requestSync();
		}
	};
	
	MajiangManager.startZimoHele = function(battler,req)
	{
		const helePai = req.helePai;
		this.stopBgm();
		this._phase = "end";
		battler.setHele();
		this.addHelejia(battler);
		this.setActionLines(battler,req);
		this.push("startHele",helePai);
		if(this.duo())
		{
			const opponentId = this.nextPositionId(this._turn);
			this._fangchongjia = $gameMajiangBattlers.battler(opponentId);
		}
	};
	
	
	
	MajiangManager.startLizhiSelect = function(req)
	{
		const battler = this.currentBattler();
		battler.startLizhiSelect();
		
		
		const isDouble = battler.yishun();
		this._requestLizhi = {"battler" : battler ,"isDouble" : isDouble};
		this._phase = "moda";
	};
	MajiangManager.applyLizhi = function()
	{
		const battler = this._requestLizhi.battler;
		battler.applyLizhi(this._requestLizhi);
		this.requestSync();
		this._lizhibo.push(battler.position());
	};
	
	MajiangManager.cancelLizhiSelect = function()
	{
		const battler = this._requestLizhi.battler;
		this._requestLizhi = null;
		
		battler.clearLizhiSelect();
	};
	
	MajiangManager.isLizhiSelecting = function()
	{
		return !!this._requestLizhi;
	};
	
	MajiangManager.checkSifengLianda = function()
	{
		if(this._sifengLiandaChecked) return false;
		const allBattlers = $gameMajiangBattlers.allBattlers();
		if(allBattlers.every(b => !!b.he()[0]))
		{
			const dapai = allBattlers[0].he()[0];
			if(dapai.isFeng()
				&& this.quartet()
				&& allBattlers.every(b => b.fulu().length === 0 && b.he()[0].code() === dapai.code())
			)
			{
				return true;
			}
			else
			{
				this._sifengLiandaChecked = true;
				return false;
			}
		}
		return false;
		
	}
	
	MajiangManager.checkLiuju = function()
	{
		if(this.sikaigang())
		{
			this._liuju = "sikaigang";
		}
		if(this.checkSifengLianda())
		{
			this._liuju = "sifengLianda";
		}
		
		
		if(this._liuju)
		{
			this.stopBgm();
			this._phase = "end";
			let text = "";
			if(this._liuju !== "jiuzhongJiupai")
			{
				text = this.liujuText(this._liuju);
			}
			this.setLiujuMessage(text);
			
			this.startEndYiju();
		}
	};
	
	MajiangManager.liujuText = function(kind)
	{
		return $dataMajiangSystem.text[kind];
	};
	
	MajiangManager.startEndYiju = function()
	{
		this.push("endGameProcess_1");
	};
	MajiangManager.setLiujuMessage = function(text)
	{
		if(text)
		{
			this.startMessage(text , null , $dataMajiangSystem.params.messageWait);
		}
	};
	
	
	
	MajiangManager.liujuDaopai = function()
	{
		const all = $gameMajiangBattlers.allBattlers();
		let daopaijia = [];
		if(this._liuju === "huangpaiPingju")
		{
			daopaijia = all.filter(b => b.isTingpai());
    	
		}
		else if(this._liuju === "jiuzhongJiupai")
		{
			daopaijia = [this.currentBattler()];
		}
		else if(this._liuju === "sijiaLizhi")
		{
			daopaijia = all.filter(b => b.isLizhi());
		}
		else if(this._liuju === "sanjiahe")
		{
			daopaijia = this.helejia();
		}
		daopaijia.forEach(b => b.daopai());
	};
	
	MajiangManager.endGameProcess_1 = function() 
	{
		if(this._liuju)
		{
			this.liujuDaopai();
		}
		this.requestSync();
		this.setWait($dataMajiangSystem.params.wait);
		this.push("endGameProcess_2");
	};
	MajiangManager.endGameProcess_2 = function() 
	{
		if(this._liuju)
		{
			this.setLiuju();
		}
		else
		{
			this.setHele();
		}
		this.setEndGameEvent();
		this.push("endGameProcess_3");
	};
	MajiangManager.setEndGameEvent = function()
	{
		//
	};
	MajiangManager.endGameProcess_3 = function() 
	{
		this.requestFadeOut();
		this.push("endGameProcess_4");
	}
	
	MajiangManager.endGameProcess_4 = function() 
	{
		if(this._restart)
		{
			this.startGame();
			SceneManager.goto(Scene_MajiangBattle);
		}
		else
		{
			this._resultSequence = this.makeResultSequence();
			SceneManager.goto(Scene_MajiangResult);
		}
		
	};
	MajiangManager.liuju = function()
	{
		return this._liuju;
	}
	
	MajiangManager.startInput = function() 
	{
    	this._phase = "input";
    	//this._inputting = true;
    };
    MajiangManager.tingpaiDaopai = function()
    {
    	
    };
    MajiangManager.isInputting = function()
    {
    	return (this._phase == "input");
	};
	
	MajiangManager.clearMajiangPai = function()
	{
		$gameMajiangPaishan.clearStatus();
	};
	
	MajiangManager.startGame = function()
	{
		this.setYiju();
	};
	
	MajiangManager.terminate = function(abstention)
	{
		const switchId = $dataMajiangSystem.params.abstentionSwitch;
		
		$gameSwitches.setValue(switchId,abstention);
		if(!abstention)
		{
			this.scoreFinalResult();
			$gameMajiangSystem.engraveResult();
		}
		this.executeTerminationFunc(abstention);
		this.replayBgmAndBgs();
		this.setTerminate();
	};
	MajiangManager.scoreFinalResult = function()
	{
		const finalResult = this.finalResult();
		
		for(const result of finalResult)
		{
			const position = $gameMajiangSystem.gpPosition(result.position);
			
			$gameMajiangSystem.setResult("rank_" + position , result.ranking);
			$gameMajiangSystem.setResult("point_" + position , result.finalPoint);
		}
	};
	
	MajiangManager.executeTerminationFunc = function(abstention)
	{
		$gameMajiangSystem.executeTerminationFunc(abstention);
	};
	
	MajiangManager.refreshVisiblePaizi = function()
	{
		$gameMajiangBattlers.allBattlers().forEach(b => b.refreshVisiblePaizi());
	};
	
	MajiangManager.requestSync = function()
	{
		this.refreshVisiblePaizi();
		this._requests.push("sync");
	};
	
	MajiangManager.requestFadeIn = function()
	{
		this._requests.push("fadeIn");
	};
	
	MajiangManager.requestFadeOut = function()
	{
		this._requests.push("fadeOut");
	};
	
	MajiangManager.requestOpenAllWindows = function()
	{
		this._requests.push("openAllWindows");
	};
	
	MajiangManager.requestCloseAllWindows = function()
	{
		this._requests.push("closeAllWindows");
	};
	
	MajiangManager.requestCloseStatusWindow = function()
	{
		this._requests.push("closeStatusWindow");
	};
	
	MajiangManager.requestInputDapai = function()
	{
		this._requests.push("inputDapai");
	};
	/*MajiangManager.requestNextGameScene = function()
	{
		this._requests.push("nextGameScene");
	};*/
	MajiangManager.requestStartChoice = function()
	{
		
		this._requests.push("startChoice");
	};
	
	MajiangManager.requestTerminate = function()
	{
		this._requests.push("terminate");
	};
	
	MajiangManager.setChoiceCondition = function(items,methodName) 
	{
		this._choiceCoidition = {"items" : items , "methodName" : methodName}
	};
	
	MajiangManager.choiceCondition = function(items,method) 
	{
		return this._choiceCoidition;
	};
	
	MajiangManager.clearRequests = function()
	{
		this._requests = [];
	};
	
	MajiangManager.requests = function()
	{
		return this._requests;
	};
	
	
	
	
	
	
	
	
	
	MajiangManager.textFeng = function(feng)
	{
		return $dataMajiangSystem.text[["dong","nan","xi","bei"][feng - 1]];
	};
	
	MajiangManager.textShuzi = function(value)
	{
		return $gameMajiangSystem.shuzi(value);
	};
	
	MajiangManager.textChangStatus = function(feng,ju)
	{
		
		return $dataMajiangSystem.text.ju.format(this.textFeng(feng) , this.textShuzi(ju));
	};
	
	MajiangManager.gangCount = function()
	{
		return this._gangCount;
	};
	
	MajiangManager.canGang = function()
	{
		return (this.gangCount() < 4);
	}
	
	MajiangManager.textCurrentChangStatus = function()
	{
		return this.textChangStatus(this._quanfeng,this._ju);
	};
	
	MajiangManager.addHelejia = function(battler)
	{
		this._heleJia.push(battler);
	};
	
	MajiangManager.helejia = function()
	{
		return this._heleJia;
	};
	
	MajiangManager.startHele = function(helePai)
	{
		for(const helejia of this.helejia())
		{
			const animationId = helejia.heleAnimation();
			if(animationId)
			{
				$gameTemp.requestAnimation(helePai , animationId);
			}
		}
		this.helejia().forEach(b => b.daopai());
		this.requestSync();
		this.startEndYiju();
	};
	
	MajiangManager.setHele = function()
	{
		this.resetPointHistory();
		this.resultPoint();
		this.setLianzhuang(true);
		
		const helejia = this.helejia()
			
		for(const battler of $gameMajiangBattlers.allBattlers())
		{
			if(helejia.includes(battler))
			{
				battler.setHeleTehai();
			}
			else
			{
				battler.clearLianHele();
			}
		}
		this._nextLizhibo = "clear";
		
		if(this.isDealerHele())
		{
			this._nextTsumibo = "add";
		}
		else
		{
			this._nextTsumibo = "clear";
		}
	};
	
	MajiangManager.setLiuju = function()
	{
		this.resetPointHistory();
		
		$gameMajiangBattlers.allBattlers().forEach(b => b.clearLianHele())
		
		if(this._liuju === "huangpaiPingju")
		{
			this.setLianzhuang(false);
			$gameMajiangBattlers.allBattlers().forEach(b => b.liujuResultDaopai());
			this.resultLiuju();
		}
		else
		{
			this._lianzhuang = false;
			this._restart = true;
		}
		this._nextTsumibo = "add";
	};
	
	MajiangManager.isDealerHele = function()
	{
		return this._heleJia.some(b => b.isDealer());
	};
	
	MajiangManager.scoreSettingsKey = function()
	{
		if(this.duo())
		{
			return "duoSettings";
		}
		else if(this.samma())
		{
			return "scoreSettingsSamma";
		}
		else
		{
			return "scoreSettings";
		}
	};
	
	MajiangManager.scoreSettings = function()
	{
		const key = this.scoreSettingsKey();
		return $gameMajiangSystem[key];
	};
	
	MajiangManager.lizhiDeposit = function(point)
	{
		return $gameMajiangSystem.config.lizhiDeposit ?? 1000;
	};
	
	MajiangManager.lizhiboPoint = function(point)
	{
		return (this._lizhibo.length) * this.lizhiDeposit();
	};
	
	MajiangManager.tsumifu = function(rong)
	{
		let tsumifu = 0;
		if(rong)
		{
			tsumifu = this.scoreSettings().tsumifuRong;
		}
		else
		{
			tsumifu = this.scoreSettings().tsumifuZimo;
		}
		
		return tsumifu * this.tsumibo();
	};
	
	MajiangManager.resultPoint = function()
	{
		const allBattlers = $gameMajiangBattlers.allBattlers();
		if(this._fangchongjia)
		{
			this.resultPointRong(this.helejia(),this._fangchongjia,allBattlers);
		}
		else
		{
			this.resultPointZimo(this.helejia(),allBattlers);
		}
		
	};
	
	MajiangManager.resetPointHistory = function()
	{
		$gameMajiangBattlers.allBattlers().forEach(b => b.resetPointHistory());
	};
	
	MajiangManager.resultLiuju = function()
	{
		if($gameMajiangBattlers.allBattlers().some(b => b.isNagashiMangan()))
		{
			this.resultLiujuNagashiMangan();
		}
		else
		{
			this.resultLiujuNormal();
		}
	};
	
	MajiangManager.resultLiujuNormal = function()
	{
		const all = $gameMajiangBattlers.allBattlers();
		const tingpai = all.filter(b => b.isTingpai());
		const noting = all.filter(b => !b.isTingpai());
		const fafuPoint = 1000 * (this.numBattlers() - 1);
		const stationary = ([0,this.numBattlers()].includes(tingpai.length));
		const point = ((stationary) ?  0 : (fafuPoint / tingpai.length));
		const lost = ((stationary) ?  0 : (fafuPoint / noting.length));
		
		tingpai.forEach(b => b.gainPoint(point));
		noting.forEach(b => b.gainPoint(-lost));
	};
	
	MajiangManager.resultLiujuNagashiMangan = function()
	{
		const allBattlers = $gameMajiangBattlers.allBattlers();
		const nagashiBattlers = allBattlers.filter(b => b.isNagashiMangan());
		let base = 0;
		
		switch($gameMajiangSystem.settings.nagashiManganPoint)
		{
			case "mangan" : base = 2000; break; 
			case "haneman" : base = 3000; break; 
			case "baiman" : base = 4000; break; 
			case "sambaiman" : base = 6000; break; 
			case "yakuman" : base = 8000; break;  
		}
		
		const payment = [
			{gain : 0 , lost : 0},
			{gain : 0 , lost : 0},
			{gain : 0 , lost : 0},
			{gain : 0 , lost : 0}
		];
		
		for(const nagashi of nagashiBattlers)
		{
			let gain = 0;
			for(const battler of allBattlers)
			{
				let total = 0;
				if(nagashi === battler) continue;
				if(nagashi.isDealer())
				{
					total += base * 2;
				}
				else
				{
					total += ((battler.isDealer()) ? (base * 2) : base);
				}
				gain += total;
				payment[battler.position()].lost += total;
			}
			payment[nagashi.position()].gain = gain;
		}
		
		for(const battler of allBattlers)
		{
			const subject = payment[battler.position()];
			const gainPoint = subject.gain - subject.lost;
			battler.gainPoint(gainPoint);
		}
	};
	
	
	MajiangManager.resultPointRong = function(helejia,fangchongjia,allBattlers)
	{
		let total = 0;
		let pointResult = [];
		
		const length = helejia.length;
		
		helejia.forEach(function(battler,i)
		{
			const result = battler.heleResult()
			
			let point = result.point.point ;
			if(!$gameMajiangSystem.settings.tsumifuKamijia
				|| i === 0
			)
			{
				point += this.tsumifu(this._isRong);
			}
			total += point;
			
			let gainPoint = point; 
			if(i === 0)
			{
				gainPoint += this.lizhiboPoint();
			}
			
			battler.gainPoint(gainPoint);
		},this);
		
		fangchongjia.gainPoint(-total);
	};
	
	MajiangManager.resultPointZimo = function(helejia,allBattlers)
	{
		helejia = helejia[0];
		const result = helejia.heleResult();
		
		let total = 0;
		for(const battler of allBattlers)
		{
			if(battler === helejia)
			{
				continue;
			}
			let point = result.point.point[(battler.isDealer()) ? 1 : 0];
			point += this.tsumifu(false);
			battler.gainPoint(-point);
			total += point;
		}
		
		total += this.lizhiboPoint();
		
		helejia.gainPoint(total);
	};
	
	MajiangManager.setLianzhuang = function(hele)
	{
		if($gameMajiangSystem.config.rsLianzhuang)
		{
			this._lianzhuang = false;
			return;
		}
		if(hele)
		{
			this._lianzhuang = (this.helejia().some(b => b.isDealer()))
		}
		else
		{
			this._lianzhuang = ($gameMajiangBattlers.dealer().isTingpai());
		}
	};
	
	MajiangManager.makeResultSequence = function()
	{
		const ret = [];
		if(this._liuju === "huangpaiPingju")
		{
			ret.push({"kind" : "liuju"});
		}
		else
		{
			for(const battler of this.helejia())
			{
				ret.push({"kind" : "hele" , "battler" : battler});
			}
		}
		if(this.checkGameEnd())
		{
			ret.push({"kind" : "finalResult"});
			ret.push({"kind" : "terminate" , "gotoNext" : true});
		}
		else
		{
			ret.push({"kind" : "nextGame" , "gotoNext" : true});
		}
		return ret;
	};
	
	MajiangManager.resultSequence = function()
	{
		return this._resultSequence;
	};
	
	MajiangManager.ranking = function(battlers)
	{
		const qijia = battlers.find(b => b.isQijia());
		const startPosition = qijia.position();
		const ret = [];
		let position = startPosition;
		for(let i = 0; i < this.numBattlers() ; i++)
		{
			ret.push(battlers.find(b => b.position() === position));
			position = this.nextPositionId(position);
		}
		
		ret.sort((a,b) => b.finalPoint() - a.finalPoint());
		return ret;
		
	};
	
	MajiangManager.currentRanking = function()
	{
		return this.ranking($gameMajiangBattlers.allBattlers());
	};
	
	MajiangManager.topBattler = function()
	{
		const battlers = this.currentRanking();
		return battlers[0];
	};
	MajiangManager.lastBattler = function()
	{
		const battlers = this.currentRanking();
		return battlers[this.numBattlers() - 1];
	};
	
	MajiangManager.dealerTop = function()
	{
		return this.topBattler().isDealer();
	};
	
	MajiangManager.checkGameEnd = function()
	{
		if($gameMajiangSystem.gamerule.tobi === 1)
		{
			const threshold = -1;
			if($gameMajiangBattlers.allBattlers().some(b => (b.point() <=  threshold)))
			{
				return true;
			}
		}
		if(!this.canKaeriDong() && (this.lastJu() && this.lastFeng()))
		{
			return true;
		}
		const lower = this.scoreSettings().lower;
		if($gameMajiangBattlers.allBattlers().every(b => (b.point() < lower)))
		{
			return false;
		}
		
		return (this.currentAllLast()
		 && (!this.isLianzhuang() || this.dealerTop())
		 && (this.suddenDeath() || this.lastJu())
		);
	};
	
	MajiangManager.isLianzhuang = function()
	{
		return this._lianzhuang;
	};
	MajiangManager.suddenDeath = function()
	{
		return !($gameMajiangSystem.config.rsSuddenDeath);
	};
	MajiangManager.lastJu = function()
	{
		return (this.currentJu() === MajiangManager.numBattlers());
	};
	
	MajiangManager.lastFeng = function()
	{
		return (this.currentQuanfeng() === MajiangManager.numBattlers());
	};
	
	MajiangManager.canKaeriDong = function()
	{
		return !$gameMajiangSystem.config.rsKaeriDong;
	};
	
	MajiangManager.currentAllLast = function()
	{
		return this.isAllLast(this._juCount);
	};
	
	
	MajiangManager.isAllLast = function(juCount)
	{
		const match = $gameMajiangSystem.condition.match;
		if(match === 3)
		{
			return (juCount >= 1);
		}
		if(this.duo())
		{
			switch(match)
			{
				case 0 : return (juCount >= 2);
				case 1 : return (juCount >= 4);
				case 2 : return (juCount >= 8);
			}
		}
		else if(this.samma())
		{
			switch(match)
			{
				case 0 : return (juCount >= 3);
				case 1 : return (juCount >= 6);
				case 2 : return (juCount >= 9);
			}
		}
		else
		{
			switch(match)
			{
				case 0 : return (juCount >= 4);
				case 1 : return (juCount >= 8);
				case 2 : return (juCount >= 16);
			}
		}
	};
	
	MajiangManager.makeFinalResult = function()
	{
		this._finalResult = [];
		const battlers = this.currentRanking();
		this.setTembo();
		battlers.forEach(function(battler,i)
		{
			const ret = {};
			ret.position = battler.position();
			ret.ranking = i + 1;
			ret.finalBasePoint = battler.point();
			
			if(ret.ranking === 1)
			{
				ret.finalBasePoint += this.lizhiboPoint();
			}
			
			ret.finalBasePoint += this.umaPoint(ret.ranking);
			
			ret.finalPoint = 0;
			this._finalResult.push(ret);
		},this);
		
		this.setFinalPoint();
	};
	
	MajiangManager.playerTop = function()
	{
		return this.topBattler().isPlayer();
	}
	
	MajiangManager.umaPoint = function(rank)
	{
		if(this.duo())
		{
			switch(rank)
			{
				case 1 : return this.scoreSettings().uma1_2;
				case 2 : return -this.scoreSettings().uma1_2;
			}
		}
		if(this.samma())
		{
			switch(rank)
			{
				case 1 : return this.scoreSettings().uma1_3;
				case 2 : return 0;
				case 3 : return -this.scoreSettings().uma1_3;
			}
		}
		else
		{
			switch(rank)
			{
				case 1 : return this.scoreSettings().uma1_4;
				case 2 : return this.scoreSettings().uma2_3;
				case 3 : return -this.scoreSettings().uma2_3;
				case 4 : return -this.scoreSettings().uma1_4;
			}
		}
	};
	
	MajiangManager.setFinalPoint = function()
	{
		const totalPointArray = [];
		const adoptOka = this.scoreSettings().adoptOka;
		const basePoint = this.scoreSettings().basePoint;
		const okaPoint = this.scoreSettings().point;
		for (const result of this._finalResult)
		{
			const bPoint = result.finalBasePoint - ((adoptOka) ? okaPoint : 0);
			const finalPoint = this.pointRounding(bPoint);
			totalPointArray.push(finalPoint);
			result.finalPoint = finalPoint;
		}
		if(adoptOka && okaPoint !== basePoint)
		{
			const okaRank = (okaPoint > basePoint) ? 0 : (this.numBattlers() - 1);
			
			totalPointArray[okaRank] = 0;
			const total = totalPointArray.reduce((r,c) => r + c , 0);
			this._finalResult[okaRank].finalPoint = -total;
		}
	};
	
	MajiangManager.pointRounding = function(point)
	{
		switch(this.scoreSettings().rounding)
		{	
			case 1 : 
				return this.round5(point / 1000) * 1000;
			break;
			case 2 : 
				return Math.round(point / 1000) * 1000;
			break;
			case 3 : 
				return this.round5(point / 1000);
			break;
			case 4 :
				return Math.round(point / 1000);
			break;
			default :
			    return point;
		}
	};
	
	MajiangManager.round5 = function(value)
	{
	    let ret = Math.abs(value);
	    ret = Math.round(ret - 0.1);
	    return ret * ((value < 0) ? -1 : 1);
	};
	
	MajiangManager.finalResult = function()
	{
		return this._finalResult;
	};
	
	MajiangManager.playAudio = function(audioKey)
	{
		const data = $gameMajiangSystem.audioData[audioKey];
		
		if(data && data.enabled)
		{
			switch(data.kind)
			{
				case "bgm" : AudioManager.playBgm(data.data); break;
				case "bgs" : AudioManager.playBgs(data.data); break;
				case "se" : AudioManager.playSe(data.data); break;
				case "me" : AudioManager.playMe(data.data); break;
			}
		}
	};
	
	MajiangManager.stopBgm = function()
	{
		AudioManager.fadeOutBgm(1);
	};
	
	
	
	
	
	
	
})();









