using YG;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Net.NetworkInformation;

namespace System.Text
{

    public class Notify : System.ComponentModel.INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyProper(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged.Invoke(this, new PropertyChangedEventArgs(name));
            }
        }
    }
    public static class CommonAtrr
    {

        public static void ShowDialog(this System.Windows.Forms.Form fm, string msg, bool isthread = true)
        {
            if (isthread)
            {
                Task.Factory.StartNew(() =>
                {
                    System.Windows.Forms.MessageBox.Show(msg, "信息提示", Windows.Forms.MessageBoxButtons.OK, Windows.Forms.MessageBoxIcon.Asterisk);
                });
            }
            else
            {
                System.Windows.Forms.MessageBox.Show(msg, "信息提示", Windows.Forms.MessageBoxButtons.OK, Windows.Forms.MessageBoxIcon.Asterisk);
            }

        }
        /// <summary>
        /// 判断text里边是否为空，如果为空那么弹出提示信息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="showmsg"></param>
        public static bool Text_Check_value_Empty(this System.Windows.Forms.TextBox text, string showmsg)
        {
            if (string.IsNullOrEmpty(text.Text))
            {
                Task.Factory.StartNew(() => { System.Windows.Forms.MessageBox.Show(showmsg, "信息提示", Windows.Forms.MessageBoxButtons.OK, Windows.Forms.MessageBoxIcon.Asterisk); });
                return false;
            }
            return true;
        }
        public static byte[] ReturnBtyesWtitString(this string value, int byteleng = 30)
        {
            byte[] bt = new byte[byteleng];
            byte[] item = Encoding.ASCII.GetBytes(value.ToClone());
            Array.Copy(item, bt, item.Length);
            return bt;
        }
        public static bool Ping(this string ip)
        {
            Ping ping = new Ping();
            PingReply pingReply = ping.Send(ip.ToClone());
            if (pingReply.Status.Equals(IPStatus.Success))
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 判断当前路径是否存在， 如果不存在就创建，
        /// </summary>
        /// <param name="path"></param>
        /// <returns>如果为false则表示当前路径不存在，true则表示当前路径存在</returns>
        public static bool PathIsExist(this string path)
        {
            try
            {
                if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(path.ToClone())))
                {
                    System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path));
                }
                if (!File.Exists(path))
                {
                    File.Create(path).Close();
                    return false;
                }

            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd($"87-->{ex.Message}");
                return false;
            }
            return true;

        }
        /// <summary>
        /// 判断text里边是否为空，并且文本的长度是否小于当前参数，如果小于那么弹出提示信息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="textleng"></param>
        /// <param name="showmsg"></param>
        public static bool Text_Check_valueLeng_Empty(this System.Windows.Forms.TextBox text, int textleng, string showmsg)
        {
            if (string.IsNullOrEmpty(text.Text) && text.Text.Length < textleng)
            {
                Task.Factory.StartNew(() => { System.Windows.Forms.MessageBox.Show(showmsg); });
                return false;
            }
            return true;
        }
        /// <summary>
        /// 把字符转换为int
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int StringToInt(this string value)
        {
            try { return Convert.ToInt32(value.ToClone()); }
            catch
            {
                Log.Instance.WriteLogAdd(value + "在进行类型转换StringToInt时出现异常", null);
                return 0;
            }
        }
        /// <summary>
        /// 把字符转换为int
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool StringToBool(this string value)
        {
            try { return Convert.ToBoolean(value.StringToInt()); }
            catch
            {
                Log.Instance.WriteLogAdd(value + "在进行类型转换StringToBool时出现异常", null);
                return false;
            }
        }
        /// <summary>
        /// 拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="List">The list.</param>
        /// <returns>List{``0}.</returns>
        public static System.ComponentModel.BindingList<T> Clone<T>(this System.ComponentModel.BindingList<T> List)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, List);
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as System.ComponentModel.BindingList<T>;
            }
        }
        public static List<T> Clone<T>(this List<T> List)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, List);
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as List<T>;
            }
        }
        public static float StringToFloat(this string value)
        {
            try { return Convert.ToSingle(value.ToClone()); }
            catch
            {
                Log.Instance.WriteLogAdd(value + "在进行类型转换StringToFloat时出现异常", null);
                return 0;
            }
        }
        /// <summary>
        /// 把字符转换为double类型 
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static double StringToDouble(this string value)
        {
            try { return Convert.ToDouble(value.ToClone()); }
            catch
            {
                Log.Instance.WriteLogAdd(value + "在进行类型转换StringToDouble时出现异常");
                return 0;
            }
        }
        /// <summary>
        /// 把噢bject类型转换为int类型
        /// </summary>
        /// <param name="ob"></param>
        /// <returns></returns>
        public static int ObjectToInt(this object ob)
        {
            return ob.ToString().StringToInt();
        }
        public static short ObjectToShort(this object ob)
        {
            return short.Parse(ob.ToString());

        }
        public static byte ObjectToByte(this object ob)
        {
            return byte.Parse(ob.ToString());

        }
        /// <summary>
        /// 把噢bject类型转换为double类型
        /// </summary>
        /// <param name="ob"></param>
        /// <returns></returns>
        public static double ObjectToDouble(this object ob)
        {
            return ob.ToString().StringToDouble();
        }
        public static string ObjectToString(this object ob)
        {
            try { if (ob != null) return ob.ToString(); else Log.Instance.WriteLogAdd("转换object为string类型时出现哦bject为空的情况默认返回空字符串"); return ""; }
            catch(Exception ex) { YG.Log.Instance.WriteLogAdd($"216-->{ex.Message}"); return ""; }
        }
        public static void DataGridViewColor(this System.Windows.Forms.DataGridView dv)
        {
            dv.RowsDefaultCellStyle.BackColor = Drawing.Color.AliceBlue;
            dv.AlternatingRowsDefaultCellStyle.BackColor = Drawing.Color.Aquamarine;
        }
        /// <summary>
        /// 判断当前的FirstOrDefaul是否为空，如果为空，那么不执行参数函数
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <param name="source"></param>
        /// <param name="action"></param>
        public static bool FirstOrDefaultYG<TSource>(this TSource source, Action<TSource> action)
        {
            if (source != null)
            {
                try
                {
                    action(source);
                    return true;
                }
                catch
                {
                    Log.Instance.WriteLogAdd("执行FirstOrDefaultYG函数时出现异常情况");
                    return false;
                }
            }
            return false;
        }
        public static bool Foreach<TSource>(this IEnumerable<TSource> source, Action<TSource> action)
        {
            if (source != null)
            {
                try
                {
                    foreach (var c in source)
                    {
                        action(c);
                    }
                    return true;
                }
                catch
                {
                    Log.Instance.WriteLogAdd("执行Foreach函数时出现异常情况");
                    return false;
                }
            }
            return false;
        }

        /// <summary>
        /// 把对象转换为字符串
        /// </summary>
        /// <param name="ob"></param>
        /// <returns></returns>
        public static string Json_SerializeObject(this object ob)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(ob);
        }
        /// <summary>
        /// 把字符串转换为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T Json_DeserializeObject<T>(this string value)
        {
            try
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(value);
            }
            catch
            {
                Log.Instance.WriteLogAdd(string.Format("转换类型时出现异常{0}-->{1}", typeof(T), value));
                return default(T);
            }
        }

        /// <summary>
        /// 如果字符串为空， 那么返回true
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static bool StringIsEmpty(this string msg)
        {
            if (string.IsNullOrEmpty(msg))
            {
                return true;
            }
            return false;

        }


        /// <summary>
        /// 通用summary
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="sw"></param>
        /// <param name="ishead"></param>
        /// <returns></returns>
        private static bool ObjectWriteCVS<T>(this T t, StreamWriter sw, bool ishead)
        {
            try
            {
                System.Reflection.PropertyInfo[] minfo = t.GetType().GetProperties();
                if (minfo.Length > 0)
                {
                    foreach (System.Reflection.PropertyInfo mi in minfo)
                    {

                        if (mi.PropertyType.IsGenericType)
                        {
                            object ob = mi.GetValue(t, null);

                            int count = (int)ob.GetType().GetProperty("Count").GetValue(ob);//.GetValue(t);
                            for (int i = 0; i < count; i++)
                            {
                                object item = ob.GetType().GetProperty("Item").GetValue(ob, new object[] { i });
                                if (item.GetType().GetProperties().Where(m => m.Name.Equals("Item_type") && m.GetValue(item).Equals("Elect")).Count() > 0)
                                {
                                    break;
                                }
                                item.ObjectWriteCVS(sw, ishead);

                            }
                        }
                        else
                        {
                            //if (mi.Name.Equals("Item_type") && mi.GetValue(t).Equals("Elect"))
                            //{
                            //    break;
                            //}
                            object[] atrti = mi.GetCustomAttributes(false);
                            if (atrti != null && atrti.Count() > 0)
                            {
                                YGAttribute YGa = mi.GetCustomAttributes(false)[0] as YGAttribute;
                                if (YGa != null && YGa.IsWrite)
                                {
                                    if (ishead)
                                    {
                                        sw.Write(mi.Name);
                                        sw.Write("\t");
                                    }
                                    else
                                    {
                                        sw.Write(mi.GetValue(t).ToString().Replace("\r", " ").Replace("\n", " ").Replace("\t", " "));
                                        sw.Write("\t");
                                    }
                                    //   sw.Write("\t");
                                }
                            }
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd($"377-->{ex.Message}");
                return false;
            }

        }


        /// <summary>
        /// 把对象写入到cvs表格里便
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="path"></param>
        public static bool ObjectWriteCVS<T>(this T t, string path)
        {
            try
            {
                System.IO.FileStream fs = new FileStream(path, System.IO.FileMode.Append, System.IO.FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs, new System.Text.UnicodeEncoding());
                System.Reflection.PropertyInfo[] minfo = t.GetType().GetProperties();

                if (minfo.Length > 0)
                {
                    foreach (System.Reflection.PropertyInfo mi in minfo)
                    {
                        if (mi.PropertyType.IsGenericType)
                        {
                            object ob = mi.GetValue(t, null);

                            int count = (int)ob.GetType().GetProperty("Count").GetValue(ob);//.GetValue(t);
                            for (int i = 0; i < count; i++)
                            {
                                object item = ob.GetType().GetProperty("Item").GetValue(ob, new object[] { i });
                                foreach (var pro in item.GetType().GetProperties())
                                {

                                    object[] atrti = pro.GetCustomAttributes(false);
                                    if (atrti != null && atrti.Count() > 0)
                                    {
                                        YGAttribute YGa = pro.GetCustomAttributes(false)[0] as YGAttribute;
                                        if (YGa != null && YGa.IsWrite)
                                        {
                                            sw.Write(pro.GetValue(item));
                                            sw.Write("\t");
                                        }
                                    }

                                }
                            }

                        }

                    }
                }
                sw.WriteLine("");
                sw.Flush();
                sw.Close();
                return true;
            }
            catch (Exception ex)
            {
                YG.Log.Instance.WriteLogAdd(ex.Message);
                return false;
            }
        }

    }
    /// <summary>
    /// 是否写入CVS
    /// </summary>
    public class YGAttribute : Attribute
    {
        /// <summary>
        /// 是否写入CVS
        /// </summary>
        public bool IsWrite { get; set; } = true;
    }
}
