using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AIAAgent.Models;
using System.Web.SessionState;
using Newtonsoft.Json;
using System.Net;
using System.Web.Script.Serialization;
using System.Collections.Specialized;
using System.Configuration;
using AIAAgentCommon.Models;
using Kendo.Mvc.Extensions;
using AIAAgentCommon;

namespace AIAAgent.Controllers
{
    [AIAAgent.Helpers.Suspension]
    public class TravelEliteController : Controller
    {
        private string WebAPIURL = ConfigurationManager.AppSettings["AIAAgent_WebAPI_URL"].ToString();
        static NLog.ILogger _logger = NLog.LogManager.LogFactory.GetCurrentClassLogger();
        private readonly RestClient _restClient;

        public TravelEliteController()
        {
            _restClient = new RestClient();
        }

        protected void ConvertResponseErrorMsg(ref List<ErrorReturn> ErrorList)
        {
            foreach (var e in ErrorList)
            {
                if (string.IsNullOrEmpty(e.ExtraValue))
                {
                    if (HttpContext.GetGlobalResourceObject("ErrMsg", e.ErrorCode) != null)
                    {
                        e.Value = HttpContext.GetGlobalResourceObject("ErrMsg", e.ErrorCode).ToString();
                    }
                    else
                    {
                        e.Value = e.ErrorCode;
                    }
                }
                else
                {
                    e.Value = string.Format(HttpContext.GetGlobalResourceObject("ErrMsg", e.ErrorCode).ToString(), e.ExtraValue);
                }
            }
        }

