let callbackAction = "post";
let twoFactorSignature = "";

const signatureService = getKGICGCAPIATLSVIAdapterObj();

const SignatureHandler = {
	generateForWindows: (
		strategyId,
		symbolRoot,
		contractMonth,
		orderMultiplier,
		accountId,
	) => {
		return signatureService.FSCAPIKGISign_eDDA(
			userId,
			`${strategyId},${symbolRoot},${contractMonth},${orderMultiplier},${accountId},${clientIp}`,
			signatureType,
			certType,
			algothrim,
			encoding,
		);
	},

	requestForMobile: (data) => {
		const url =
			deviceType === "android"
				? `kgi://mode=sign;id=${userId};signtype=${signatureType};order=${data};callback=AgreementCallback`
				: `kgi://?mode=sign;id=${userId};signtype=${signatureType};order=${data};callback=AgreementCallback`;

		Logger.logInfo(
			`向E策略請求憑證簽章中... userId=${userId}, clientId=${clientIp}, url=${url}`,
		);

		window.location.href = url;
	},
};

const AgreementCallback = (id, errorCode, signedOrderData, caSn) => {
    Logger.logInfo(`憑證簽章回調函數被調用. userId=${userId}, clientId=${clientIp}, errorCode=${errorCode}, signedOrderData=${signedOrderData}, caSn=${caSn}, id-${id}, action=${callbackAction}`);

	if (callbackAction === "auth" && twoFactorSignature === "") {
		if (errorCode != "0") {
			alert(`雙因子憑證檢驗失敗, 請檢查憑證. ${errorCode}`);
			CurrentUser.signOut();
			return;
		}

        twoFactorSignature = signedOrderData;
        clearInterval(mobileTwoFactorChecker);
        Logger.logInfo(`雙因子憑證簽章成功. UserId=${userId}`);
		return;
	}

	if (callbackAction === "post") {
		if (errorCode != "0") {
			alert(`簽署失敗, 請檢查憑證. ${errorCode}`);
			Logger.logError(
				`啟用條件單簽章失敗. Error code: ${errorCode}. userId=${userId}`,
			);
			return;
        }
        
        Logger.logInfo(`憑證簽章成功, 正在啟用條件單... id=${id}, userId=${userId}`);

		InternalApiClient.createTradingCondition(
			CreateTradingConditionRequest.createForMobile(signedOrderData, caSn),
		);
		return;
	}

	if (callbackAction === "bulkPost") {
		if (errorCode != "0") {
			alert(`簽署失敗, 請檢查憑證. ${errorCode}`);

			pendingRequests = [];
			expectedPendingRequestsCount = 0;
			return;
        }
        
        Logger.logInfo(`憑證簽章成功, 正在啟用條件單... id=${id}, userId=${userId}`);

		pendingRequests.push(
			CreateTradingConditionRequest.createForMobile(
				signedOrderData,
                caSn,
                pendingStrategyIds[pendingRequests.length],
			),
		);

		if (pendingRequests.length !== expectedPendingRequestsCount) {
			return;
		}
        
        Logger.logInfo(`憑證簽章成功, 正在啟用全部條件單... id=${id}, userId=${userId}`);
        InternalApiClient.bulkCreateTradingConditions(pendingRequests);
        pendingRequests = [];
        pendingStrategyIds = [];
        expectedPendingRequestsCount = 0;

		return;
	}
};
