using System;
using System.Configuration;
using System.IO;

namespace RGD.Common

{
    /// <summary>
    /// 所有进制之间的转换函数库
    /// Creator：RGD
    /// </summary>
    public static class CCarryConvert
    {
        /// <summary>
        /// 十进制转二进制
        /// </summary>
        /// <param name="dec">十进制数</param>
        /// <returns>二进制字符串</returns>
        //public static string DecimalToBin(decimal dec)
        //{
        //     return Convert.ToString(dec, 2);
        //}
        /// <summary>
        /// 十进制转十六进制
        /// </summary>
        /// <param name="dec">十进制数</param>
        /// <returns>十六进制字符串</returns>
        public static string DecimalToHex(byte dec)
        {
            return Convert.ToString(dec, 16);
        }

        /// <summary>
        /// 十进制转十六进制
        /// </summary>
        /// <param name="dec"></param>
        /// <returns></returns>
        public static string DecimalToHex(int dec)
        {
            return Convert.ToString(dec, 16);
        }

        /// <summary>
        /// 十进制转八进制
        /// </summary>
        /// <param name="dec">十进制数</param>
        /// <returns>八进制字符串</returns>
        public static string DecimalToOct(byte dec)
        {
            return Convert.ToString(dec, 8);
        }

        /// <summary>
        /// 二进制转十进制
        /// </summary>
        /// <param name="bin">二进制字符串</param>
        /// <returns>十进制数</returns>
        public static Int32 BinToDecimal(string bin)
        {
            return Convert.ToInt32(bin, 2);
        }

        /// <summary>
        /// 八进制转十进制
        /// </summary>
        /// <param name="bin">八进制字符串</param>
        /// <returns>十进制数</returns>
        public static Int32 OctToDecimal(string Oct)
        {
            return Convert.ToInt32(Oct, 8);
        }

        /// <summary>
        /// 十六进制转十进制
        /// </summary>
        /// <param name="bin">十六进制字符串</param>
        /// <returns>十进制数</returns>
        public static Int32 HexToDecimal(string hex)
        {
            return Convert.ToInt32(hex, 16);
        }

        /// <summary>
        /// 十六进制转字节型十进制
        /// </summary>
        /// <param name="bin">十六进制字符串</param>
        /// <returns>字节型十进制数</returns>
        public static byte HexToByte(string hex)
        {
            return Convert.ToByte(hex, 16);
        }

        /// <summary>
        /// 在十进制数获得指定bit位的二进制字符：0/1
        /// </summary>
        /// <param name="Int">十进制数</param>
        /// <param name="bitno">比特位</param>
        /// <returns></returns>
        public static byte GetBitFromInteger(int Int, int bitno)
        {
            if ((Int & Convert.ToInt32(Math.Pow(2, Convert.ToDouble(bitno)))) == Convert.ToInt32(Math.Pow(2, Convert.ToDouble(bitno))))
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// byte[0]存放高八位,byte[1]存放低八位
        /// </summary>
        /// <param name="_int16"></param>
        /// <returns></returns>
        public static byte[] GetByteFromInt16(int _int16)
        {
            char[] cc = new char[1] { '.' };
            string[] sp;
            byte[] _bytes = new byte[2];
            sp = Convert.ToString(_int16 >> 8).Split(cc);
            _bytes[0] = Convert.ToByte(sp[0]);
            _bytes[1] = Convert.ToByte(_int16 & 255);
            return _bytes;
        }

        public static UInt16 GetInt16FromBytes(byte[] _bytes)
        {
            UInt16 _int16;
            _int16 = Convert.ToUInt16(_bytes[1] + (_bytes[0] * 256));
            return _int16;
        }

        /// <summary>
        /// 读取某一天的通讯日志，就是所谓的黑匣子
        /// </summary>
        /// <param name="mydate">指定的日期</param>
        /// <returns>这一天的所有通讯记录</returns>
        public static string ReadCommLog(string mydate)
        {
            string filePath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString());
            filePath = System.IO.Path.GetDirectoryName(filePath);
            filePath = System.IO.Path.Combine(filePath, mydate + ".log");
            StreamReader sr = new StreamReader(filePath);
            if (sr.EndOfStream == false)
            {
                return sr.ReadToEnd();
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        /// 写黑匣子
        /// </summary>
        /// <param name="mydate"></param>
        /// <param name="textline"></param>
        /// <returns></returns>
        public static bool WriteCommLog(string mydate, string textline)
        {
            try
            {
                mydate = Convert.ToDateTime(mydate).ToString("yyyy-MM-dd");
                string filePath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString());
                filePath = System.IO.Path.GetDirectoryName(filePath);
                filePath = System.IO.Path.Combine(filePath, "DarkCasket");
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }
                //1--99循环
                string strf = string.Empty;
                string filepath1 = string.Empty;
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    if (fcount.ToString().Length < 2)
                    {
                        strf = "0" + fcount.ToString();
                    }
                    else
                    {
                        strf = fcount.ToString();
                    }

                    filepath1 = System.IO.Path.Combine(filePath, mydate + strf + ".log");
                    if (File.Exists(filepath1) == false)
                    {
                        using (StreamWriter sw = File.CreateText(filepath1))
                        {
                            sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                            sw.WriteLine(textline);
                            //20091102
                            sw.Close();
                            sw.Dispose();
                        }//

                        return true;//20081217
                    }
                    else
                    {
                        FileInfo ff = new FileInfo(filepath1);
                        AppSettingsReader asr = new AppSettingsReader();
                        long len = (long)asr.GetValue("DarkCasketSize", typeof(long));
                        if (ff.Length > len)
                        {
                            continue;
                        }
                        else
                        {
                            using (StreamWriter sw = File.AppendText(filepath1))
                            {
                                sw.WriteLine(textline);
                                //20091102
                                sw.Close();
                                sw.Dispose();
                            }

                            return true;//20081217
                        }
                    }
                }
                //20081217
                //99个文件都写满了，删除今天的99个文件重新开始
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    if (fcount.ToString().Length < 2)
                    {
                        strf = "0" + fcount.ToString();
                    }
                    else
                    {
                        strf = fcount.ToString();
                    }

                    filepath1 = System.IO.Path.Combine(filePath, mydate + strf + ".log");
                    if (File.Exists(filepath1) == true)
                    {
                        File.Delete(filepath1);
                    }
                }
                filepath1 = System.IO.Path.Combine(filePath, mydate + "01.log");

