using SceneEditor.Proxy.Editor;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Thousandto.Cfg.Data;
using Thousandto.Code.Logic;
using Thousandto.Core.Base;
using UnityEditor;

namespace Thousandto.Package
{
    /// <summary>
    /// 生成fls文件的工具类, 暂时不用
    /// </summary>
    public class FlsUtils
    {
        public static string SubFlsRoot = "../SubResource/FLS/";
#if UNITY_ANDROID
        public static string SubAllRoot = "../SubResource/Android/ResAll/";
        static string _subResRoot = "../SubResource/Android/ResAll/GameAssets/Resources/";
#elif UNITY_IPHONE
        public static string SubAllRoot = "../SubResource/IOS/ResAll/";
        static string _subResRoot = "../SubResource/IOS/ResAll/GameAssets/Resources/";
#elif UNITY_WEBPLAYER
        public static string SubAllRoot = "../SubResource/WebPlayer/ResAll/";
        static string _subResRoot = "../SubResource/WebPlayer/ResAll/GameAssets/Resources/";
#else //windows
        public static string SubAllRoot = "../SubResource/Windows/ResAll/";
        static string _subResRoot = "../SubResource/Windows/ResAll/GameAssets/Resources/";
#endif
        static string _assetRoot = "Assets/GameAssets/Resources/";
        static string _cinematicPath = "Cinematics";
        static string _lanStr = LanguageConstDefine.KR;

        //默认3段
        static int _partialCount = 3;

        public static void Build(string lan)
        {
            _lanStr = lan;
            Start();
        }

        public static void Start()
        {
            EditorUtility.DisplayProgressBar("生成FLS文件", "", 0);
            var oldFlsList = Utils.GetFiles(SubFlsRoot, "*.fls", SearchOption.TopDirectoryOnly, PkgConstDefine.CommonExceptionEx);
            foreach (string oldFls in oldFlsList)
            {
                string parent = Path.GetDirectoryName(oldFls);
                if (!parent.EndsWith("FLS"))
                {
                    continue;
                }
                File.Delete(oldFls);
            }

            //删除旧的分段资源
            Utils.DeleteFileOrDir(string.Format("../SubResource/{0}/Res1", PackageManager.GetSourceDirByBuildTarget()));
            Utils.DeleteFileOrDir(string.Format("../SubResource/{0}/Res2", PackageManager.GetSourceDirByBuildTarget()));
            Utils.DeleteFileOrDir(string.Format("../SubResource/{0}/Res3", PackageManager.GetSourceDirByBuildTarget()));

            EditorUtility.DisplayProgressBar("生成FLS文件", "", 0.3f);

            //这里开始自动分fls
            work();

            //拷贝fls0到FLS目录
            string fls0 = SubFlsRoot + _lanStr + "/fls0.fls";
            if (File.Exists(fls0))
                File.Copy(fls0, SubFlsRoot + "fls0.fls");

            //拷贝fls.fls到上一级目录
            string fls = SubFlsRoot + _lanStr + "/fls.fls";
            if (File.Exists(fls))
                File.Copy(fls, SubFlsRoot + "fls.fls");

            var newFlsList = Utils.GetFiles(SubFlsRoot, "*.fls", SearchOption.TopDirectoryOnly, PkgConstDefine.CommonExceptionEx);

            EditorUtility.DisplayProgressBar("生成FLS文件", "拷贝分段资源到对应目录", 0.9f);
            //下面是拷贝资源到分段资源路径
            //foreach (string newFls in newFlsList)
            //{
            //    string flsName = Path.GetFileNameWithoutExtension(newFls);
            //    string copyToDir = string.Format("../SubResource/{0}/", PackageManager.GetSourceDirByBuildTarget());
            //    if (flsName == "fls1")
            //    {
            //        copyToDir += "Res1";
            //    }
            //    else if (flsName == "fls2")
            //    {
            //        copyToDir += "Res2";
            //    }
            //    else if (flsName == "fls3")
            //    {
            //        copyToDir += "Res3";
            //    }

            //    var fileListInFls = File.ReadAllLines(newFls);
            //    //从1开始,第一行是描述
            //    for (int i = 0; i < fileListInFls.Length; ++i )
            //    {
            //        if (fileListInFls[i].IndexOf(",") != -1)
            //            continue;

            //        string sourceFile = SubAllRoot + fileListInFls[i];
            //        string toFile = copyToDir + "/" + fileListInFls[i];
            //        string toDir = toFile.Substring(0, toFile.LastIndexOf("/"));
            //        if (!Directory.Exists(toDir))
            //        {
            //            Directory.CreateDirectory(toDir);
            //        }
            //        if (File.Exists(sourceFile))
            //        {
            //            if (Path.GetFullPath(sourceFile) == Path.GetFullPath(toFile)) continue;
            //            File.Copy(sourceFile, toFile, true);
            //        }
            //    }
            //}
            EditorUtility.DisplayProgressBar("生成FLS文件", "完成", 1.0f);
            EditorUtility.ClearProgressBar();
        }

