using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Txgy.EWS.Client.Common;

namespace Txgy.EWS.Client.PageModule.Services
{
    public class DownloadJsonFile
    {
        public int Download(string eventTime, string savePath, string saveName, string tableName)
        {
            string connStr = BusinessConfigManager.GetConnectionString("TencetnMySQL");
            MySqlConnection RemoteConn = new MySqlConnection(connStr);
            string courseSql = @"select JsonFile from " + tableName + " where EventTime=@eventTime";
            MySqlCommand Comm = new MySqlCommand(courseSql, RemoteConn);
            MySqlDataReader DataReader = null;
            try
            {
                if (RemoteConn.State != ConnectionState.Open)
                {
                    RemoteConn.Open();
                }

                Comm.Parameters.AddWithValue("@eventTime", eventTime);
                DataReader = Comm.ExecuteReader();
                List<byte> wds = new List<byte>();
                //开始读数据
                while (DataReader.Read())
                {
                    byte[] blob;
                    blob = (byte[])DataReader["JsonFile"];
                    if (blob.Length == 0)
                        break;
                    wds.AddRange(blob);
                }
                string jsonPath = savePath + saveName;
                if (!Directory.Exists(savePath))
                {
                    Directory.CreateDirectory(savePath);
                }
                int len = -1;
                using (FileStream fs = new FileStream(jsonPath, FileMode.OpenOrCreate))
                {
                    using (BinaryWriter binWriter = new BinaryWriter(fs))
                    {
                        binWriter.Write(wds.ToArray());
                        len = (int)new FileInfo(jsonPath).Length;
                    }
                }
                if (len == wds.Count)
                {
                    return wds.Count;
                }
                return -1;

            }
            catch(Exception ex) 
            {
                throw ex;
            }
            finally
            {
                if (DataReader != null)
                {
                    DataReader.Dispose();
                    DataReader = null;
                }
                if (Comm != null)
                {
                    Comm.Dispose();
                    Comm = null;
                }
                if (RemoteConn != null)
                {
                    RemoteConn.Close();
                    RemoteConn.Dispose();
                    RemoteConn = null;
                }
            }
        }

        public static async Task<int> DownloadAsync(string eventTime, string savePath, string saveName, string tableName)
        {
            string connStr = BusinessConfigManager.GetConnectionString("TencetnMySQL");
            using (MySqlConnection RemoteConn = new MySqlConnection(connStr))
            using (MySqlCommand Comm = new MySqlCommand($"SELECT JsonFile FROM {tableName} WHERE EventTime=@eventTime", RemoteConn))
            {
                try
                {
                    await RemoteConn.OpenAsync();

                    Comm.Parameters.AddWithValue("@eventTime", eventTime);

                    using (var DataReader = await Comm.ExecuteReaderAsync())
                    {
                        List<byte> wds = new List<byte>();
                        while (await DataReader.ReadAsync())
                        {
                            byte[] blob = (byte[])DataReader["JsonFile"];
                            if (blob.Length == 0)
                                break;
                            wds.AddRange(blob);
                        }

                        string jsonPath = Path.Combine(savePath, saveName);
                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }

                        int len = -1;
                        using (FileStream fs = new FileStream(jsonPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 4096, true))
                        {
                            await fs.WriteAsync(wds.ToArray(), 0, wds.Count);
                            len = (int)fs.Length;
                        }

                        return len == wds.Count ? wds.Count : -1;
                    }
                }
                catch (Exception)
                {
                    // 异常处理逻辑，比如记录日志等
                    throw;
                }
            }
        }

    }
}
