using AntDesign;
using Microsoft.AspNetCore.Components;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;
using wispro.sp.entity.workflowDefine;
using wispro.sp.web.Services;

namespace wispro.sp.web.Pages.Workflow
{
    public partial class WorkflowDetail
    {
        Components.FlowChart chart;

        entity.workflowDefine.Workflow workflow;
        List<entity.workflowDefine.Step> Steps;
        List<entity.workflowDefine.Action> Actions;
        List<entity.workflowDefine.TrasferCondition> Transfers;
        List<InputValueSetting> inputValueSettings;


        internal class StepItem
        {
            public string Name { get; set; }

            public int? StepId { get; set; }
            
        }

        UserField userField = new UserField();

        [Parameter]
        public int WorkflowId { get; set; }
        
        [Inject] protected MessageService _msgService { get; set; }

        [Inject] protected WorkflowService _wfService { get; set; }

        [Inject] protected IConfiguration _configuration { get; set; }

        string DownloadUrl;
        List<StepItem> stepItems;
        async Task InitData()
        {

            //int Id = int.Parse(WorkflowId.ToString());
            workflow = await _wfService.GetWorkflow(WorkflowId);
            Steps = await _wfService.GetSteps(WorkflowId);
            Actions = await _wfService.GetActions(WorkflowId);
            Transfers = await _wfService.GetTransfers(WorkflowId);

            DownloadUrl = $"{_configuration.GetValue<string>("APIUrl")}WorkflowEngine/ExportToImage?workflowId={workflow.Id}";

            stepItems = new List<StepItem>();
            stepItems.Add(new StepItem() { Name = "开始",StepId = 0});

            foreach(var step in Steps)
            {
                if (step.Id != workflow.EndStepId)
                {
                    stepItems.Add(new StepItem() { Name = step.Name, StepId = step.Id });
                }
            }

            stepItems.Add(new StepItem() { Name = "结束", StepId = workflow.EndStepId });
        }
        [Inject] protected IAuthService _authService { get; set; }
        protected async override Task OnInitializedAsync()
        {
            await _authService.CanVisitResource();

            await base.OnInitializedAsync();

            #region Demo流程数据
            await InitData();
            #endregion
        }

        

        void OnClickStep(entity.workflowDefine.Step step)
        {
            //_msgService.Info($"您点击了：【{step.Name}】步骤");
            
        }

        void OnDblClickStep(entity.workflowDefine.Step step)
        {
            bool b = (workflow.EndStepId != null && workflow.EndStepId.Value == step.Id);
            EditStep = new share.NewStepObject() { Step = step, isLastStep = b };
            try
            {
                //Console.WriteLine(step.defaultResponseSetting);
                userField = System.Text.Json.JsonSerializer.Deserialize<UserField>(step.defaultResponseSetting);
                //Console.WriteLine($"Deserialize Result:{System.Text.Json.JsonSerializer.Serialize(userField)}" );
            }
            catch {
                userField = new UserField();
            }

            EditStep.actions = GetActions(step.Id);
            
            StepModalShow = true;

        }

        async void OnDblClickAction(entity.workflowDefine.Action action)
        {
            if (action.Id == workflow.InitAction.Id)
            {
                EditAction = new share.ActionObject();
                EditAction.Action = action;
            }
            else
            {
                //Console.WriteLine($"BeginEditAction-Begin:{System.Text.Json.JsonSerializer.Serialize(action)}");
                if (EditStep.actions != null)
                {
                    EditAction = EditStep.actions.FirstOrDefault(a => a.Action.Id == action.Id);
                }
            }

            
            if (EditAction != null)
            {
                if (EditAction.Action.Id > 0)
                {
                    EditAction.InputValueSettingObjects = await _wfService.getInputValueSteeing(EditAction.Action.Id);
                }
                ActionModalShow = true;
            }
            //Console.WriteLine($"BeginEditAction-End:{System.Text.Json.JsonSerializer.Serialize(EditAction)}");
            //StateHasChanged();
        }

        void OnDblClickTransfer(entity.workflowDefine.TrasferCondition transfer)
        {
            EditTransfer = transfer;
            TransferModalShow = true;
        }

        share.NewStepObject EditStep;
         
        share.ActionObject EditAction;
        entity.workflowDefine.TrasferCondition EditTransfer;

        bool StepModalShow = false;
        bool ActionModalShow = false;
        bool TransferModalShow = false;
        
        void AddNewStep()
        {
            EditStep = new share.NewStepObject();
            EditStep.Step = new entity.workflowDefine.Step() { Name = "新步骤", stepType = 2, workflowId = workflow.Id };
            EditStep.actions = new List<share.ActionObject>();
            EditStep.isLastStep = false;
            userField = new UserField();
            

            StepModalShow = true;
        }

        void AddNewAction()
        {
            EditAction = new share.ActionObject();
            EditAction.Action = new entity.workflowDefine.Action();
            EditAction.Action.Name = "新操作";
            EditAction.InputValueSettingObjects = new List<share.InputValueSettingObject>();

            if (EditStep.NewActions == null)
            {
                EditStep.NewActions = new List<share.ActionObject>();
            }

            EditStep.NewActions.Add(EditAction);
            
            ActionModalShow = true;
        }