        private static void work()
        {
            LuaDataConverter.Load();
            var sceneCfgFileList = Utils.GetFiles(SubFlsRoot + _lanStr, "*.scene", SearchOption.TopDirectoryOnly);
            for (int i = 0; i < sceneCfgFileList.Count; ++i)
            {
                combineFls(sceneCfgFileList[i]);
            }
        }

        public static void Test2()
        {
            LuaDataConverter.Load();
            var itor = DeclareMapsetting.CacheData.Values.GetEnumerator();
            while (itor.MoveNext())
            {
                var mapID = itor.Current.MapId;
                string mapName = itor.Current.LevelName;
                var fileList = addDependenceRes(mapID);
                string filePath = SubFlsRoot + mapID + ".txt";
                File.WriteAllLines(filePath, fileList.ToArray());
                UnityEngine.Debug.LogError("生成场景关联文件列表: " + filePath);
            }

            EditorUtility.ClearProgressBar();
        }

        /// <summary>
        /// 根据MapSetting表生成资源列表
        /// </summary>
        public static void GenResListByMapSetting()
        {
            Dictionary<string, List<string>> mapDict = new Dictionary<string, List<string>>();
            mapDict.Clear();
            LuaDataConverter.Load();
            var itor = DeclareMapsetting.CacheData.Values.GetEnumerator();
            while (itor.MoveNext())
            {
                var mapID = itor.Current.MapId;
                //场景名字
                string mapName = itor.Current.LevelName;
                var fileList = addDependenceRes(mapID);
                if (mapDict.ContainsKey(mapName))
                {
                    List<string> pathList = mapDict[mapName];
                    for (int i = 0; i < fileList.Count; i++)
                    {
                        //去掉重复的资源路径
                        if (!pathList.Contains(fileList[i]))
                        {
                            pathList.Add(fileList[i]);
                        }
                    }
                    //再把新增的再保存到字典里面
                    mapDict[mapName] = pathList;
                }
                else
                {
                    mapDict.Add(mapName, fileList);
                }
            }
            
            //遍历场景的资源列表,生成文件
            var iter = mapDict.GetEnumerator();
            while (iter.MoveNext())
            {
                List<string> mapResPathList = iter.Current.Value;
                string filePath = SubFlsRoot + iter.Current.Key + ".txt";
                File.WriteAllLines(filePath, mapResPathList.ToArray());
                UnityEngine.Debug.LogError("根据MapSetting表生成资源列表: " + filePath);
            }
            EditorUtility.ClearProgressBar();
        }

        //合并.scene和.fls文件到新的fls文件
        private static void combineFls(string sceneFile)
        {
            //场景id列表
            string[] sceneIdArray = File.ReadAllLines(sceneFile);
            //场景关联资源
            List<string> sceneResList = new List<string>();
            for (int i = 0; i < sceneIdArray.Length; ++i)
            {
                EditorUtility.DisplayProgressBar("生成FLS文件", "搜索场景关联的资源", 0.5f);
                sceneResList.AddRange(addDependenceRes(sceneIdArray[i]));
            }

            EditorUtility.DisplayProgressBar("生成FLS文件", "收集场景资源", 0.7f);

            int count = 0;
            long size = 0;
            //去重,并且计算count和size
            var allRes = optimizeList(sceneResList, out count, out size);
            //合并场景资源和默认资源
            string flsFileName = Path.ChangeExtension(sceneFile, "fls");
            combineFlsFile(allRes, flsFileName, ref count, ref size);

            //合并默认路径
            string flsDir = Path.ChangeExtension(sceneFile, "dir");
            combineFlsDir(allRes, flsDir, ref count, ref size);

            EditorUtility.DisplayProgressBar("生成FLS文件", "合并文件列表", 0.9f);

            if (allRes.Count > 0)
            {
                //新的fls路径,就是去掉语言路径的默认fls路径
                string saveFlsPath = flsFileName.Replace(_lanStr + "/", "");
                StreamWriter sw = new StreamWriter(saveFlsPath);
                sw.WriteLine(string.Format("{0},{1}", count, size));
                var itor = allRes.GetEnumerator();
                while (itor.MoveNext())
                {
                    //还有manifest或者没有后缀,则跳过
                    if (itor.Current.IndexOf(".manifest") > 0 || itor.Current.IndexOf(".") == -1 || itor.Current.IndexOf(".meta") > 0)
                        continue;
                    sw.WriteLine(itor.Current);
                }

                sw.Close();
            }
            EditorUtility.DisplayProgressBar("生成FLS文件", "完成", 1.0f);
        }