        [HttpPost]
        [Helpers.RedirectHttps]
        public ActionResult ReCalculatePremium(decimal DiscountRate)
        {
            string api_url = WebAPIURL + "TravelReCalPremium";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new
            {
                SalesDiscountRate = DiscountRate,
                AppNo = this.AppNo,
                Coverage = Session["TypeofCoverage"].ToString(),
                Lang = Common.Lang,
                Channel = Common.Channel,
                AgentCode = (Session["AgentCode"] == null) ? string.Empty : Session["AgentCode"].ToString()
            });

            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }
            TravelReCalPremiumResponseObj response = JsonConvert.DeserializeObject<TravelReCalPremiumResponseObj>(APIReturn.Json);
            return Json(response.PremiumDetail);
        }

        [HttpPost]
        public ActionResult CheckAppNo(string AppNo)
        {
            return Json(AppNo == this.AppNo);
        }

        [Helpers.RedirectHttps]
        public ActionResult Start()
        {
            return RedirectToAction("Application");
        }

        [Helpers.RedirectHttps]
        [Helpers.ExchangeKey]
        public ActionResult MyeTran(string exchgkey, string channelcode, string functioncode)
        {
            if (Session["ProdCode"] == null || string.IsNullOrEmpty(Session["ProdCode"].ToString()) || Session["MyeTranAppNo"] == null || string.IsNullOrEmpty(Session["MyeTranAppNo"].ToString()))
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                _logger.Error("here");
                return new HttpStatusCodeResult(500);
            }

            string ProdCode = Session["ProdCode"].ToString();
            string MyeTranAppNo = Session["MyeTranAppNo"].ToString();
            _logger.Error("lllllllllllllllll");
            ViewBag.AgentName = Session["AgentName"]?.ToString() ?? "";

            string api_url = WebAPIURL + "TravelMyeTran";
            _logger.Error(api_url);
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new
            {
                ProductCode = ProdCode,
                AppNo = MyeTranAppNo,
                Lang = Common.Lang
            });
            _logger.Error(APIReturn);

            TravelCalPremiumResponseObj returnObj = JsonConvert.DeserializeObject<TravelCalPremiumResponseObj>(APIReturn.Json);
            ViewBag.Channel = returnObj.Channel;
            _logger.Error("here here");

            return View("MyeTran" + ProdCode, returnObj.Confirm);
        }

        [HttpPost]
        [Helpers.RedirectHttps]
        public ActionResult ResendEmail(string Email)
        {
            if (Session["ProdCode"] == null || string.IsNullOrEmpty(Session["ProdCode"].ToString()) || Session["MyeTranAppNo"] == null || string.IsNullOrEmpty(Session["MyeTranAppNo"].ToString()))
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }

            string api_url = WebAPIURL + "ResendEmail";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new
            {
                ProductCode = Session["ProdCode"].ToString(),
                AppNo = Session["MyeTranAppNo"].ToString(),
                Email = Email
            });

            GeneralAPIResponseObj respObj = JsonConvert.DeserializeObject<GeneralAPIResponseObj>(APIReturn.Json);

            if (respObj.Status == "SUCCESS")
            {
                return Json(true);
            }
            else if (respObj.Status == "FAIL" && respObj.ErrorList.Count() > 0)
            {
                this.ConvertResponseErrorMsg(ref respObj.ErrorList);
                return Json(respObj.ErrorList);
            }
            else
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }
        }

        [Helpers.RedirectHttps]
        [Helpers.ExchangeKey]
        public ActionResult Application(string exchgkey, string channelcode, string functioncode, bool skipClearSession = false)
        {
            var coverage = "AST";
            if (Session["TypeofCoverage"] != null)
                coverage = Session["TypeofCoverage"].ToString();

            if (Session["TRAVELAPPLY"] != null && (bool)Session["TRAsuVELAPPLY"] == true)
            {
                Session["TRAVELAPPLY"] = null;
                Session.Remove("TRAVELAPPLY");
            }
            else
            {
                if (!skipClearSession)
                {
                    Session["TRAVELAPPLYLOGIN"] = null;
                    Session["TravelCampaignCode"] = null;
                    Session["TravelAgreement1"] = null;
                    Session["TravelAgreement2"] = null;
                    Session["TravelAgreement3"] = null;
                    Session["TravelAgreement4"] = null;
                    Session["TravelAgreement5"] = null;
                    Session["TravelAgreement6"] = null;
                    Session["TravelAgreement7"] = null;
                    Session["IsInsured"] = null;
                    Session["ReApply_AppNo"] = null;
                    Session["TypeofCoverage"] = null;
                    Session["Travel_AppNo"] = null;
                    Session["Type"] = null;
                    Session["TRAVELAdult"] = null;
                    Session["TRAVELChild"] = null;

                    Session.Remove("TravelCampaignCode");
                    Session.Remove("TravelAgreement1");
                    Session.Remove("TravelAgreement2");
                    Session.Remove("TravelAgreement3");
                    Session.Remove("TravelAgreement4");
                    Session.Remove("TravelAgreement5");
                    Session.Remove("TravelAgreement6");
                    Session.Remove("TravelAgreement7");
                    Session.Remove("IsInsured");
                    Session.Remove("ReApply_AppNo");
                    Session.Remove("TypeofCoverage");
                    Session.Remove("Travel_AppNo");
                    Session.Remove("Type");
                    Session.Remove("TRAVELAdult");
                    Session.Remove("TRAVELChild");
                }
            }


            Guid nTokenid = Guid.NewGuid();
            Session["TravelFormToken"] = nTokenid.ToString();
            Session["Travelrenew"] = false;

            var nApp = new OnlineTravelForm(coverage);

            string api_url = WebAPIURL + "TravelSetting";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new { Channel = Common.Channel, Coverage = coverage, Lang = Common.Lang });
            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }

            string SpAnnouncement = "";
            EDM.WebSysInfoEntities dbSys = new EDM.WebSysInfoEntities();
            var Record = (from a in dbSys.tbSetTravelAppAnnouncements
                          where a.Channel == Common.Channel && a.ProductCode == coverage && a.EffectiveStartDate <= DateTime.Now && a.EffectiveEndDate >= DateTime.Now
                          select a).ToList();

            if (Record.Count() > 0)
            {
                SpAnnouncement = Common.Lang.ToUpper() == "CHI" ? Record.First().Announcement_TC : Record.First().Announcement_EN;
            }

            nApp.Setting = JsonConvert.DeserializeObject<Models.TravelSetting>(APIReturn.Json);
            nApp.FormToken = nTokenid.ToString();
            nApp.SpecialAnnouncement = SpAnnouncement;
            ViewBag.IsShow = nApp.Setting.IsShow;
            return View(nApp);
        }


        [Helpers.RedirectHttps]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Application(string Type)
        {
            if (Session["TypeofCoverage"] == null)
            {

                Session["Type"] = null;
                return RedirectToAction("Application");
            }
            var onlineForm = new OnlineTravelForm(Session["TypeofCoverage"].ToString());

            if (!string.IsNullOrEmpty(AppNo))
            {
                onlineForm.CurrentAppNo = AppNo;
                Session["Type"] = "reapply";
            }

            string api_url = WebAPIURL + "TravelSetting";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new { Channel = Common.Channel, Coverage = onlineForm.TypeofCoverage, Lang = Common.Lang });
            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }
            onlineForm.Setting = JsonConvert.DeserializeObject<Models.TravelSetting>(APIReturn.Json);

            Guid nTokenid = Guid.NewGuid();
            Session["TravelFormToken"] = nTokenid.ToString();
            onlineForm.FormToken = nTokenid.ToString();
            onlineForm.SpecialAnnouncement = "";
            return View(onlineForm);
        }

        [HttpPost]
        [Helpers.RedirectHttps]
        [ValidateAntiForgeryToken]
        public ActionResult Apply(OnlineTravelForm App)
        {

            bool form = checkToken(App.FormToken);
            if (form == false)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return RedirectToAction("Application");
            }


            if (Session["Type"] != null && Session["Type"].ToString() == "reapply")
            {
                if (Session["TypeofCoverage"] != null)
                {
                    App = new OnlineTravelForm(Session["TypeofCoverage"].ToString());
                }
                App.CurrentAppNo = AppNo;
                ViewBag.isReapply = true;
            }

            App.Adult = (Session["TRAVELAdult"] != null) ? (int)Session["TRAVELAdult"] : App.Adult;
            App.Child = (Session["TRAVELChild"] != null) ? (int)Session["TRAVELChild"] : App.Child;
            string strType = (Session["Type"]) == null ? null : Session["Type"].ToString();
            string api_url = WebAPIURL + "TravelQuote";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new
            {
                Lang = Common.Lang,
                App = App,
                IsInsured = (Session["IsInsured"] == null) ? true : (bool)Session["IsInsured"],
                Type = strType,
                CreditTerm = (Session["CreditTerm"] == null) ? "N" : Session["CreditTerm"].ToString(),
                DefaultEmail = (Session["DefaultEmail"] == null) ? string.Empty : Session["DefaultEmail"].ToString(),
                AgentCode = (Session["AgentCode"] == null) ? string.Empty : Session["AgentCode"].ToString(),
                Channel = Common.Channel
            });
            Session.Remove("Type");

            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }

            TravelQuoteResponseObj returnObj = JsonConvert.DeserializeObject<TravelQuoteResponseObj>(APIReturn.Json);
            if (returnObj.ErrorList.Count() > 0)
            {
                this.ConvertResponseErrorMsg(ref returnObj.ErrorList);
                return Json(returnObj.ErrorList);
            }
            if (returnObj.Apply != null && returnObj.Apply.InsuredDetail != null && returnObj.Apply.InsuredDetail.Count() > 0)
            {
                var iDtl = returnObj.Apply.InsuredDetail;
                foreach (var rec in iDtl)
                {
                    if (rec.nDOB.Year == 1 && rec.nDOB.Month == 1 && rec.nDOB.Day == 1)
                    {
                        rec.nDOB.Year = 0;
                        rec.nDOB.Month = 0;
                        rec.nDOB.Day = 0;
                    }
                }
            }

            Session["TRAVELAdult"] = returnObj.Apply.Adult;
            Session["TRAVELChild"] = returnObj.Apply.Child;
            Session["TypeofCoverage"] = returnObj._coverage;
            this.AppNo = returnObj.Apply.AppNo;

            if (App.TypeofCoverage == "AST" || App.TypeofCoverage == "AAT")
            {
                ModelState.Clear();
                return PartialView("_Apply" + App.TypeofCoverage, returnObj.Apply);
            }

            return RedirectToAction("Application");
        }

        [Helpers.RedirectHttps]
        public ActionResult Error()
        {
            if (Session["CheckTerrorist"] != null && Session["CheckTerrorist"].ToString() == AppNo)
            {
                AppNo = string.Empty;
                Session["CheckTerrorist"] = null;
                Session.Remove("CheckTerrorist");
                return View();
            }
            else
            {
                return RedirectToAction("Application");
            }
        }

        [Helpers.RedirectHttps]
        public ActionResult Fail()
        {
            if (Session["ErrorMsg"] != null)
            {
                ViewBag.ErrorMsg = Session["ErrorMsg"].ToString();
                Session.Remove("Error");
                return View();
            }
            return RedirectToAction("Application");
        }

        [Helpers.RedirectHttps]
        public ActionResult SendEmailFail(string caseNo)
        {
            if (string.IsNullOrWhiteSpace(caseNo))
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = "Case No can not be empty.";
                return new HttpStatusCodeResult(500);
            }
            ViewBag.CaseNo = caseNo;
            return View();
        }

        [HttpPost]
        [Helpers.RedirectHttps]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitCalculatePremium(TravelPremium Premium)
        {
            string api_url = WebAPIURL + "TravelCalPremium";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new
            {
                AppNo = this.AppNo,
                PremiumDetail = Premium,
                Coverage = Session["TypeofCoverage"].ToString(),
                AgentCode = (Session["AgentCode"] == null) ? null : Session["AgentCode"].ToString(),
                Lang = Common.Lang,
                Channel = Common.Channel
            });

            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }

            TravelCalPremiumResponseObj returnObj = JsonConvert.DeserializeObject<TravelCalPremiumResponseObj>(APIReturn.Json);
            if (!string.IsNullOrEmpty(returnObj.CheckTerrorist))
            {
                Session["CheckTerrorist"] = returnObj.CheckTerrorist;
                return RedirectToAction("Error");
            }
            if (returnObj.ErrorList.Count() > 0)
            {
                this.ConvertResponseErrorMsg(ref returnObj.ErrorList);
                return Json(returnObj.ErrorList);
            }

            if (returnObj.Confirm.IsPaymentLink)
            {
                returnObj.Confirm.isCreditCard = false;
                returnObj.Confirm.isCreditTerm = false;
            }

            if (returnObj._coverage == "AST" || returnObj._coverage == "AAT")
            {
                ViewBag.TargetAction = "Confirm" + returnObj._coverage;
                return PartialView("_Confirm" + returnObj._coverage, returnObj.Confirm);
            }
            else
            {
                return RedirectToAction("Application");
            }
        }

        [HttpPost]
        [Helpers.RedirectHttps]
        [ValidateAntiForgeryToken]
        public ActionResult ConfirmAST(string AppNo, string ApplyType, bool IsPaymentLink, string ApplicantEmailAddress)
        {
            if (AppNo != this.AppNo || string.IsNullOrEmpty(this.AppNo))
            {
                string MessageID = AIAAgentAPI.Common.Logging.GetUnitCode("WERR");
                Common.LogError("I", "TravelEliteController", "Session expired in online application", "Action = Confirm, Message ID = " + MessageID);
                Session["Error"] = true;
                Session["ErrorMsg"] = string.Format(HttpContext.GetGlobalResourceObject("ErrMsg", "Message7").ToString(), MessageID);
                if (AppNo != this.AppNo)
                {
                    return new HttpStatusCodeResult(500, "skipClearSession");
                }
                else
                {
                    return new HttpStatusCodeResult(500);
                }
            }

            if (IsPaymentLink)
            {
                string api_url = WebAPIURL + $"TravelElite/GetDataForPaymentLink?appNo={AppNo}&type=AST";
                var response = _restClient.RestClientGet(api_url);

                var dataResponse = JsonConvert.DeserializeObject<ApiResponse<PaymentLinkCreateDate>>(response.Content);
                var data = dataResponse.Data;
                string agentCode = Session["AgentCode"] as string;
                var createResult = CreatePaymentLink(new OAPaymentLinkModel
                {
                    AgentId = agentCode,
                    ApplicantType = data.Application,
                    AppNo = AppNo,
                    CreateBy = agentCode,
                    CreateDate = DateTime.Now,
                    Email = ApplicantEmailAddress,
                    //PaymentLinkDetails = Applicant.AppDetail
                    PlanCode = data.Plan,
                    PolicyEffectiveDateFrom = data.EffectiveDateFrom,
                    PolicyEffectiveDateTo = data.EffectiveDateTo,
                    PolicyHolder = data.Application.Equals("I", StringComparison.InvariantCultureIgnoreCase) ? data.SurName + " " + data.GivenName : data.CompanyName,
                    ProductCode = "AST",
                    ProductNameCh = "單次旅行保障",
                    ProductNameEn = "Single-trip Cover",
                    Status = PaymentLinkStatus.PendingPayment,
                    Rider = string.Empty,
                    FailCallbackUrl = string.Empty,
                    RePayCallbackUrl = string.Empty,
                    SuccessCallbackUrl = string.Empty,
                });

                if (createResult.Item1)
                {
                    SendEmail(createResult.Item2);
                    return PartialView("_PaymentLinkSuccess", new ReSendPaymentLinkEmail { CaseNo = createResult.Item2 });
                }
                else
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    return new HttpStatusCodeResult(500);
                }
            }
            else
            {
                string api_url = WebAPIURL + "TravelASTConfirm";
                APIHelper api = new APIHelper();
                var APIReturn = api.CallWebAPI(api_url, "POST", new
                {
                    AppNo = AppNo,
                    Language = Common.Lang,
                    Channel = Common.Channel,
                    CreditTerm = (Session["CreditTerm"] == null) ? "N" : Session["CreditTerm"].ToString(),
                    AgentCode = (Session["AgentCode"] == null) ? null : Session["AgentCode"].ToString()
                });

                if (APIReturn.StatusCode != 200)
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    return new HttpStatusCodeResult(500);
                }

                TravelConfirmResponseObj returnObj = JsonConvert.DeserializeObject<TravelConfirmResponseObj>(APIReturn.Json);
                if (!string.IsNullOrEmpty(returnObj.CheckTerrorist))
                {
                    Session["CheckTerrorist"] = returnObj.CheckTerrorist;
                    return RedirectToAction("Error");
                }

                if (!string.IsNullOrEmpty(returnObj.PaymentMethod))
                {
                    if (returnObj.PaymentMethod == "CT")
                    {
                        return Json(true);
                    }
                    else
                    {
                        return Json(returnObj.PaymentMethod);
                    }
                }
                else
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    return new HttpStatusCodeResult(500);
                }
            }

        }


        [Helpers.RedirectHttps]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ConfirmAAT(string AppNo, string ApplyType, bool IsPaymentLink, string ApplicantEmailAddress)
        {
            if (AppNo != this.AppNo || string.IsNullOrEmpty(this.AppNo))
            {
                string MessageID = AIAAgentAPI.Common.Logging.GetUnitCode("WERR");
                Common.LogError("I", "TravelEliteController", "Session expired in online application", "Action = Confirm, Message ID = " + MessageID);
                Session["Error"] = true;
                Session["ErrorMsg"] = string.Format(HttpContext.GetGlobalResourceObject("ErrMsg", "Message7").ToString(), MessageID);
                if (AppNo != this.AppNo)
                {
                    return RedirectToAction("Application", new { skipClearSession = true });
                }
                else
                {
                    return RedirectToAction("Application");
                }
            }

            if (IsPaymentLink)
            {
                string api_url = WebAPIURL + $"TravelElite/GetDataForPaymentLink?appNo={AppNo}&type=AAT";
                var response = _restClient.RestClientGet(api_url);

                var dataResponse = JsonConvert.DeserializeObject<ApiResponse<PaymentLinkCreateDate>>(response.Content);
                var data = dataResponse.Data;
                string agentCode = Session["AgentCode"] as string;
                var createResult = CreatePaymentLink(new OAPaymentLinkModel
                {
                    AgentId = agentCode,
                    ApplicantType = data.Application,
                    AppNo = AppNo,
                    CreateBy = agentCode,
                    CreateDate = DateTime.Now,
                    Email = ApplicantEmailAddress,
                    //PaymentLinkDetails = Applicant.AppDetail
                    PlanCode = data.Plan,
                    PolicyEffectiveDateFrom = data.EffectiveDateFrom,
                    PolicyEffectiveDateTo = data.EffectiveDateTo,
                    PolicyHolder = data.Application.Equals("I", StringComparison.InvariantCultureIgnoreCase) ? data.SurName + " " + data.GivenName : data.CompanyName,
                    ProductCode = "AAT",
                    ProductNameCh = "全年保障",
                    ProductNameEn = "Annual Cover",
                    Status = PaymentLinkStatus.PendingPayment,
                    Rider = string.Empty,
                    FailCallbackUrl = string.Empty,
                    RePayCallbackUrl = string.Empty,
                    SuccessCallbackUrl = string.Empty,
                });

                if (createResult.Item1)
                {
                    SendEmail(createResult.Item2);
                    return PartialView("_PaymentLinkSuccess", new ReSendPaymentLinkEmail { CaseNo = createResult.Item2 });
                }
                else
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    return new HttpStatusCodeResult(500);
                }
            }
            else
            {
                string api_url = WebAPIURL + "TravelAATConfirm";
                APIHelper api = new APIHelper();
                var APIReturn = api.CallWebAPI(api_url, "POST", new
                {
                    AppNo = AppNo,
                    Channel = Common.Channel,
                    Language = Common.Lang,
                    AgentCode = (Session["AgentCode"] == null) ? null : Session["AgentCode"].ToString(),
                    CreditTerm = (Session["CreditTerm"] == null) ? "N" : Session["CreditTerm"].ToString()
                });

                if (APIReturn.StatusCode != 200)
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    return new HttpStatusCodeResult(500);
                }

                TravelConfirmResponseObj returnObj = JsonConvert.DeserializeObject<TravelConfirmResponseObj>(APIReturn.Json);
                if (!string.IsNullOrEmpty(returnObj.CheckTerrorist))
                {
                    Session["CheckTerrorist"] = returnObj.CheckTerrorist;
                    return RedirectToAction("Error");
                }

                if (!string.IsNullOrEmpty(returnObj.PaymentMethod))
                {
                    if (returnObj.PaymentMethod == "CT")
                    {
                        return Json(true);
                    }
                    else
                    {
                        return Json(returnObj.PaymentMethod);
                    }
                }
                else
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    return new HttpStatusCodeResult(500);
                }
            }
        }


        public string GetTokenid()
        {
            if ((bool)Session["Travelrenew"])
            {
                Guid nTokenid = Guid.NewGuid();
                Session.Remove("TravelFormToken");
                Session.Remove("Travelrenew");
                Session.Add("TravelFormToken", nTokenid.ToString());
                Session.Add("Travelrenew", false);
                return nTokenid.ToString();
            }
            else
            {
                return Session["TravelFormToken"].ToString();
            }
        }


        public string AppNo
        {
            get
            {
                return Session["Travel_AppNo"] == null ? "" : Session["Travel_AppNo"].ToString();
            }
            set
            {
                Session["Travel_AppNo"] = value;
            }
        }

        public bool checkToken(string SubmitToken)
        {
            if (Session["TravelFormToken"] == null)
            {
                return false;
            }

            if (Session["TravelFormToken"].ToString() == SubmitToken)
            {
                Session["Travelrenew"] = true;
                Session["TravelFormToken"] = string.Empty;
                return true;
            }
            else
            {
                return false;
            }
        }

        [HttpPost]
        [Helpers.RedirectHttps]
        public ActionResult GetToken()
        {
            string nTokenid = GetTokenid();
            return Json(nTokenid.ToString());
        }


        [HttpPost]
        [Helpers.RedirectHttps]
        [ValidateAntiForgeryToken]
        public ActionResult SubmitAST(ApplyTravel Applicant)
        {
            try
            {
                if (Applicant.AppNo != AppNo || string.IsNullOrEmpty(AppNo))
                {
                    Common.LogError("I", "TravelEliteController", "Session expired in online application", "Action = Submit");
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Message7").ToString();
                    if (Applicant.AppNo != AppNo)
                    {
                        return new HttpStatusCodeResult(500, "skipClearSession");
                    }
                    else
                    {
                        return new HttpStatusCodeResult(500);
                    }
                }
                Applicant.isCreditCard = Applicant.isPaymentLink ? true : Applicant.isCreditCard;

                Applicant.Adult = (int)Session["TRAVELAdult"];
                Applicant.Child = (int)Session["TRAVELChild"];
                string api_url = WebAPIURL + "TravelASTApply";
                APIHelper api = new APIHelper();
                var APIReturn = api.CallWebAPI(api_url, "POST", new
                {
                    App = Applicant,
                    Coverage = Session["TypeofCoverage"] as string,
                    AgentCode = Session["AgentCode"] as string,
                    Lang = Common.Lang,
                    Channel = Applicant.isPaymentLink ? Common.Channel_VIP : Common.Channel,
                    //BuzLine = Applicant.isPaymentLink ? Common.Channel_VIP : Common.Channel
                });

                if (APIReturn.StatusCode != 200)
                {
                    Session["Error"] = true;
                    Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                    Common.LogError("E", "TravelEliteController", "SubmitAST API Error", "Action = Submit");
                    return new HttpStatusCodeResult(500);
                }

                TravelApplyResponseObj returnObj = JsonConvert.DeserializeObject<TravelApplyResponseObj>(APIReturn.Json);
                if (returnObj.ErrorList.Count() > 0)
                {
                    this.ConvertResponseErrorMsg(ref returnObj.ErrorList);
                    return Json(returnObj.ErrorList);
                }

                return PartialView("_CalculatePremium", returnObj.PremiumDetail);
            }
            catch (Exception Ex)
            {
                Common.LogError("E", "TravelEliteController", Ex.ToString(), "AppNo: " + Applicant.AppNo);
                return new HttpStatusCodeResult(500);
            }
        }


        [Helpers.RedirectHttps]
        [HttpPost]
        public ActionResult SubmitAAT(ApplyTravel Applicant)
        {
            if (Applicant.AppNo != this.AppNo || string.IsNullOrEmpty(this.AppNo) && Session["CheckSubmit"] != null && Applicant.AppNo != Session["CheckSubmit"].ToString())
            {
                Common.LogError("I", "TravelEliteController", "Session expired in online application", "Action = Submit");
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Message7").ToString();
                if (Applicant.AppNo != this.AppNo)
                {
                    return new HttpStatusCodeResult(500, "skipClearSession");
                }
                else
                {
                    return new HttpStatusCodeResult(500);
                }
            }

            Applicant.isCreditCard = Applicant.isPaymentLink ? true : Applicant.isCreditCard;
            Applicant.Adult = (int)Session["TRAVELAdult"];
            Applicant.Child = (int)Session["TRAVELChild"];
            string paymentLinkCreateUrl = WebAPIURL + "TravelAATApply";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(paymentLinkCreateUrl, "POST", new
            {
                App = Applicant,
                Channel = Applicant.isPaymentLink ? Common.Channel_VIP : Common.Channel,
                AgentCode = Session["AgentCode"] as string,
                Coverage = Session["TypeofCoverage"] as string,
                Lang = Common.Lang,
                BuzLine = Applicant.isPaymentLink ? Common.Channel_VIP : Common.Channel
            });

            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return new HttpStatusCodeResult(500);
            }

            TravelApplyResponseObj returnObj = JsonConvert.DeserializeObject<TravelApplyResponseObj>(APIReturn.Json);
            if (returnObj.ErrorList.Count() > 0)
            {
                this.ConvertResponseErrorMsg(ref returnObj.ErrorList);
                return Json(returnObj.ErrorList);
            }
            return PartialView("_CalculatePremium", returnObj.PremiumDetail);

        }

        [Helpers.RedirectHttps]
        public ActionResult Success(string AppNo)
        {
            if(!string.IsNullOrEmpty(AppNo)) 
            {
                Session["Travel_AppNo"] = AppNo;
            }
            string api_url = WebAPIURL + "TravelSuccess";
            APIHelper api = new APIHelper();
            var APIReturn = api.CallWebAPI(api_url, "POST", new
            {
                AppNo = this.AppNo,
                Channel = Common.Channel
            });

            if (APIReturn.StatusCode != 200)
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = HttpContext.GetGlobalResourceObject("ErrMsg", "Err02").ToString();
                return RedirectToAction("Application");
            }
            TravelSuccessResponseObj returnObj = JsonConvert.DeserializeObject<TravelSuccessResponseObj>(APIReturn.Json);
            if (!string.IsNullOrEmpty(returnObj.PolicyNo))
            {
                ViewBag.PolicyNo = returnObj.PolicyNo;
            }
            return View();
        }

        [Helpers.RedirectHttps]
        [HttpPost]
        public ActionResult ReSendEmailForPaymentLink(string caseNo)
        {
            if (string.IsNullOrWhiteSpace(caseNo))
            {
                Session["Error"] = true;
                Session["ErrorMsg"] = "Case No can not be empty.";
                return new HttpStatusCodeResult(500);
            }
            var sendResult = SendEmail(caseNo);
            if (sendResult.Item1)
            {
                return PartialView("_PaymentLinkSuccess", new ReSendPaymentLinkEmail { CaseNo = caseNo });
            }
            else
            {
                return PartialView("_PaymentLinkSendFail", new ReSendPaymentLinkEmail { CaseNo = caseNo });
            }
        }

        private Tuple<bool, string> CreatePaymentLink(OAPaymentLinkModel request)
        {
            string paymentLinkCreateUrl = WebAPIURL + "PaymentLink/Create";

            var response = _restClient.RestClientPost(paymentLinkCreateUrl, request);

            var createResponse = JsonConvert.DeserializeObject<ApiResponse<string>>(response.Content);
            if (createResponse != null && !createResponse.Success)
            {
                return new Tuple<bool, string>(false, createResponse.Message);
            }
            else
            {
                return new Tuple<bool, string>(true, createResponse.Data);
            }
        }

        private Tuple<bool, string> SendEmail(string caseNo)
        {
            string paymentLinkCreateUrl = WebAPIURL + $"PaymentLink/SendEmail?caseNo={caseNo}";

            var response = _restClient.RestClientPost(paymentLinkCreateUrl);

            var createResponse = JsonConvert.DeserializeObject<ApiResponse<string>>(response.Content);
            if (createResponse != null && !createResponse.Success)
            {
                return new Tuple<bool, string>(false, createResponse.Message);
            }
            else
            {
                return new Tuple<bool, string>(true, createResponse.Data);
            }
        }
    }
}