using System;
using System.Collections;
using System.Collections.Generic;
using Core.AssetLoadTool.Asset;
using Fort23.UTool;
#if !COMBAT_SERVER
using Fort23.Core;
using UnityEngine;
#endif
using Utility;
using Object = UnityEngine.Object;

public class AssetLoadTaskBasic : LoadTaskBasic
{
#if !COMBAT_SERVER
    private List<LoadAssetCallBackData> loadEndCallBackData = new List<LoadAssetCallBackData>();


    private Object objAsset;
    private List<AssetHandle> _loadAssetHandles = new List<AssetHandle>();

    protected bool _isUnloadType;
    private int _callBackCount;

    public int HandCount
    {
        get { return _loadAssetHandles.Count; }
    }

    public void InitAsset<T>(AssetInfo bundleInfo, bool isUnloadType,
        LoadAssetCallBackData loadEndCallBack)
        where T : Object
    {
        _isUnloadType = isUnloadType;

        _assetInfo = bundleInfo;

        loadState = LoadState.Load;
        AddCallBack<T>(loadEndCallBack);

        StartLoadAsset<T>();
    }

    protected virtual void StartLoadAsset<T>() where T : Object
    {
    }

    public void LoadFinish<T>(Object objAsset)
    {
        this.objAsset = objAsset;
        LoadAsset<T>();
    }

    public void Dispose()
    {
        if (loadState == LoadState.Disposed)
        {
            return;
        }

        objAsset = null;
        loadEndCallBackData.Clear();

        if (AssetBundleLoadManager.Instance != null)
        {
            AssetBundleLoadManager.Instance.RemoveAssetTask(_assetInfo);
        }

        loadState = LoadState.Disposed;
        ProDispose();
    }

    protected virtual void ProDispose()
    {
    }

    public void RemoveAssetHandle(AssetHandle assetHandle)
    {
        _loadAssetHandles.Remove(assetHandle);
        if (_loadAssetHandles.Count <= 0 && _callBackCount <= 0)
        {
            Dispose();
        }
    }

    private void LoadAsset<T>()
    {
        if (loadEndCallBackData.Count <= 0 || objAsset == null)
        {
            if (objAsset == null)
            {
                LogTool.Error(ToString() + "   " + _assetInfo.name + "资源没有了");
            }
            else
            {
                LogTool.Error(ToString() + "   " + _assetInfo.name + " 回掉没有了");
            }

            return;
        }

        if (loadState != LoadState.Load)
        {
            LogTool.Error(_assetInfo.name + " 以释放不能在加载");
            return;
        }

        loadState = LoadState.End;
        LoadAssetCallBackData[] delegateArr = loadEndCallBackData.ToArray();
        _callBackCount = delegateArr.Length;
        for (int i = 0; i < delegateArr.Length; i++)
        {
            _callBackCount--;
            ExecutionCallBack<T>(delegateArr[i]);
        }

        loadEndCallBackData.Clear();
        _callBackCount = 0;
    }

    protected void ExecutionCallBack<T>(LoadAssetCallBackData loadAssetCallBackData)
    {
        // Debug.Log("加载资源"+_assetInfo.name);
        if (loadAssetCallBackData.Clock != null && loadAssetCallBackData.Clock.isBreak)
        {
            loadAssetCallBackData.loadEndCallBack?.Invoke(null, loadAssetCallBackData.userData);
            return;
        }

        InstantiateSync<T>(loadAssetCallBackData.loadEndCallBack, loadAssetCallBackData.userData,
            loadAssetCallBackData.isUseSynchronous);
    }

    public async CTask<AssetHandle> InstantiateSync(bool isUseSynchronous)
    {
        if (objAsset == null)
        {
            return null;
        }

        AssetHandle assetHandle = new AssetHandle();
        try
        {
            UnityEngine.Object go = objAsset;
            if ((go is GameObject)) //Prefab类型
            {
                //异步unity目前有bug,先不要使用
                // AsyncInstantiateOperation asyncInstantiateOperation = Object.InstantiateAsync<GameObject>(objAsset as GameObject);
                //
                // if (isUseSynchronous)
                // {
                //     asyncInstantiateOperation.WaitForCompletion();
                // }
                // else
                // {
                //     CTask cTask = CTask.Create(false);
                //     asyncInstantiateOperation.completed += delegate(AsyncOperation operation)
                //     {
                //         cTask.SetResult();
                //     };
                //     await cTask;
                // }

                // go = asyncInstantiateOperation.Result[0];
                go = Object.Instantiate(objAsset);
                go.name = _assetInfo.name;
            }

            assetHandle.Init(this, go);
            _loadAssetHandles.Add(assetHandle);
        }
        catch (Exception e)
        {
            LogTool.Error("资源加载出问题" + _assetInfo.name + "___" + e.Message);
            LogTool.Error(e);
        }

        return assetHandle;
    }

    private async CTask InstantiateSync<T>(System.Action<AssetHandle, object> callBack, object userData,
        bool isUseSynchronous)
    {
        try
        {
            AssetHandle assetHandle = await InstantiateSync(isUseSynchronous);
            callBack(assetHandle, userData);
        }
        catch (System.Exception e)
        {
            LogTool.Error(_assetInfo.name + "_" + e);
            CallErrorBack();
        }
    }

    protected override void ProUpdate()
    {
        for (int i = 0; i < _loadAssetHandles.Count; i++)
        {
            bool isActivation = _loadAssetHandles[i].IsActivation();
            if (!isActivation)
            {
                _loadAssetHandles[i].Release();
            }
        }
    }

    public void AddCallBack<T>(LoadAssetCallBackData loadEndCallBack)
    {
        //LogTool.Log("assetAddCallBack" + assetName);
        if (loadState == LoadState.End)
        {
            ExecutionCallBack<T>(loadEndCallBack);
            return;
        }

        loadEndCallBackData.Add(loadEndCallBack);
    }


    protected void CallErrorBack()
    {
        for (int i = 0; i < loadEndCallBackData.Count; i++)
        {
            LoadAssetCallBackData loadAssetCallBackData = loadEndCallBackData[i];
            loadAssetCallBackData.loadEndCallBack?.Invoke(null, loadAssetCallBackData.userData);
        }

        _callBackCount = 0;
        loadEndCallBackData.Clear();
    }
#endif
}