        //读取fls.dir资源
        private static List<string> readFlsDir(string flsDir)
        {
            List<string> resList = new List<string>();
            if (!File.Exists(flsDir))
            {
                return resList;
            }

            string[] dirList = File.ReadAllLines(flsDir);
            for (int i = 0; i < dirList.Length; ++i)
            {
                string dirPath = SubAllRoot + dirList[i];
                var fileList = Utils.GetFiles(dirPath, "*", SearchOption.AllDirectories);
                foreach (string filePath in fileList)
                {
                    resList.Add(filePath.Replace(SubAllRoot, ""));
                }
            }

            return resList;
        }

        //合并fls.dir
        private static System.Collections.Generic.HashSet<string> combineFlsDir(System.Collections.Generic.HashSet<string> allRes,
            string flsDirFile, ref int count, ref long size)
        {
            var resList = readFlsDir(flsDirFile);

            for (int i = 0; i < resList.Count; ++i)
            {
                if (!allRes.Contains(resList[i]))
                {
                    string subResPath = SubAllRoot + resList[i];
                    //GameCfgData文件要区分语言
                    if (resList[i].IndexOf("GameCfgData") >= 0 && resList[i].IndexOf("GameCfgData_" + _lanStr) == -1)
                    {
                        continue;
                    }
                    if (File.Exists(subResPath))
                    {
                        count++;
                        size += new FileInfo(subResPath).Length;
                    }
                    allRes.Add(resList[i]);
                }
            }

            return allRes;
        }

        //合并fls.fls
        private static System.Collections.Generic.HashSet<string> combineFlsFile(System.Collections.Generic.HashSet<string> allRes, 
            string flsFile, ref int count, ref long size)
        {
            string[] defaultResArray = null;
            //默认存在的fls文件,用来和sceneFile里面场景对应资源进行合并
            if (File.Exists(flsFile))
            {
                defaultResArray = File.ReadAllLines(flsFile);
            }

            //合并默认内容
            if (defaultResArray != null && defaultResArray.Length > 0)
            {
                //合并size和count,其实这个不准
                string tagLine = defaultResArray[0];
                string[] sizeAndCountArray = tagLine.Split(',');
                count += int.Parse(sizeAndCountArray[0].Trim());
                size += long.Parse(sizeAndCountArray[1].Trim());

                //合并资源列表
                for (int i = 1; i < defaultResArray.Length; ++i)
                {
                    if (!allRes.Contains(defaultResArray[i]))
                    {
                        allRes.Add(defaultResArray[i]);
                    }
                }
            }

            return allRes;
        }

        //去重资源列表,计算count和size
        private static System.Collections.Generic.HashSet<string> optimizeList(List<string> sceneResList, out int count, out long size)
        {
            count = 0;
            size = 0;
            System.Collections.Generic.HashSet<string> allRes = new System.Collections.Generic.HashSet<string>();
            for (int i = 0; i < sceneResList.Count; ++i)
            {
                //去重
                if (!string.IsNullOrEmpty(sceneResList[i]) && !allRes.Contains(sceneResList[i]))
                {
                    string subResPath = SubAllRoot + sceneResList[i];
                    if (File.Exists(subResPath))
                    {
                        size += (new FileInfo(subResPath)).Length;
                        count++;
                    }
                    else
                    {
                        UnityEngine.Debug.LogError("自动分FLS: 文件不存在 " + sceneResList[i]);
                    }
                    allRes.Add(sceneResList[i]);
                }
            }

            return allRes;
        }


