using System.Collections.Generic;
using System.Threading.Tasks;

namespace WS
{
    ///<summary>模块组件</summary>
    public class ModuleComponent : WSComponent
    {
        private ProcessManager process;
        ///<summary>流程管理期</summary>
        private ProcessManager Process
        {
            get
            {
                if (process == null)
                    process = (ProcessManager)Parent;
                return process;
            }
        }
        ///<summary>Id</summary>
        public int Id { get { return Data.Id; } }
        ///<summary>名称</summary>
        public string Name { get { return Data.Name; } }
        ///<summary>忽略任务栏</summary>
        public bool NoTaskbar { get { return Data.NoTaskbar; } }
        ///<summary>没有顺序</summary>
        public bool NoOrder { get { return Data.NoOrder; } }
        ///<summary>当前任务Id</summary>
        public int VTaskId { get { return CurrentVTask.Id; } }
        ///<summary>分数</summary>
        public float Score;
        ///<summary>是否完成</summary>
        public bool IsComplete;
        ///<summary>数据</summary>
        public Module Data;
        ///<summary>所有任务</summary>
        private List<WSTaskComponent> VTasks = new List<WSTaskComponent>();
        ///<summary>当前任务</summary>
        private WSTaskComponent CurrentVTask;

        public void Update()
        {
            if (NoOrder)
            {
                for (int i = 0; i < VTasks.Count; i++)
                {
                    if (!VTasks[i].IsComplete)
                        VTasks[i].Update();
                }
                OnComplete();
            }
            else
            {
                if (CurrentVTask != null)
                {
                    if (!CurrentVTask.IsComplete)
                        CurrentVTask.Update();
                    else
                        SwitchVTask(CurrentVTask.Id + 1);
                }
            }
        }

        ///<summary>无序判断是否完成</summary>
        private void OnComplete()
        {
            bool complete = !VTasks.Exists(v => v.IsComplete == false);
            IsComplete = complete;
            if (IsComplete)
            {
                Settlement();
            }
        }

        ///<summary>开始模块</summary>
        public void StartModule()
        {
#if UNITY_EDITOR || DEBUG_MODEL
            Log.LogDebug($"进入模块:{Name} ID:{Id}", WSLogType.橙);
#endif
            List<int> performids = new List<int>();
            for (int i = 0; i < Data.WSTasks.Count; i++)
            {
                if (Data.WSTasks[i].Perform)
                {
                    performids.Add(Data.WSTasks[i].PerformId);
                }
            }
            for (int i = 0; i < Data.WSTasks.Count; i++)
            {
                WSTaskComponent vtask = ComponentFactory.CreateWithParent<WSTaskComponent>(this);
                vtask.Data = Data.WSTasks[i];
                VTasks.Add(vtask);
                if (NoOrder)
                {
                    if (!performids.Exists(l => l == Data.WSTasks[i].Id))
                        vtask.StartVTask();
                }
                if (!NoTaskbar)
                {
                    WSTaskRecord record = new WSTaskRecord { Id = VTasks[i].Id, Score = VTasks[i].Score, Module = Name, Name = VTasks[i].Name ,IsEnd =false};
                    Process.AddVTaskRecord(record);
                }
            }
            if (!NoOrder)
                SwitchVTask(VTasks[0].Id);
        }

        ///<summary>下一个模块</summary>
        public async Task NextModule()
        {
            try
            {
                for (int i = 0; i < VTasks.Count; i++)
                {
                    if (NoOrder)
                    {
                        if (!VTasks[i].IsComplete)
                            await VTasks[i].JumpVTask(false);
                    }
                    else
                    {
                        if (VTasks[i].Id >= VTaskId)
                            await VTasks[i].JumpVTask(false);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Log.LogError(ex);
            }
        }

        ///<summary>跳转步骤</summary>
        ///<param name="Id">Id</param>
        ///<param name="invertedorder">倒序</param>
        public async Task<bool> JumpVTask(int Id, bool invertedorder)
        {
            bool exists = false;
            try
            {
                exists = VTasks.Exists(t => t.Id == Id);
                if (!invertedorder)
                {
                    for (int i = CurrentVTask.Id - 1; i < VTasks.Count; i++)
                    {
                        if (VTasks[i].Id < Id)
                            await VTasks[i].JumpVTask(invertedorder);
                    }
                }
                else
                {
                    for (int i = CurrentVTask.Id - 1; i >= 0; i--)
                    {
                        if (VTasks[i].Id >= Id)
                            await VTasks[i].JumpVTask(invertedorder);
                    }
                }
                if (exists)
                    SwitchVTask(Id);
                else
                    IsComplete = true;
            }
            catch (System.Exception ex)
            {
                Log.LogError(ex);
            }
            return exists;
        }

        ///<summary>上一步</summary>
        ///<param name="newmd">新模块</param>
        public async Task<bool> LastVTask(bool newmd)
        {
            try
            {
                if (newmd)
                {
                    WSTaskComponent vTask = VTasks[VTasks.Count - 1];
                    await vTask.JumpVTask(true);
                    SwitchVTask(vTask.Id - 1);
                }
                else
                {
                    await CurrentVTask.JumpVTask(true);
                    int index = VTasks.FindIndex(v => v == CurrentVTask);
                    if (index == 0)
                    {
                        IsComplete = false;
                        return false;
                    }
                    else
                    {
                        WSTaskComponent vTask = VTasks.Find(t => t.Id == CurrentVTask.Id - 1);
                        if (vTask!=null)
                            await vTask.JumpVTask(true);
                        SwitchVTask(CurrentVTask.Id - 1);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Log.LogError(ex);
            }
            return true;
        }

        ///<summary>下一步</summary>
        public async Task NextVTask()
        {
            try
            {
                await CurrentVTask.JumpVTask(false);
                SwitchVTask(CurrentVTask.Id + 1);
            }
            catch (System.Exception ex)
            {
                Log.LogError(ex);
            }
        }

        ///<summary>结算</summary>
        public void Settlement()
        {
            for (int i = 0; i < VTasks.Count; i++)
            {
                if (VTasks[i].IsComplete)
                {
                    if (!VTasks[i].IsError)
                        Score += VTasks[i].Score;
                }
                else
                {
                    if (!NoTaskbar)
                    {
                        WSTaskRecord record = Process.GetVTaskRecord(VTasks[i].Id);
                        record.IsError = true;
                    }
                }
            }
        }

        ///<summary>获取任务</summary>
        public WSTaskComponent GetVTask(int vtaskid)
        {
            return VTasks.Find(t => t.Id == vtaskid);
        }

        ///<summary>提示</summary>
        public void Prompt()
        {
            CurrentVTask.Prompt();
        }

        ///<summary>切换任务</summary>
        private void SwitchVTask(int id)
        {
            WSTaskComponent vTask = VTasks.Find(t => t.Id == id);
            if (vTask != null)
            {
                CurrentVTask = vTask;
                CurrentVTask.StartVTask();
            }
            else
            {
                Settlement();
                IsComplete = true;
            }
        }

        public override void Dispose()
        {
            base.Dispose();
            //////Score = 0;            //////Score = 0;
            IsComplete = false;
            Data = null;
            for (int i = 0; i < VTasks.Count; i++)
            {
                VTasks[i].Dispose();
            }
            VTasks.Clear();
            CurrentVTask = null;
        }
    }
}