        async Task BeginEditAction(int Id)
        {
            EditAction = EditStep.actions.FirstOrDefault(a => a.Action.Id == Id);

            //Console.WriteLine($"BeginEditAction-Begin:{System.Text.Json.JsonSerializer.Serialize(EditAction)}");
            if (EditAction != null)
            {
                if ( EditAction.Action.Id >0)
                {
                    EditAction.InputValueSettingObjects = await _wfService.getInputValueSteeing(EditAction.Action.Id);
                }
                ActionModalShow = true;
            }
            //Console.WriteLine($"BeginEditAction-End:{System.Text.Json.JsonSerializer.Serialize(EditAction)}");
        }

        async void DeleteAction(int Id)
        {
            var ret = await _wfService.DeleteAction(Id);

            if (!ret.Success)
            {
                await _msgService.Error("删除Action出错！");
            }
            else
            {
                Actions = await _wfService.GetActions(workflow.Id);
                EditStep.actions = GetActions(EditStep.Step.Id);
            }
        }

        void AddNewTransfer()
        {
            EditTransfer = new entity.workflowDefine.TrasferCondition();
            TransferModalShow = true;
        }

        List<share.ActionObject> GetActions(int stepId)
        {
            var actionList = Actions.Where<entity.workflowDefine.Action>(a=>a.StepId == stepId).ToList();
            List<share.ActionObject> retList = new List<share.ActionObject>();

            foreach(var ac in actionList)
            {
                share.ActionObject acobj = new share.ActionObject();
                acobj.Action = ac;
                retList.Add(acobj);
            }

            return retList;
        }

        async Task EditStepOK()
        {
            JsonSerializerOptions options = new() { IgnoreNullValues = true };
            EditStep.Step.defaultResponseSetting = System.Text.Json.JsonSerializer.Serialize(userField,options);
            //Console.WriteLine($"UsrValue={userField.UserValue},UserConditionType={userField.UserConditionType},UserType={userField.UserType}"); 
            //Console.WriteLine(EditStep.Step.defaultResponseSetting);

            var ret = await _wfService.SaveStep(EditStep);
            if (ret.Success)
            {
                StepModalShow = false;
                await InitData();
            }
            else
            {
                await _msgService.Error("保存出现错误！");
            }

            OnRefresh();
        }

        void EditStepCancel()
        {
            StepModalShow = false;
        }

        List<share.ActionObject> newActions;
        async Task EditActionOK()
        {
            if (EditStep != null)
            {
                if (!EditStep.actions.Contains(EditAction))
                {
                    EditStep.actions.Add(EditAction);

                    if (EditStep.NewActions == null)
                    {
                        EditStep.NewActions = new List<share.ActionObject>();
                    }

                    if (!EditStep.NewActions.Contains(EditAction))
                    {
                        EditStep.NewActions.Add(EditAction);
                    }
                }
                else
                {
                    if (EditStep.ModifyActions == null)
                    {
                        EditStep.ModifyActions = new List<share.ActionObject>();
                    }
                }

                if (!EditStep.ModifyActions.Contains(EditAction))
                {
                    EditStep.ModifyActions.Add(EditAction);
                }
                
            }

            ActionModalShow = false;
        }

        void EditActionCancel()
        {
            ActionModalShow = false;
        }

        async Task EditTransferOK()
        {
            
            //Console.WriteLine(System.Text.Json.JsonSerializer.Serialize(EditTransfer));

            if(EditTransfer.StepId!= null && EditTransfer.StepId.Value == 0)
            {
                EditTransfer.StepId = null;
            }

            var ret = await _wfService.SaveTransfer(EditTransfer);

            if (ret.Success)
            {
                TransferModalShow = false;
                await InitData();
                
                
            }
            else {
               await _msgService.Error("保存出现错误！");
            }

            OnRefresh();
        }

        void EditTransferCancel()
        {
            TransferModalShow = false;
        }

        void OnRefresh()
        {
            chart.Refresh();

            //StateHasChanged();
        }

        [Inject] ModalService _modalService { get; set; }
        async Task DeleteObject()
        {
            string strMsg = "";
            if (chart.SelectedObject != null)
            {
                if(chart.SelectedObject is entity.workflowDefine.TrasferCondition)
                {
                    TrasferCondition transfer = chart.SelectedObject as TrasferCondition;
                    await _wfService.DeleteTransfer(transfer);
                    strMsg = (transfer.StepId == null) ? "开始" : transfer.Step.Name;
                    strMsg = $"已删除{strMsg}的转移条件！";
                }

                if(chart.SelectedObject is entity.workflowDefine.Step)
                {
                    await _wfService.DeleteStep((entity.workflowDefine.Step)chart.SelectedObject);
                    strMsg = $"已删除步骤[{((entity.workflowDefine.Step)chart.SelectedObject).Name}]";
                }
            }

            await InitData();
            await _msgService.Info(strMsg);
            chart.Refresh();
        }
    }
}