        private static List<string> addDependenceRes(string mapIdStr)
        {
            int id = 0; 
            if (int.TryParse(mapIdStr, out id))
            {
                return addDependenceRes(id);
            }

            return new List<string>();
        }

        private static List<string> addDependenceRes(int mapID)
        {
            DeclareMapsetting mapSetting = DeclareMapsetting.Get(mapID);
            if (mapSetting == null)
            {
                UnityEngine.Debug.LogError("地图id没找到: " + mapID);
                return new List<string>();
            }
            string sceneName = mapSetting.LevelName;
            string sceneMusic = mapSetting.Music;
            var mapInfoData = MapInfoDataReader.LoadSceneObjectData(getResourcePath("MapInfo"), mapSetting.MapInfo);
            UnityEngine.Debug.Log("collect scene:" + sceneName);

            var monsterResList = new List<string>();
            var npcResList = new List<string>();
            if (mapInfoData != null)
            {
                EditorUtility.DisplayProgressBar("生成FLS文件", "收集怪物资源", 0.5f);
                //怪物monster
                var monsterList = mapInfoData.mapMonsterStubs;
                List<int> monsterIDList = new List<int>();
                for (int i = 0; i < monsterList.Count; ++i)
                {
                    int monsterID = monsterList[i].m_id;
                    if (monsterIDList.Contains(monsterID))
                    {
                        continue;
                    }
                    monsterIDList.Add(monsterID);
                }

                monsterResList = collectMonsterRes(monsterIDList);
                UnityEngine.Debug.Log("monsterResList " + monsterResList.Count);
                //---

                EditorUtility.DisplayProgressBar("生成FLS文件", "收集NPC资源", 0.5f);
                //NPC
                var npcDataList = mapInfoData.mapNpcStubs;
                List<int> npcIDList = new List<int>();
                for (int i = 0; i < npcDataList.Count; ++i)
                {
                    int npcID = npcDataList[i].m_id;
                    if (npcIDList.Contains(npcID))
                    {
                        continue;
                    }
                    npcIDList.Add(npcID);
                }

                npcResList = collectNPCRes(npcIDList);
                UnityEngine.Debug.Log("npcResList " + npcResList.Count);
                //---
            }


            EditorUtility.DisplayProgressBar("生成FLS文件", "收集副本资源", 0.5f);
            //cloneMap
            var cloneMaps = collectCloneMapID(mapID);
            var cloneResList = collectCloneMonster(cloneMaps);
            UnityEngine.Debug.Log("cloneResList " + cloneResList.Count);
            //---

            EditorUtility.DisplayProgressBar("生成FLS文件", "收集关联动作资源", 0.5f);
            //怪物关联的动作资源
            List<string> animList = new List<string>();
            animList.AddRange(collectMonsterAnim(monsterResList));
            animList.AddRange(collectMonsterAnim(npcResList));
            animList.AddRange(collectMonsterAnim(cloneResList));
            //---

            List<string> allDependenceResList = new List<string>();
            allDependenceResList.Add(string.Format("{0}Scene/{1}.unity3d", _assetRoot, sceneName));
            string music = string.Format("{0}Sound/Music/{1}.mp3", _assetRoot, sceneMusic);
            if(File.Exists(music))
                allDependenceResList.Add(music);
            string miniMap = string.Format("{0}Texture/Map/tex_{1}.jpg", _assetRoot, sceneName);
            if (File.Exists(miniMap))
                allDependenceResList.Add(miniMap);

            allDependenceResList.AddRange(monsterResList);
            allDependenceResList.AddRange(npcResList);
            allDependenceResList.AddRange(cloneResList);
            allDependenceResList.AddRange(animList);

            return allDependenceResList;
        }