                {
                    using (StreamWriter sw = File.CreateText(filepath1))
                    {
                        sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                        sw.WriteLine(textline);
                        //20091102
                        sw.Close();
                        sw.Dispose();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
                //throw ex;
            }
        }

        public static bool WriteCommLog(string DarkCasketFolder, string mydate, string textline)
        {
            try
            {
                mydate = Convert.ToDateTime(mydate).ToString("yyyy-MM-dd");
                string filePath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString());
                filePath = System.IO.Path.GetDirectoryName(filePath);
                filePath = System.IO.Path.Combine(filePath, DarkCasketFolder + "DarkCasket");
                if (Directory.Exists(filePath) == false)
                {
                    Directory.CreateDirectory(filePath);
                }
                //1--99循环
                string strf = string.Empty;
                string filepath1 = string.Empty;
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    if (fcount.ToString().Length < 2)
                    {
                        strf = "0" + fcount.ToString();
                    }
                    else
                    {
                        strf = fcount.ToString();
                    }

                    filepath1 = System.IO.Path.Combine(filePath, mydate + strf + ".log");
                    if (File.Exists(filepath1) == false)
                    {
                        using (StreamWriter sw = File.CreateText(filepath1))
                        {
                            sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                            sw.WriteLine(textline);
                            //20091102
                            sw.Close();
                            sw.Dispose();
                        }//

                        return true;//20081217
                    }
                    else
                    {
                        FileInfo ff = new FileInfo(filepath1);
                        AppSettingsReader asr = new AppSettingsReader();
                        long len = (long)asr.GetValue("DarkCasketSize", typeof(long));
                        if (ff.Length > len)
                        {
                            continue;
                        }
                        else
                        {
                            using (StreamWriter sw = File.AppendText(filepath1))
                            {
                                sw.WriteLine(textline);
                                //20091102
                                sw.Close();
                                sw.Dispose();
                            }

                            return true;//20081217
                        }
                    }
                }
                //20081217
                //99个文件都写满了，删除今天的99个文件重新开始
                for (int fcount = 1; fcount <= 99; fcount++)
                {
                    if (fcount.ToString().Length < 2)
                    {
                        strf = "0" + fcount.ToString();
                    }
                    else
                    {
                        strf = fcount.ToString();
                    }

                    filepath1 = System.IO.Path.Combine(filePath, mydate + strf + ".log");
                    if (File.Exists(filepath1) == true)
                    {
                        File.Delete(filepath1);
                    }
                }
                filepath1 = System.IO.Path.Combine(filePath, mydate + "01.log");

                {
                    using (StreamWriter sw = File.CreateText(filepath1))
                    {
                        sw.WriteLine("通讯时间**********接口类型**********命令**********地址/端口**********报文内容");
                        sw.WriteLine(textline);
                        //20091102
                        sw.Close();
                        sw.Dispose();
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
                //throw ex;
            }
        }

