using Bizgaze.CRM;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Unibase.Data;
using Unibase.Data.Expressions;
using Unibase.Data.Sql;
using Unibase.Dependency;
using Unibase.Platform.Apps.Managers;
using Unibase.Platform.Data;
using Unibase.Platform.Forms.Providers;
using Unibase.Platform.Keys;

namespace CRM.Visitors.ActionProviders
{
    class FeedBackPostActionProvider : BaseFormActionProvider, IFormActionProvider
    {
        public string ControllerClass
        {
            get
            {
                return "Bizgaze.CRM.Visitors.ActionProviders.FeedBackPostActionProvider";

            }
        }
        public string FormActionName
        {
            get
            {
                return "FeedBack";
            }
        }/// <summary>
        /// test 123
        /// </summary>
        public string Description
        {
            get
            {
                return "Feed Back Pos tAction Provider";
            }
        }
        public UniqueKey UniqueId
        {
            get
            {
                return Bizgaze.CRM.Actions.FeedBack;
            }
        }
        public int ActionType
        {
            get
            {
                return (int)Unibase.Platform.Forms.Enums.FormActionProvider.PostAction;
            }
        }
        //public ActionResponse<ExpandoObject> Execute(ActionRequest request, object IdValue, ExpandoObject obj, List<Unibase.Platform.Forms.Requests.DocParameter> docParametersList, ref long defaultPKValue)
        //{
        //    return null;

        //}
        public async Task<ActionResponse<FormActionResponse>> ExecuteAsync(ActionRequest request, FormActionProviderObject providerObject)
        {
            using (var requestTrans = await request.BeginTransactionAsync())
            {
                var IdValue = providerObject.IdValue;
                var srequest = SelectRequest.FromRequest(request);
                var obj = providerObject.RequestObject;
                var docParametersList = providerObject.DocParametersList;
                dynamic visitorparam = new Dictionary<string, object>();
                var defaultPKValue = providerObject.DefaultPKValue;
                var stageManager = Unibase.Dependency.DependencyConfig.Resolve<IStageManager>();
                var visitorManager = Unibase.Dependency.DependencyConfig.Resolve<Bizgaze.CRM.Visitors.Managers.IVisitorManager>();
                var dictObj = obj as IDictionary<string, dynamic>;                
                var connection = GetConnection(request);
                ExpandoObject obj1 = dictObj["RequestObj"];
                var req = obj1 as IDictionary<string, object>;
                var code = Convert.ChangeType(req["uniqueid"].ToString(), typeof(object)).ToString();
                var feedBackJson = Convert.ChangeType(req["feedbackrating"].ToString(), typeof(object)).ToString();
                var feedBackObj = JsonSerializer.Deserialize<Request.VisitorRequest>(feedBackJson);
                var comments = feedBackObj.Comments;
                var rating = feedBackObj.Rating;
                var visitorInfo = await visitorManager.GetpreVisitorsAsync(srequest, code);
                if (visitorInfo != null)
                {
                    var visitorId = Convert.ToInt64(visitorInfo.Result.VisitorId);                    
                    var sql = new Unibase.Data.Sql.Select("bizgazecrm_visitors").Columns("bizgazecrm_visitors.installedappid", "bizgazecrm_visitors.fullname", "bizgazecrm_visitors.mobilenumber", "bizgazecrm_visitors.emailid", "bizgazecrm_visitors.photourl", "unibase_stagestatus.stageStatusName", "unibase_stagestatus.RefStatusId").InnerJoin("unibase_stages", Exp.EqColumns("unibase_stages.stageid", "bizgazecrm_visitors.stageid")).InnerJoin("unibase_stagestatus", Exp.EqColumns("unibase_stagestatus.stagestatusid", "unibase_stages.stagestatusid")).Where("bizgazecrm_visitors.visitorid", visitorId);
                    List<Parameter> param = new List<Parameter>();
                    param.Add(new Parameter("@bizgazecrm_visitors.visitorid", visitorId));
                    var dt = GetDataTable(srequest, sql, param);                    
                    var stageStatusName = "";                   
                    if (dt.Rows.Count > 0)
                    {                        
                      stageStatusName = "CheckOut";
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {                           
                            var installedAppId = Convert.ToInt64(dt.Rows[i]["installedAppId"]);                            
                            var stage = stageManager.GetStageByStageStatus(srequest, installedAppId, stageStatusName);
                            var NewStageId = stage.Result.StageId;
                            var UpdateStage = new Update("bizgazecrm_visitors").Value("stageid", NewStageId).Where(Exp.Eq("visitorId", visitorId));
                            _repository.Execute(request, UpdateStage);
                        }
                        var options = new EntityOptions()
                        {
                            IsIdentity = true,
                            IsNewEntity = true,
                            TableName = "bizgazecrm_visitorcheckout",
                            PkColumn = "visitorcheckoutid",
                            IsExcludeFromAudit = false,
                            Id = 0,
                        };
                        dynamic visitor = new Dictionary<string, object>();
                        visitor.Add("createdby", srequest.Identity.UserId);
                        visitor.Add("createddate", DateTime.Now);
                        visitor.Add("checkoutdate", DateTime.Now);
                        visitor.Add("comments", comments);
                        visitor.Add("rating", Convert.ToInt32(rating));
                        visitor.Add("versionguid", Guid.NewGuid());
                        visitor.Add("uniqueid", code);                       
                        visitor.Add("statusid", (int)RowStatus.Active);
                        visitor.Add("installedappid", visitorInfo.Result.Installedappid);
                        visitor.Add("visitorid", visitorInfo.Result.VisitorId);
                        var responses = await _repository.SaveAsync(request, options, visitor);
                        if (responses.Status == ResponseStatus.Error)
                        {
                            if (requestTrans.StartedLocal) await request.RollbackTransactionAsync();
                            return ActionResponse<FormActionResponse>.CreateErrorResponse("1", "Visitor Check Out Data Not Saved");
                        }
                    }                    
                }
                var returnresponse = new FormActionResponse();
                returnresponse.Obj = dictObj as ExpandoObject;
                returnresponse.PkValue = defaultPKValue;
                return ActionResponse<FormActionResponse>.CreateSuccessResponse("success", returnresponse);
            }
        }
        public List<UniqueKey> AppliedApps
        {
            get
            {
                return new List<UniqueKey>() {
                    Bizgaze.CRM.Actions.FeedBack,
            };
            }
        }
    }
}