        //保存文件
        private static void save(params List<string>[] args)
        {
            int count = 0;
            System.Collections.Generic.HashSet<string> allRes = new System.Collections.Generic.HashSet<string>();
            for (int i = 0; i < args.Length; ++i)
            {
                for (int m = 0; m < args[i].Count; ++m)
                {
                    //去重
                    if (!allRes.Contains(args[i][m]))
                    {
                        allRes.Add(args[i][m]);
                        count++;
                    }
                }
            }

            string flsLanDir = SubFlsRoot + _lanStr;
            if (!Directory.Exists(flsLanDir))
            {
                Directory.CreateDirectory(flsLanDir);
            }
            StreamWriter sw = new StreamWriter(SubFlsRoot + _lanStr + "/test.txt");
            sw.WriteLine(string.Format("{0},0", count));

            var itor = allRes.GetEnumerator();
            while (itor.MoveNext())
            {
                sw.WriteLine(itor.Current);
            }
            
            sw.Close();
        }

        //怪物模型
        private static List<string> collectMonsterRes(List<int> monsterIDs)
        {
            List<string> monsterPaths= new List<string>();
            for (int i = 0; i < monsterIDs.Count; ++i)
            {
                string path = collectMonsterRes(monsterIDs[i]);
                if (!string.IsNullOrEmpty(path))
                {
                    monsterPaths.Add(path);
                }
            }

            return monsterPaths;
        }

        private static string collectMonsterRes(int monsterID)
        {
            var monsterCfg = DeclareMonster.Get(monsterID);
            if (monsterCfg == null)
            {
                return "";
            }
            var modelConfig = DeclareModelConfig.Get(monsterCfg.Res);
            if (modelConfig == null)
            {
                return "";
            }
            return combineMonsterPath(modelConfig.Model);
        }

        //npc模型和音效
        private static List<string> collectNPCRes(List<int> npcIDs)
        {
            List<string> npcPaths = new List<string>();
            List<string> speechPath = new List<string>();

            for (int i = 0; i < npcIDs.Count; ++i)
            {
                var npcCfg = DeclareNpc.Get(npcIDs[i]);
                if (npcCfg == null)
                {
                    continue;
                }
                var modelConfig = DeclareModelConfig.Get(npcCfg.Res);
                if (modelConfig != null)
                {
                    npcPaths.Add(combineNPCPath(modelConfig.Model));
                }

                string speechName = npcCfg.Speech;
                if (string.IsNullOrEmpty(speechName))
                {
                    continue;
                }

                speechPath.Add(combineNpcSpeechRes(speechName));
            }

            npcPaths.AddRange(speechPath);

            return npcPaths;
        }

        //通过副本数据获取副本中怪物信息CloneMonster
        private static List<string> collectCloneMonster(List<DeclareCloneMap> cloneMapData)
        {
            List<int> monsterIDList = new List<int>();
            List<string> monsterPathList = new List<string>();

            //for (int i = 0; i < cloneMapData.Count; ++i)
            //{
            //    int cloneMapId = cloneMapData[i].Id;
            //    var cloneMonsterDataItor = DeclareCloneMonster.CacheData.GetEnumerator();
            //    while (cloneMonsterDataItor.MoveNext())
            //    {
            //        var current = cloneMonsterDataItor.Current.Value;

            //        if (current.CloneID == cloneMapId)
            //        {
            //            //怪物信息monster_information,解析出id
            //            string[] monsterIDArray = current.MonsterInformation.Split(';');
            //            for (int m = 0; m < monsterIDArray.Length; ++m)
            //            {
            //                string monsterIDstr = monsterIDArray[m].Substring(0, monsterIDArray[m].IndexOf('_'));
            //                int monsterID = getInt(monsterIDstr);
            //                if (!monsterIDList.Contains(monsterID))
            //                {
            //                    monsterIDList.Add(monsterID);
            //                    string path = collectMonsterRes(monsterID);
            //                    if (!string.IsNullOrEmpty(path) && !monsterPathList.Contains(path))
            //                    {
            //                        monsterPathList.Add(path);
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}

            return monsterPathList;
        }

        //通过地图id获取副本数据
        private static List<DeclareCloneMap> collectCloneMapID(int mapID)
        {
            List<DeclareCloneMap> cloneMapDataList = new List<DeclareCloneMap>();
            DeclareCloneMap.Foreach((cfg) =>
            {
                if (mapID == cfg.Mapid)
                {
                    cloneMapDataList.Add(cfg);
                    return false;
                }
                return true;
            });
            return cloneMapDataList;
        }