        /// <summary>
        /// 写黑匣子
        /// </summary>
        /// <param name="interfacename"></param>
        /// <param name="ordername"></param>
        /// <param name="addr_port"></param>
        /// <param name="message"></param>
        public static void WriteDarkCasket(string interfacename, string ordername, string addr_port, byte[] message)
        {
            string data = "", wtxt;
            if (message == null)
            {
                data = "";
            }
            else
            {
                for (int i = 0; i < message.GetLength(0); i++)
                {
                    data = data + "-" + message[i].ToString();
                }
            }
            wtxt = DateTime.Now.ToLongTimeString() + "**" + interfacename + "**" + ordername + "**" + addr_port + "**" + data;
            Common.CCarryConvert.WriteCommLog(DateTime.Today.ToShortDateString(), wtxt);
        }

        public static void WriteDarkCasket(string DarkCasketFolder, string interfacename, string ordername, string addr_port, byte[] message)
        {
            string data = "", wtxt;
            if (message == null)
            {
                data = "";
            }
            else
            {
                for (int i = 0; i < message.GetLength(0); i++)
                {
                    data = data + "-" + message[i].ToString();
                }
            }
            wtxt = DateTime.Now.ToLongTimeString() + "**" + interfacename + "**" + ordername + "**" + addr_port + "**" + data;
            Common.CCarryConvert.WriteCommLog(DarkCasketFolder, DateTime.Today.ToShortDateString(), wtxt);
        }

        public static void WriteDarkCasket(string DarkCasketFolder, string interfacename, string ordername, string addr_port, ushort[] message)
        {
            string data = "", wtxt;
            if (message == null)
            {
                data = "";
            }
            else
            {
                for (int i = 0; i < message.GetLength(0); i++)
                {
                    data = data + "-" + message[i].ToString();
                }
            }
            wtxt = DateTime.Now.ToLongTimeString() + "**" + interfacename + "**" + ordername + "**" + addr_port + "**" + data;
            Common.CCarryConvert.WriteCommLog(DarkCasketFolder, DateTime.Today.ToShortDateString(), wtxt);
        }

        /// <summary>
        /// 写黑匣子
        /// </summary>
        /// <param name="interfacename"></param>
        /// <param name="ordername"></param>
        /// <param name="addr_port"></param>
        /// <param name="message"></param>
        public static void WriteDarkCasket(string interfacename, string ordername, string addr_port, string message)
        {
            string wtxt;

            wtxt = DateTime.Now.ToLongTimeString() + "**" + interfacename + "**" + ordername + "**" + addr_port + "**" + message;
            Common.CCarryConvert.WriteCommLog(DateTime.Today.ToShortDateString(), wtxt);
        }

        public static void WriteDarkCasket(string DarkCasketFolder, string interfacename, string ordername, string addr_port, string message)
        {
            string wtxt;

            wtxt = DateTime.Now.ToLongTimeString() + "**" + interfacename + "**" + ordername + "**" + addr_port + "**" + message;
            Common.CCarryConvert.WriteCommLog(DarkCasketFolder, DateTime.Today.ToShortDateString(), wtxt);
        }

        /// <summary>
        /// 执行整理黑匣子文件；在app.config文件中找到整理周期
        /// </summary>
        public static void NeatenDarkCasket()
        {
            try
            {
                string filePath;
                string[] files;
                string[] doc = new string[3] { "DarkCasket", "ReceiveAGVDarkCasket", "LoginDarkCasket" };
                AppSettingsReader asr = new AppSettingsReader();
                long FileSum = (long)asr.GetValue("DarkCasketSum", typeof(long));

                for (int ii = doc.GetLowerBound(0); ii <= doc.GetUpperBound(0); ii++)
                {
                    filePath = System.IO.Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().GetName().ToString());
                    filePath = System.IO.Path.GetDirectoryName(filePath);
                    filePath = System.IO.Path.Combine(filePath, doc[ii]);

                    //string mydate, path1, pathnew;
                    if (Directory.Exists(filePath) == false) continue;

                    files = Directory.GetFiles(filePath);
                    Array.Sort(files);//20100521
                    int fc = files.GetLength(0);
                    //string strf = string.Empty;
                    if ((fc - FileSum) < 1) continue;//20100521
                    for (long fi = 0; fi <= (fc - FileSum - 1); fi++)//20100521
                    {
                        File.Delete(files[fi]);
                    }
                    ////20091218
                    //   for (long i = (FileSum); i <=(FileSum+ 100); i++)
                    //   {
                    //       path1 = filePath;
                    //       mydate = DateTime.Today.AddDays(-i).ToShortDateString();

                    //       for (int fcount = 1; fcount <= 99; fcount++)
                    //       {
                    //           if (fcount.ToString().Length < 2)
                    //           {
                    //               strf = "0" + fcount.ToString();
                    //           }
                    //           else
                    //           {
                    //               strf = fcount.ToString();
                    //           }
                    //           pathnew = System.IO.Path.Combine(path1, mydate + strf + ".log");
                    //           if (File.Exists(pathnew) == true)
                    //           {
                    //               File.Delete(pathnew);
                    //           }
                    //       }
                    //   }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}