using GFGEditor;
using GFGGame;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using UnityEngine;
using Color = System.Drawing.Color;
using Graphics = System.Drawing.Graphics;
public class ImagesClip : MonoBehaviour
{
    public static void CutImageWhitePart(string FilePath, string TargetPath, string fileName, int WhiteBarRate = 2)
    {
        Debug.Log("fileName:" + fileName);
        Bitmap bmp = new Bitmap(FilePath);
        int top = 0, left = 0;
        int right = bmp.Width, bottom = bmp.Height;
        int width = bmp.Width, height = bmp.Height;
        int xLeft = 0, yTop = 0;
        //寻找最上面的标线,从左(0)到右,从上(0)到下
        for (int i = 0; i < bmp.Height; i++)//行
        {
            bool find = false;
            for (int j = 0; j < bmp.Width; j++)//列
            {
                Color c = bmp.GetPixel(j, i);
                if (IsBlank(c))
                {
                    top = i;
                    find = true;
                    yTop = i;
                    break;
                }
            }
            if (find) break;
        }
        //寻找最左边的标线,从上(top位)到下,从左到右
        for (int i = 0; i < bmp.Width; i++)//列
        {
            bool find = false;
            for (int j = top; j < bmp.Height; j++)//行
            {
                Color c = bmp.GetPixel(i, j);
                if (IsBlank(c))
                {
                    left = i;
                    find = true;
                    xLeft = i;
                    break;
                }
            }
            if (find) break; ;
        }
        //寻找最下边标线,从下到上,从左到右
        for (int i = bmp.Height - 1; i >= 0; i--)//行
        {
            bool find = false;
            for (int j = left; j < bmp.Width; j++)//列
            {
                Color c = bmp.GetPixel(j, i);
                if (IsBlank(c))
                {
                    bottom = i;
                    find = true;
                    break;
                }
            }
            if (find) break;
        }
        //寻找最右边的标线,从上到下,从右往左
        for (int i = bmp.Width - 1; i >= 0; i--)//列
        {
            bool find = false;
            for (int j = 0; j < bottom; j++)//行
            {
                Color c = bmp.GetPixel(i, j);
                if (IsBlank(c))
                {
                    right = i;
                    find = true;
                    break;
                }
            }
            if (find) break;
        }
        bmp = Cut(bmp, left, top, right - left, bottom - top);
        if (bmp != null)
        {
            bmp.Save(TargetPath + fileName);
            WriteImagePos(TargetPath, fileName, xLeft + (bmp.Width / 2) - (width / 2), yTop + (bmp.Height / 2) - (height / 2));
            bmp.Dispose();
            Debug.Log("换装部件裁剪完成");
        }
    }
    public static Bitmap Cut(Bitmap b, int StartX, int StartY, int iWidth, int iHeight)
    {
        if (b == null)
        {
            return null;
        }
        int w = b.Width;
        int h = b.Height;
        if (StartX >= w || StartY >= h)
        {
            return null;
        }
        if (StartX + iWidth > w)
        {
            iWidth = w - StartX;
        }
        if (StartY + iHeight > h)
        {
            iHeight = h - StartY;
        }
        try
        {
            Bitmap bmpOut = new Bitmap(iWidth, iHeight, PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(bmpOut);
            g.DrawImage(b, new Rectangle(0, 0, iWidth, iHeight), new Rectangle(StartX, StartY, iWidth, iHeight), GraphicsUnit.Pixel);
            g.Dispose();
            return bmpOut;
        }
        catch
        {
            return null;
        }
    }
    /// 
    /// 判断空白与否
    /// 
    /// 
    /// 
    public static bool IsBlank(Color c)
    {
        // Debug.Log("r:" + c.R + "  G:" + c.G + "  b:" + c.B + "  a:" + c.A);
        if ((c.R <= 255 || c.G <= 255 || c.B <= 255) && c.A > 0)
            return true;
        else return false;
    }
    public static List ReadImagePosition()
    {
        string targetPath = ImportArtResTool.DressUpTargetPath; ;
        string sourcePath = ImportArtResTool.DressUpTargetPath;
        string[] includeExtensionNames = new string[] { ".png", ".jpg" };
        List result = new List();
        if (Directory.Exists(sourcePath))
        {
            var files = Directory.GetFiles(sourcePath);
            foreach (var file in files)
            {
                if (file.Trim() == file)
                {
                    string extensionName = Path.GetExtension(file);//获取扩展名
                    if (includeExtensionNames == null || Array.IndexOf(includeExtensionNames, extensionName) >= 0)
                    {
                        string fileName = Path.GetFileName(file);//返回指定路径字符串的文件名和扩展名。
                        int xImage = 0;
                        int yImage = 0;
                        ReadImagePos(targetPath, fileName, out xImage, out yImage);
                    }
                }
                else
                {
                    Debug.LogError($"请检查文件名 {file}");
                }
            }
        }
        return result;
    }
    private static void WriteImagePos(string targetPath, string imageName, int iamgeX, int imageY)
    {
        string savePath = Path.Combine(targetPath, imageName.Split('.')[0] + ".bytes");
        using (var writer = new BinaryWriter(File.Open(savePath, FileMode.Create)))
        {
            writer.Write(iamgeX);
            writer.Write(imageY);
            writer.Close();
        }
    }
    private static void ReadImagePos(string targetPath, string imageName, out int imageX, out int imageY)
    {
        string savePath = Path.Combine(targetPath, imageName.Split('.')[0] + ".bytes");
        try
        {
            byte[] data = File.ReadAllBytes(savePath);
            var reader = new BinaryReader(new MemoryStream(data));
            imageX = reader.ReadInt32();
            imageY = reader.ReadInt32();
            reader.Close();
            Debug.Log(imageName + "  iamgeX:" + imageX + "   iamgeY:" + imageY);
        }
        catch
        {
            imageX = 0;
            imageY = 0;
            Debug.Log(imageName + "未写入位置数据");
        }
    }
    public static void WriteSourceImagesMD5(Dictionary resMd5, string saveName)
    {
        string savePath = Path.Combine(ImportArtResTool.Md5FilePath, saveName);
        using (var writer = new BinaryWriter(File.Open(savePath, FileMode.Create)))
        {
            ICollection keys = resMd5.Keys;
            foreach (string key in keys)
            {
                writer.Write(key);
                writer.Write(resMd5[key]);
            }
            writer.Close();
        }
    }
    public static Dictionary ReadSourceImagesMD5(string saveName)
    {
        string savePath = Path.Combine(ImportArtResTool.Md5FilePath, saveName);
        Dictionary resMd5 = new Dictionary();
        try
        {
            byte[] data = File.ReadAllBytes(savePath);
            var reader = new BinaryReader(new MemoryStream(data));
            bool isReadEnd = false;
            while (!isReadEnd)
            {
                try
                {
                    string key = reader.ReadString();
                    string value = reader.ReadString();
                    resMd5.Add(key, value);
                }
                catch
                {
                    isReadEnd = true;
                }
            }
            reader.Close();
        }
        catch
        {
            Debug.Log(savePath + "不存在");
        }
        return resMd5;
    }
}