        //通过怪物名字来获取对应的怪物动作文件
        private static List<string> collectMonsterAnim(string monsterPath)
        {
            List<string> animFileList = new List<string>();
            string monsterDirName = Path.GetFileNameWithoutExtension(monsterPath);
            string animRootPath = _subResRoot + "Animation/monster/" + monsterDirName;
            if (Directory.Exists(animRootPath))
            {
                animFileList = Utils.GetFiles(animRootPath, "*.*", SearchOption.AllDirectories, PkgConstDefine.CommonExceptionEx);
            }

            for (int i = 0; i < animFileList.Count; ++i)
            {
                animFileList[i] = Path.ChangeExtension(animFileList[i].Replace(SubAllRoot, ""), "unity3d");
            }

            return animFileList;
        }

        private static List<string> collectMonsterAnim(List<string> monsterList)
        {
            List<string> animList = new List<string>();
            for (int i = 0; i < monsterList.Count; ++i)
            {
                animList.AddRange(collectMonsterAnim(monsterList[i]));
            }

            return animList;
        }

        //组合怪物路径
        private static string combineMonsterPath(int id)
        {
            string monsterPrefabName = string.Format("m_{0:D3}.unity3d", id);
            string assetsPath = getResourcePath(string.Format("Prefab/Monster/{0}", monsterPrefabName));
            return assetsPath;
        }

        //NPC资源路径
        private static string combineNPCPath(int id)
        {
            return combineMonsterPath(id);
        }

        //NPC音效文件
        private static string combineNpcSpeechRes(string speechName)
        {
            string lan = _lanStr;
            if (_lanStr.IndexOf("/") > 0)
            {
                lan = _lanStr.Substring(0, _lanStr.IndexOf("/"));
            }
            //音效有语言路径
            return getResourcePath(string.Format("Sound/Speech/{1}/{0}.unity3d", speechName, lan));
        }

        private static string getResourcePath(string resDirName)
        {
            return _assetRoot + resDirName;
        }

        private static int getInt(string intStr)
        {
            int ret = 0;
            int.TryParse(intStr, out ret);
            return ret;
        }


        #region 生成分段资源

        public static void CreateBinaryRes(string binaryFileName, out List<string> binaryResList)
        {
#if UNITY_STANDALONE_WIN
            string resStoreDir = "../SubResource/EXE";
#else
            string resStoreDir = "../SubResource/APK";
#endif
            if (!Directory.Exists(resStoreDir))
                Directory.CreateDirectory(resStoreDir);
            binaryFileName = resStoreDir + "/" + binaryFileName;
            binaryResList = new List<string>();
            List<string> flsList = Utils.GetFiles(SubFlsRoot, "*.fls", SearchOption.TopDirectoryOnly, PkgConstDefine.CommonExceptionEx);
            int index = 1;
            for (int i = 0; i < flsList.Count; ++i)
            {
                if (flsList[i].IndexOf("fls0") > 0 || flsList[i].IndexOf("fls.fls") > 0)
                    continue;

                string binaryResPath = binaryFileName + "_" + (index);
                binaryResList.Add(binaryResPath);
                CreateBinaryResAndMapFile(flsList[i], binaryResPath);
                index++;
            }

            EditorUtility.ClearProgressBar();
        }

