using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OTSCommon
{
    public class MergedparticlesHelper
    {
        private SqLiteHelper dbHelper;
        public MergedparticlesHelper(string path)
        {
            dbHelper = new SqLiteHelper("data source = '"+path+"'");
        }
        /// 
        /// 获取ParticleList
        /// 
        /// Feature
        /// 
        public DataTable GetMergedParticles()
        {
            string sqlp = @"select *,
(select group_concat(name||'-'||Percentage,';')  
from ElementChemistry where XRayId	=MergedParticles.XRayId		and fieldid=MergedParticles.fieldid	) as Element
from 	MergedParticles ";
            DataTable DT = dbHelper.ExecuteQuery(sqlp);
            // List listp = dbHelper.TableToList(DT);
            return DT;
        }
        /// 
        /// 获取所有Particle
        /// 
        /// 
        public DataTable GetParticleAll(string fieldAndPartic)
        {
            string sqlp = @"select * from INcAData";
            if (fieldAndPartic != "")
            {
                sqlp = sqlp + " where '" + fieldAndPartic + "' like ('%,'||fieldid||'-'||particleid||',%')";
            }
            DataTable DT = dbHelper.ExecuteQuery(sqlp);
            return DT;
        }
        /// 
        /// 通过FileStream 来打开文件,这样就可以实现不锁定Image文件,到时可以让多用户同时访问Image文件
        /// 
        /// 
        /// 
        public Bitmap ReadImageFile(string path)
        {
            if (!File.Exists(path))
            {
                return null;//文件不存在
            }
            FileStream fs = File.OpenRead(path); //OpenRead
            int filelength = 0;
            filelength = (int)fs.Length; //获得文件长度 
            Byte[] image = new Byte[filelength]; //建立一个字节数组 
            fs.Read(image, 0, filelength); //按字节流读取 
            System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            Bitmap bit = new Bitmap(result);
            return bit;
        }
        public Bitmap GetBitmapForBig(string sub, double xs, string path)
        {
            string vs = "," + sub.Replace(':', '-') + ",";
            DataTable dataTable = GetParticleAll(vs);
            if (dataTable.Rows.Count == 0)
            {
                return null;
            }
            //内接矩形
            double max_Y = Convert.ToInt64(dataTable.Rows[0]["FieldPosY"]) * xs - Convert.ToInt64(dataTable.Rows[0]["RectTop"]);
            double max_X = Convert.ToInt64(dataTable.Rows[0]["FieldPosX"]) * xs + Convert.ToInt64(dataTable.Rows[0]["RectLeft"]);
            double min_Y = max_Y;
            double min_X = max_X;
            //拼接field矩形
            double MAX_Y = Convert.ToInt64(dataTable.Rows[0]["FieldPosY"]) * xs;
            double MAX_X = Convert.ToInt64(dataTable.Rows[0]["FieldPosX"]) * xs;
            double MIN_Y = MAX_Y;
            double MIN_X = MAX_X;
            foreach (DataRow item in dataTable.Rows)
            {
                //颗粒外接矩形
                double lefttopX = Convert.ToInt64(item["FieldPosX"]) * xs + Convert.ToInt64(item["RectLeft"]);
                if (lefttopX < min_X)
                {
                    min_X = lefttopX;
                }
                if (lefttopX + Convert.ToInt64(item["RectWidth"]) > max_X)
                {
                    max_X = lefttopX + Convert.ToInt64(item["RectWidth"]);
                }
                double lrfttopY = Convert.ToInt64(item["FieldPosY"]) * xs - Convert.ToInt64(item["RectTop"]);
                if (max_Y < lrfttopY)
                {
                    max_Y = lrfttopY;
                }
                if (min_Y > lrfttopY - Convert.ToInt64(item["RectHeight"]))
                {
                    min_Y = lrfttopY - Convert.ToInt64(item["RectHeight"]);
                }
                //画布
                double lefttopXH = Convert.ToInt64(item["FieldPosX"]) * xs;
                if (lefttopXH > MAX_X)
                {
                    MAX_X = lefttopXH;
                }
                if (lefttopXH < MIN_X)
                {
                    MIN_X = lefttopXH;
                }
                double lrfttopYH = Convert.ToInt64(item["FieldPosY"]) * xs;
                if (MAX_Y < lrfttopYH)
                {
                    MAX_Y = lrfttopYH;
                }
                if (MIN_Y > lrfttopYH)
                {
                    MIN_Y = lrfttopYH;
                }
            }
            int WIDTH = Convert.ToInt32(MAX_X - MIN_X) + 1024;
            int HEIGHT = Convert.ToInt32(MAX_Y - MIN_Y) + 768;
            //构造最终的图片白板
            Bitmap tableChartImage = new Bitmap(WIDTH, HEIGHT);
            Graphics graph = Graphics.FromImage(tableChartImage);
            //初始化这个大图
            graph.DrawImage(tableChartImage, 0, 0);
            int width = Convert.ToInt32(max_X - min_X);
            int height = Convert.ToInt32(max_Y - min_Y);
            int X = Convert.ToInt32(min_X - MIN_X);
            int Y = Convert.ToInt32(MAX_Y - max_Y);
            Rectangle rectangle = new Rectangle() { X = X, Y = Y, Width = width, Height = height };
            foreach (DataRow item in dataTable.Rows)
            {
                string filePath = path + "\\FIELD_FILES\\";
                string imagePath = filePath + "Field" + item["fieldid"].ToString() + ".bmp";
                //然后将取出的数据,转换成Bitmap对象
                Bitmap ls_bt = ReadImageFile(imagePath);
                int x = Convert.ToInt32(Convert.ToDouble(item["FieldPosX"]) * xs - MIN_X);
                int y = Convert.ToInt32(Convert.ToDouble(item["FieldPosY"]) * xs - MIN_Y);
                try
                {
                    graph.DrawImage(ls_bt, x, y);
                }
                catch /*(Exception e)*/
                {
                    throw;
                }
            }
            Bitmap bmap = tableChartImage.Clone(rectangle, PixelFormat.Format8bppIndexed);
          //  bmap.Save(path + "asd.bmp");
            return bmap;
        }
    }
}