        public static bool CreateBinaryResAndMapFile(string flsFile, string outMapFile)
        {
            bool retValue = true;

            string outFileMap = outMapFile + ".map";
            string outFileRes = outMapFile;

            FileStream writerRes = new FileStream(outFileRes, FileMode.Create);
            FileStream writerMap = new FileStream(outFileMap, FileMode.Create);

            try
            {
                string readLine = "";
                StreamReader reader = File.OpenText(flsFile);

                long begin = 0;
                long end = 0;
                int dirLen = 0;
                int nameLen = 0;
                int md5Len = 0;
                long fileSize = 0;
                string dir = "";
                string name = "";
                string md5 = "";

                string originalPath = "";

                int count = 0;
                int maxCount = 0;
                bool hasMaxCount = false;
                while ((readLine = reader.ReadLine()) != null)
                {
                    //不拷贝视频文件
                    if (readLine.IndexOf(".map4") > 0)
                        continue;
                    if (readLine.Contains(","))
                    {
                        string countStr = readLine.Substring(0, readLine.IndexOf(",")).Trim();
                        hasMaxCount = Int32.TryParse(countStr, out maxCount);
                        continue;
                    }

                    if (maxCount != 0)
                        EditorUtility.DisplayProgressBar("生成分段资源", readLine, count / (float)maxCount);

                    originalPath = SubAllRoot + readLine;
                    //begin_end_dirLen_nameLen_md5Len_fileSize_dir_name_md5
                    FileInfo fileInfo = new FileInfo(originalPath);
                    if (!fileInfo.Exists)
                    {
                        //retValue = false;
                        UnityEngine.Debug.LogError("WARN::" + fileInfo.FullName + " ----> 不存在!!!");
                        continue;
                    }

                    if (retValue == false)
                    {
                        continue;
                    }

                    fileSize = fileInfo.Length;
                    begin = end;

                    //readLine = g_form.g_configModel.m_addDir + readLine;

                    dirLen = getDirOrNameLen(readLine, true);
                    nameLen = getDirOrNameLen(readLine, false);
                    md5Len = 32;
                    end += fileSize + dirLen + nameLen + md5Len + 32 * 4;
                    dir = getDirOrNameStr(readLine, true);
                    name = getDirOrNameStr(readLine, false);
                    md5 = Utils.MD5(fileInfo.FullName);

                    //write map file
                    writerMap.Write(getByte("" + begin, 10), 0, 10);
                    writerMap.Write(getByte("" + end, 10), 0, 10);
                    writerMap.Write(getByte("" + dirLen, 10), 0, 10);
                    writerMap.Write(getByte("" + nameLen, 10), 0, 10);
                    writerMap.Write(getByte("" + md5Len, 10), 0, 10);
                    writerMap.Write(getByte("" + fileSize, 10), 0, 10);
                    writerMap.Write(getByte(dir), 0, getByte(dir).Length);
                    writerMap.Write(getByte(name), 0, getByte(name).Length);
                    writerMap.Write(getByte(md5), 0, getByte(md5).Length);
                    //---

                    //write res file
                    writerRes.Write(getByte("" + dirLen, 32), 0, 32);
                    writerRes.Write(getByte("" + nameLen, 32), 0, 32);
                    writerRes.Write(getByte("" + md5Len, 32), 0, 32);
                    writerRes.Write(getByte("" + fileSize, 32), 0, 32);
                    writerRes.Write(getByte(dir), 0, getByte(dir).Length);
                    writerRes.Write(getByte(name), 0, getByte(name).Length);
                    writerRes.Write(getByte(md5), 0, getByte(md5).Length);

                    writeFile(writerRes, originalPath);
                    //---

                    count++;

                }

                reader.Close();
            }
            catch (System.Exception)
            {
                retValue = false;
            }
            finally
            {
                writerMap.Flush();
                writerMap.Close();

                writerRes.Flush();
                writerRes.Close();
            }
            return retValue;
        }

        private static int getDirOrNameLen(string abPath, bool forDir)
        {
            string newPath = abPath.Replace("\\", "/");
            int dirRange = newPath.LastIndexOf("/");
            string dir = newPath.Substring(0, dirRange + 1);
            string name = newPath.Substring(dirRange + 1, newPath.Length - dirRange - 1);
            if (forDir)
            {
                return dir.Length;
            }
            return name.Length;
        }

        private static string getDirOrNameStr(string abPath, bool forDir)
        {
            string newPath = abPath.Replace("\\", "/");
            int dirRange = newPath.LastIndexOf("/");
            string dir = newPath.Substring(0, dirRange + 1);
            string name = newPath.Substring(dirRange + 1, newPath.Length - dirRange - 1);
            if (forDir)
            {
                return dir;
            }
            return name;
        }

        private static Byte[] getByte(string value, int len)
        {
            Byte[] bytes = new Byte[len];
            Byte[] tempBts = Encoding.Default.GetBytes(value);

            for (int i = 0; i < tempBts.Length; ++i)
            {
                if (i > len)
                {
                    break;
                }
                bytes[i] = tempBts[i];
            }

            return bytes;

        }

        private static Byte[] getByte(string value)
        {
            return Encoding.Default.GetBytes(value);
        }

        private static void writeFile(FileStream writer, string file)
        {
            FileStream read = new FileStream(file, FileMode.Open);

            Byte[] buffer = new Byte[1024];
            int len = 0;
            while ((len = read.Read(buffer, 0, 1024)) > 0)
            {
                writer.Write(buffer, 0, len);
            }
            read.Close();
        }

#endregion
    }
}