using APT.Infrastructure.Core;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace APT.Utility
{
    public static partial class DataHelper
    {
        public static string MD5(this string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] arr = UTF8Encoding.Default.GetBytes(str);
            byte[] bytes = md5.ComputeHash(arr);
            str = BitConverter.ToString(bytes);
            str = str.Replace("-", "");
            return str;
        }
        /// <summary>
        /// 将最后一个字符串的路径path替换
        /// </summary>
        /// <param name="str"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string Path(this string str, string path)
        {
            int index = str.LastIndexOf('\\');
            int indexDian = str.LastIndexOf('.');
            return str.Substring(0, index + 1) + path + str.Substring(indexDian);
        }
        public static List<string> ToList(this string ids)
        {
            List<string> listId = new List<string>();
            if (!string.IsNullOrEmpty(ids))
            {
                var sort = new SortedSet<string>(ids.Split(','));
                foreach (var item in sort)
                {
                    listId.Add(item);

                }
            }
            return listId;
        }
        /// <summary>
        /// 从^分割的字符串中获取多个Id,先是用 ^ 分割，再使用 & 分割
        /// </summary>
        /// <param name="ids">先是用 ^ 分割，再使用 & 分割</param>
        /// <returns></returns>
        public static List<string> GetIdSort(this string ids)
        {
            List<string> listId = new List<string>();
            if (!string.IsNullOrEmpty(ids))
            {
                var sort = new SortedSet<string>(ids.Split('^')
                    .Where(w => !string.IsNullOrWhiteSpace(w) && w.Contains('&'))
                    .Select(s => s.Substring(0, s.IndexOf('&'))));
                foreach (var item in sort)
                {
                    listId.Add(item);
                }
            }
            return listId;
        }
        /// <summary>
        /// 从，分割的字符串中获取单个Id
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static string GetId(this string ids)
        {
            if (!string.IsNullOrEmpty(ids))
            {
                var sort = new SortedSet<string>(ids.Split('^')
                    .Where(w => !string.IsNullOrWhiteSpace(w) && w.Contains('&'))
                    .Select(s => s.Substring(0, s.IndexOf('&'))));
                foreach (var item in sort)
                {
                    if (!string.IsNullOrWhiteSpace(item))
                    {
                        return item;
                    }
                }
            }
            return null;
        }
        /// <summary>
        /// 将String转换为Dictionary类型，过滤掉为空的值，首先 6 分割，再 7 分割
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static Dictionary<string, string> StringToDictionary(string value)
        {
            Dictionary<string, string> queryDictionary = new Dictionary<string, string>();
            string[] s = value.Split('^');
            for (int i = 0; i < s.Length; i++)
            {
                if (!string.IsNullOrWhiteSpace(s[i]) && !s[i].Contains("undefined"))
                {
                    var ss = s[i].Split('&');
                    if ((!string.IsNullOrEmpty(ss[0])) && (!string.IsNullOrEmpty(ss[1])))
                    {
                        queryDictionary.Add(ss[0], ss[1]);
                    }
                }

            }
            return queryDictionary;
        }
        /// <summary>
        /// 得到对象的 Int 类型的值，默认值0
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值0</returns>
        public static int GetInt(this object Value)
        {
            return GetInt(Value, 0);
        }
        /// <summary>
        /// 得到对象的 Int 类型的值，默认值0
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <param name="defaultValue">如果转换失败，返回的默认值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值0</returns>
        public static int GetInt(this object Value, int defaultValue)
        {

            if (Value == null) return defaultValue;
            if (Value is string && Value.GetString().HasValue() == false) return defaultValue;

            if (Value is DBNull) return defaultValue;

            if ((Value is string) == false && (Value is IConvertible) == true)
            {
                return (Value as IConvertible).ToInt32(CultureInfo.CurrentCulture);
            }

            int retVal = defaultValue;
            if (int.TryParse(Value.ToString(), NumberStyles.Any, CultureInfo.CurrentCulture, out retVal))
            {
                return retVal;
            }
            else
            {
                return defaultValue;
            }
        }
        /// <summary>
        /// 得到对象的 String 类型的值，默认值string.Empty
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值string.Empty</returns>
        public static string GetString(this object Value)
        {
            return GetString(Value, string.Empty);
        }
        /// <summary>
        /// 得到对象的 String 类型的值，默认值string.Empty
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <param name="defaultValue">如果转换失败，返回的默认值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值 。</returns>
        public static string GetString(this object Value, string defaultValue)
        {
            if (Value == null) return defaultValue;
            string retVal = defaultValue;
            try
            {
                var strValue = Value as string;
                if (strValue != null)
                {
                    return strValue;
                }

                char[] chrs = Value as char[];
                if (chrs != null)
                {
                    return new string(chrs);
                }

                retVal = Value.ToString();
            }
            catch
            {
                return defaultValue;
            }
            return retVal;
        }
        /// <summary>
        /// 得到对象的 DateTime 类型的值，默认值为DateTime.MinValue
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回的默认值为DateTime.MinValue </returns>
        public static DateTime GetDateTime(this object Value)
        {
            return GetDateTime(Value, DateTime.MinValue);
        }

        /// <summary>
        /// 得到对象的 DateTime 类型的值，默认值为DateTime.MinValue
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <param name="defaultValue">如果转换失败，返回默认值为DateTime.MinValue</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回的默认值为DateTime.MinValue</returns>
        public static DateTime GetDateTime(this object Value, DateTime defaultValue)
        {
            if (Value == null) return defaultValue;

            if (Value is DBNull) return defaultValue;

            string strValue = Value as string;
            if (strValue == null && (Value is IConvertible))
            {
                return (Value as IConvertible).ToDateTime(CultureInfo.CurrentCulture);
            }
            if (strValue != null)
            {
                strValue = strValue
                    .Replace("年", "-")
                    .Replace("月", "-")
                    .Replace("日", "-")
                    .Replace("点", ":")
                    .Replace("时", ":")
                    .Replace("分", ":")
                    .Replace("秒", ":")
                      ;
            }
            DateTime dt = defaultValue;
            if (DateTime.TryParse(Value.GetString(), out dt))
            {
                return dt;
            }

            return defaultValue;
        }
        /// <summary>
        /// 得到对象的布尔类型的值，默认值false
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值false</returns>
        public static bool GetBool(this object Value)
        {
            return GetBool(Value, false);
        }

        /// <summary>
        /// 得到对象的 Bool 类型的值，默认值false
        /// </summary>
        /// <param name="Value">要转换的值</param>
        /// <param name="defaultValue">如果转换失败，返回的默认值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值false</returns>
        public static bool GetBool(this object Value, bool defaultValue)
        {
            if (Value == null) return defaultValue;
            if (Value is string && Value.GetString().HasValue() == false) return defaultValue;

            if ((Value is string) == false && (Value is IConvertible) == true)
            {
                if (Value is DBNull) return defaultValue;

                try
                {
                    return (Value as IConvertible).ToBoolean(CultureInfo.CurrentCulture);
                }
                catch { }
            }

            if (Value is string)
            {
                if (Value.GetString() == "0") return false;
                if (Value.GetString() == "1") return true;
                if (Value.GetString().ToLower() == "yes") return true;
                if (Value.GetString().ToLower() == "no") return false;
            }
            ///  if (Value.GetInt(0) != 0) return true;
            bool retVal = defaultValue;
            if (bool.TryParse(Value.GetString(), out retVal))
            {
                return retVal;
            }
            else return defaultValue;
        }
        /// <summary>
        /// 检测 GuidValue 是否包含有效的值，默认值Guid.Empty
        /// </summary>
        /// <param name="GuidValue">要转换的值</param>
        /// <returns>如果对象的值可正确返回， 返回对象转换的值 ，否则， 返回默认值Guid.Empty</returns>
        public static Guid GetGuid(string GuidValue)
        {
            try
            {
                return new Guid(GuidValue);
            }
            catch { return Guid.Empty; }
        }
        /// <summary>
        /// 检测 Value 是否包含有效的值，默认值false
        /// </summary>
        /// <param name="Value"> 传入的值</param>
        /// <returns> 包含，返回true，不包含，返回默认值false</returns>
        public static bool HasValue(this string Value)
        {
            if (Value != null)
            {
                return !string.IsNullOrEmpty(Value.ToString());
            }
            else return false;
        }

        /// <summary>
        ///  string 自动填充前导0 
        /// </summary>
        /// <param name="Str"> 传入的值</param>
        /// <param name="length"> 长度</param>
        /// <returns> 包含，返回str</returns>
        public static string FromatStrLen(string Str, int length)
        {
            if (Str.Length < length)
            {
                Str = Str.PadLeft(length, '0');
            }

            return Str;

        }
        /// <summary>
        /// 字符位置
        /// </summary>
        /// <param name="i"></param>
        /// <param name="p"></param>
        /// <returns>当转换失败时返回0</returns>
        public static int ToWtStrIndexOfArray(string i, string p)
        {
            string[] v = i.Split(',');
            return Array.IndexOf(v, p);
        }

        /// <summary>
        /// 获取枚举 信息
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static dynamic GetEnum(string name)
        {
            var type = EnumToType(name);
            List<EnumsResult> list = new List<EnumsResult>();
            if (type != null && type.IsEnum)
            {
                var enums = Enum.GetValues(type);
                string description = string.Empty;
                foreach (var x in enums)
                {
                    EnumsResult enumOpyion = new EnumsResult();
                    enumOpyion.ID = (int)x;

                    description = EnumExtensions.GetDescription((System.Enum)x);
                    if (!string.IsNullOrEmpty(description))
                    {
                        enumOpyion.NAME = description;
                    }
                    else
                    {
                        enumOpyion.NAME = x.ToString();
                    }

                    list.Add(enumOpyion);
                }
            }
            return list;
        }

        /// <summary>
        /// 获取所有的枚举信息
        /// </summary>
        /// <returns></returns>
        public static List<EnumInfo> GetAllEnums()
        {
            List<EnumInfo> result = new List<EnumInfo>();
            var files = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, "*.Domain.dll");
            if (files.Length > 0)
            {
                foreach (var file in files)
                {
                    var assembly = Assembly.LoadFrom(file);
                    if (assembly != null)
                    {
                        foreach (var item in assembly.GetTypes())
                        {
                            var tableDesc = "";
                            object[] attribArray = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
                            if (attribArray.Length > 0)
                                tableDesc = (attribArray[0] as DescriptionAttribute).Description;
                            if (item.IsEnum)
                            {
                                EnumInfo info = new EnumInfo();
                                info.EnumName = item.Name;
                                int i = 0;
                                bool isSort = false;
                                foreach (var x in Enum.GetValues(item))
                                {
                                    int tempIndex = i;
                                    EnumDetailInfo detailInfo = new EnumDetailInfo();

                                    detailInfo.label = x.ToString();
                                    detailInfo.value = (int)x;
                                    var fieldInfo = item.GetField(x.ToString());
                                    if (fieldInfo != null)
                                    {
                                        EnumSortIndexAttribute[] enumSortIndexAttributes = (EnumSortIndexAttribute[])fieldInfo.
                                                        GetCustomAttributes(typeof(EnumSortIndexAttribute), false);
                                        if (enumSortIndexAttributes.Length > 0)
                                        {
                                            tempIndex = enumSortIndexAttributes[0].SortIndex;
                                            isSort = true;
                                        }
                                        DescriptionAttribute descAttr = (DescriptionAttribute)fieldInfo.GetCustomAttribute
                                               (typeof(DescriptionAttribute));
                                        if (descAttr != null)
                                            detailInfo.label = descAttr.Description;
                                    }
                                    detailInfo.sortIndex = tempIndex;
                                    i++;
                                    info.options.Add(detailInfo);
                                }
                                if (isSort)
                                    info.options = info.options.OrderBy(t => t.sortIndex).ToList();
                                result.Add(info);
                            }
                        }
                    }
                }
            }
            return result;

        }

        /// <summary>
        /// C# guid 转 oracle
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string DotNetToOracle(string text)
        {

            Guid guid = new Guid(text);

            return BitConverter.ToString(guid.ToByteArray()).Replace("-", "");

        }
        /// <summary>
        /// oracle转C# guid
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string OracleToDotNet(string text)

        {

            byte[] bytes = ParseHex(text);

            Guid guid = new Guid(bytes);

            return guid.ToString().ToUpperInvariant();

        }

        public static byte[] ParseHex(string text)

        {

            byte[] ret = new byte[text.Length / 2];

            for (int i = 0; i < ret.Length; i++)

            {

                ret[i] = Convert.ToByte(text.Substring(i * 2, 2), 16);

            }

            return ret;

        }

        /// <summary>
        /// 获取枚举类型
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Type EnumToType(string name)
        {
            if (string.IsNullOrEmpty(name)) return null;
            name = name.Trim();
            var type = APT.Infrastructure.Core.Refctor.ReflectHelper.FindTypeInCurrentDomain(name);
            //if (string.IsNullOrEmpty(name)) return null;
            //var fullname = new string[] { "APT.BaseData.Domain.Enums.", " APT.MS.Domain.Enums.", "APT.MS.Domain.Entities." };
            //var realName = new List<string>();
            //foreach (var f in fullname)
            //{
            //    if (!name.StartsWith(f))
            //    {
            //        realName.Add(f + name);
            //    }
            //    else
            //    {
            //        realName.Add(name);
            //        break;
            //    }

            //}
            //var files = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, "*.Domain.dll");
            //Type type = null;
            //if (files.Length > 0)
            //{
            //    foreach (var file in files)
            //    {
            //        var assembly = Assembly.LoadFrom(file);
            //        if (assembly != null)
            //        {
            //            foreach (var real in realName)
            //            {
            //                type = assembly.GetType(real);
            //                if (type != null)
            //                    break;
            //            }
            //            if (type != null)
            //                break;
            //        }
            //    }
            //}
            return type;
        }


        /// <summary>
        /// 枚举转字符串
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string EnumToString(string name)
        {
            var type = EnumToType(name);
            var res = name;
            if (type != null && type.IsEnum)
            {
                res = "";
                foreach (var x in Enum.GetValues(type))
                {
                    res += (x + ":" + (int)x) + ",";
                }

            }
            return res.TrimEnd(',');
        }
        public class FiledProper
        {
            /// <summary>
            /// 字段名称
            /// </summary>
            public string FileName { get; set; }
            /// <summary>
            /// 类型名称
            /// </summary>
            public string TypeName { get; set; }
            /// <summary>
            /// 显示名称
            /// </summary>
            public string Description { get; set; }
            /// <summary>
            /// 是否自定义类型
            /// </summary>
            public bool IsCustom { get; set; }
            /// <summary>
            /// 是否显示
            /// </summary>
            public bool IsDefault { get; set; }
            /// <summary>
            /// 是否必输
            /// </summary>
            public bool IsRequired { get; set; }

            /// <summary>控件类型PFControlTypeEnum</summary>
            public int ControlType { get; set; }

            /// <summary>忽视拷贝</summary>
            public bool IsCopy { get; set; }

            /// <summary>
            /// 枚举
            /// </summary>
            public string EnumName { get; set; }

        }


        public static Type GetTypeByEntityName(string entityName)
        {
            entityName = entityName.Trim();
            var es = entityName.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
            entityName = es[es.Length - 1];
            var files = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, "*.Domain.dll");
            Type type = null;
            if (files.Length > 0)
            {
                foreach (var file in files)
                {
                    var assembly = Assembly.LoadFrom(file);
                    if (assembly != null)
                    {
                        var types = assembly.GetTypes();
                        foreach (var t in types)
                        {
                            if (t.Name == entityName)
                            {
                                type = t;
                                break;
                            }
                        }
                        if (type != null)
                            break;
                    }
                }
            }
            if (type == null)
            {
                files = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, "APT.Infrastructure.Core.dll");
                if (files.Length > 0)
                {
                    foreach (var file in files)
                    {
                        var assembly = Assembly.LoadFrom(file);
                        if (assembly != null)
                        {
                            var types = assembly.GetTypes();
                            foreach (var t in types)
                            {
                                if (t.Name == entityName)
                                {
                                    type = t;
                                    break;
                                }
                            }
                            if (type != null)
                                break;
                        }
                    }
                }
            }
            return type;
        }


        public static List<FiledProper> EntityFieldList(string entityName)
        {
            var baseEntityName = "APT.Infrastructure.Core.MesEntityBase";
            string[] GenricTypes = new string[] { "DateTime", "Int32", "Decimal", "String", "Guid", "Boolean", "Double" };
            var propertieList = new List<FiledProper>();
            var type = GetTypeByEntityName(entityName);
            var res = entityName;
            if (type != null)
            {
                //基础类型
                var file = System.IO.Directory.GetFiles(System.AppContext.BaseDirectory, "APT.Infrastructure.Core.dll");
                string[] baseProperties = new string[30];
                if (file.Length > 0)
                {
                    var assembly = Assembly.LoadFrom(file[0]);
                    var baseType = assembly.GetType(baseEntityName);
                    baseProperties = baseType.GetProperties().Select(i => i.Name).ToArray(); ;
                }

                PropertyInfo[] properties = type.GetProperties().ToArray();
                foreach (PropertyInfo info in properties)
                {
                    var filed = new FiledProper();
                    filed.FileName = info.Name;

                    if (info.PropertyType.IsGenericType && info.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        // If it is NULLABLE, then get the underlying type. eg if "Nullable<int>" then this will return just "int"
                        filed.TypeName = info.PropertyType.GetGenericArguments()[0].Name;
                        filed.IsRequired = false;
                    }
                    else
                    {
                        filed.TypeName = info.PropertyType.Name;
                        filed.IsRequired = true;
                    }
                    if (GenricTypes.Contains(filed.TypeName))
                    {
                        filed.IsCustom = false;
                        //基类包含
                        if (baseProperties.Contains(info.Name) || filed.TypeName == "Guid")
                        {
                            continue;
                        }
                        else
                        {
                            filed.IsDefault = true;
                        }
                        switch (filed.TypeName)
                        {
                            case "DateTime":
                                filed.ControlType = 2;//日期
                                break;
                            case "Int32":
                                filed.ControlType = 3;//下拉
                                break;
                            case "Decimal":
                            case "Double":
                                filed.ControlType = 7;//数值
                                break;
                            case "Boolean":
                                filed.ControlType = 5;//多项选框
                                break;
                            default:
                                filed.ControlType = 1;//文本
                                break;
                        }
                        //不显示字段默认不复制
                        if (filed.IsDefault || string.Compare(info.Name, "PARENT_ID", true) == 0 || string.Compare(info.Name, "IS_LEAF", true) == 0
                             || string.Compare(info.Name, "ORG_ID", true) == 0)
                            filed.IsCopy = true;
                    }
                    else
                    {
                        continue;
                    }
                    //内置类型
                    //if (GenricTypeinfo.PropertyType == typeof(object)
                    //    || Type.GetTypeCode(info.PropertyType) != TypeCode.Object
                    //    || filed.TypeName == "DateTime"
                    //    || filed.TypeName == "Guid")
                    //{
                    //    filed.IsCustom = false;
                    //}
                    //else
                    //{
                    //    filed.IsCustom = true;
                    //}
                    //注释
                    var v = (DescriptionAttribute[])info.GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (v != null && v.Length > 0)
                    {
                        filed.Description = v[0].Description;
                    }
                    var v1 = (EnumNameAttribute[])info.GetCustomAttributes(typeof(EnumNameAttribute), false);
                    if (v1 != null && v1.Length > 0)
                    {
                        filed.EnumName = v1[0].EnumName;
                    }
                    propertieList.Add(filed);
                }

            }
            return propertieList;
        }


        public static string ToStringByDic(Dictionary<string, object> dic)
        {
            StringBuilder sb = new StringBuilder();
            if (dic != null && dic.Any())
            {
                foreach (var p in dic)
                    sb.Append(p.Key + ":" + (p.Value == null ? "" : p.Value.ToString()) + ",");
            }
            if (sb.Length > 0)
                sb.Length--;
            return sb.ToString();
        }

        public static string ToStringByTable(List<Dictionary<string, object>> tables)
        {
            StringBuilder sb = new StringBuilder();
            if (tables != null && tables.Any())
            {
                foreach (var r in tables)
                {
                    string str = ToStringByDic(r);
                    if (!string.IsNullOrEmpty(str))
                    {
                        sb.Append(str);
                        sb.Append("||");
                    }
                }
            }
            if (sb.Length > 0)
                sb.Length = sb.Length - 2;
            return sb.ToString();
        }



        public static Dictionary<string, object> ToDicByString(string str)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            if (string.IsNullOrEmpty(str)) return dic;
            var array = str.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (array != null && array.Length != 0)
            {
                foreach (var item in array)
                {
                    var temp = item.Split(':');
                    if (temp != null && temp.Length >= 2)
                        dic[temp[0]] = temp[1];
                }
            }
            return dic;
        }

        public static List<Dictionary<string, object>> ToTableByString(string str)
        {
            List<Dictionary<string, object>> tables = new List<Dictionary<string, object>>();
            if (string.IsNullOrEmpty(str)) return tables;
            var array = str.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
            if (array != null && array.Length != 0)
            {
                foreach (var item in array)
                {
                    if (string.IsNullOrEmpty(item)) continue;
                    var temp = ToDicByString(item);
                    if (temp != null && temp.Any())
                        tables.Add(temp);
                }
            }
            return tables;
        }


        public static StringDictionary GetStringDictionary(string s)
        {
            StringDictionary ret = new StringDictionary();
            if (string.IsNullOrEmpty(s)) return ret;
            var temps = s.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            temps.ForEach(t =>
            {
                var temp = t.Split('=');
                if (temp.Length >= 2)
                    ret.SetValue(temp[0], temp[1]);
            });
            return ret;
        }

        /// <summary>
        /// 将“yyyyMMdd”格式的int值转换为日期值。
        /// </summary>
        public static DateTime FromIDate(this int date)
        {
            return new DateTime(date / 10000, date / 100 % 100, date % 100);
        }

        /// <summary>
        /// 将“yyyyMMdd”格式的int值转换为日期值。
        /// </summary>
        public static DateTime FromIHour(this int date)
        {
            return new DateTime(date / 1000000, date / 10000 % 100, date / 100 % 100, date % 100, 0, 0);
        }

        /// <summary>
        /// 将“yyyyMM”格式的int值转换为日期值。
        /// </summary>
        public static DateTime FromIMonth(this int date)
        {
            return new DateTime(date / 100, date % 100, 1);
        }

        /// <summary>
        /// 将日期值转换为“yyyyMMdd”格式的int值。
        /// </summary>
        public static int ToIDate(this DateTime date)
        {
            return date.Year * 10000 + date.Month * 100 + date.Day;
        }

        /// <summary>
        /// 将日期值转换为“yyyyMMddHH”格式的int值。
        /// </summary>
        public static int ToIHour(this DateTime date)
        {
            return date.Year * 1000000 + date.Month * 10000 + date.Day * 100 + date.Hour;
        }

        /// <summary>
        /// 将日期值转换为“yyyyMM”格式的int值。
        /// </summary>
        public static int ToIMonth(this DateTime date)
        {
            return date.Year * 100 + date.Month;
        }

        /// <summary>
        /// 将日期值转换为“yyyyMM”格式的int值。
        /// </summary>
        public static int ToIYear(this DateTime date)
        {
            return date.Year;
        }

        /// <summary>
        /// 将“yyyy”格式的int值转换为日期值。
        /// </summary>
        public static DateTime FromIYear(this int date)
        {
            return new DateTime(date, 1, 1);
        }

        /// <summary>
        /// 将整型格式的值转为日期值。
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static DateTime FromITime(this int date)
        {
            if (date > 1000000000)
                return date.FromIHour();
            if (date > 10000000)
                return date.FromIDate();
            if (date > 10000)
                return date.FromIMonth();
            return date.FromIYear();
        }

        public static long GetTimeSpanFrom1970Ticks(DateTime dateTime)
        {
            return (dateTime.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
        }
        /// <summary>
        /// 时间戳转为C#格式时间10位
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        public static DateTime GetDateTimeFrom1970Ticks(long curSeconds)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            return dtStart.AddSeconds(curSeconds);
        }
        /// <summary>
        /// 判断二进制某位是否为1
        /// </summary>
        /// <param name="num"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static bool IsThirdBitOne(int num, int n)
        {
            //使用ToString()方法，转换成二进制,第二个参数只能是，2，8，16；
            string s = Convert.ToString(num, 2);
            //在选择第n位数字与1比较
            int b = s[n - 1] & 1;
            if (b == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static List<BitAnd> IsThirdBitArr(int num, List<BitAnd> bitAnds)
        {
            //使用ToString()方法，转换成二进制,第二个参数只能是，2，8，16；
            string s = Convert.ToString(num, 2).PadLeft(16, '0');
            //在选择第n位数字与1比较
            foreach (var bitAnd in bitAnds)
            {
                int b = s[bitAnd.position - 1] & 1;
                if (b == 1)
                {
                    bitAnd.isTrue = true;
                }
                else
                {
                    bitAnd.isTrue = false;
                }
            }
            return bitAnds;
        }
        /// <summary>
        /// 获取请求类型
        /// 1：PC    2：app
        /// </summary>
        /// <param name="Headers">请求头</param>
        /// <returns></returns>
        public static int GetRequestType(IHeaderDictionary Headers)
        {
            int RequestType = 1;
            if (Headers.ContainsKey("RequestType"))
            {
                string strRequestType = Headers["RequestType"];
                if (!string.IsNullOrEmpty(strRequestType))
                {
                    try
                    {
                        RequestType = int.Parse(strRequestType);
                    }
                    catch
                    {
                        RequestType = 1;
                    }
                }
            }
            return RequestType;
        }


        #region     wyw 获取初始化密码


        /// <summary>
        /// 去除首几位字母变成数字
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string GetCodeNO(string input)
        {
            Regex reg = new Regex(@"^[0-9]*$");
            int length = input.Length;
            string val = string.Empty;
            Match a = null;
            for (int i = 0; i < length; i++)
            {
                a = reg.Match(input);
                if (!a.Success)
                {
                    input = input.Substring(1);
                }
                else
                {
                    val = a.Value;
                    break;
                }
            }
            return val;
        }

        /// <summary>
        /// 32位MD5加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static string MD5Encrypt32(MD5 md5, string password)
        {
            string cl = password;
            string pwd = "";
            //MD5 md5 = MD5.Create(); //实例化一个md5对像
            // 加密后是一个字节类型的数组，这里要注意编码UTF8/Unicode等的选择　
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(cl));
            // 通过使用循环，将字节类型的数组转换为字符串，此字符串是常规字符格式化所得
            for (int i = 0; i < s.Length; i++)
            {
                // 将得到的字符串使用十六进制类型格式。格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                pwd = pwd + s[i].ToString("X2");
            }
            return pwd;
        }


        #region 获取汉字转换拼音 首字母

        /// <summary>
        /// 
        /// </summary>
        /// <param name="HanZiStr"></param>
        /// <returns></returns>
        public static string MkPinyinString(string HanZiStr, bool isMore = false)
        //获取汉字字符串的拼音首字母，含多音字
        {
            int i, j, k, m;
            string tmpStr;
            string returnStr = "";  //返回最终结果的字符串
            string[] tmpArr;
            for (i = 0; i < HanZiStr.Length; i++)
            {   //处理汉字字符串,对每个汉字的首字母进行一次循环
                tmpStr = GetPinyin((char)HanZiStr[i], isMore);   //获取第i个汉字的拼音首字母,可能为1个或多个
                if (i != 0)
                {
                    //首字母大写 其余小写
                    tmpStr = tmpStr.ToLower();
                }
                if (tmpStr.Length > 0)
                {   //汉字的拼音首字母存在的情况才进行操作
                    if (returnStr != "")
                    {   //不是第一个汉字
                        Regex regex = new Regex(",");
                        tmpArr = regex.Split(returnStr);
                        returnStr = "";
                        for (k = 0; k < tmpArr.Length; k++)
                        {
                            for (j = 0; j < tmpStr.Length; j++)    //对返回的每个首字母进行拼接
                            {
                                string charcode = tmpStr[j].ToString(); //取出第j个拼音字母
                                returnStr += tmpArr[k] + charcode + ",";
                            }
                        }
                        if (returnStr != "")
                            returnStr = returnStr.Substring(0, returnStr.Length - 1);
                    }
                    else
                    {   //构造第一个汉字返回结果
                        for (m = 0; m < tmpStr.Length - 1; m++)
                            returnStr += tmpStr[m] + ",";
                        returnStr += tmpStr[tmpStr.Length - 1];
                    }
                }
            }
            return returnStr;   //返回处理结果字符串，以，分隔每个拼音组合
        }

        private static string GetPinyin(char HanZi, bool isMore) //获取单个汉字对应的拼音首字符字符串，
        {
            // 汉字拼音首字母列表 本列表包含了20902个汉字,收录的字符的Unicode编码范围为19968至40869
            string strChineseFirstPY = " ";
            //此处收录了375个多音字
            string MultiPinyin = string.Empty;
            if (isMore)
            {
                MultiPinyin = "19969:DZ,19975:WM,19988:QJ,20048:YL,20056:SC,20060:NM,20094:QG,20127:QJ,20167:QC,20193:YG,20250:KH,20256:ZC,20282:SC,20285:QJG,20291:TD,20314:YD,20340:NE,20375:TD,20389:YJ,20391:CZ,20415:PB,20446:YS,20447:SQ,20504:TC,20608:KG,20854:QJ,20857:ZC,20911:PF,20504:TC,20608:KG,20854:QJ,20857:ZC,20911:PF,20985:AW,21032:PB,21048:XQ,21049:SC,21089:YS,21119:JC,21242:SB,21273:SC,21305:YP,21306:QO,21330:ZC,21333:SDC,21345:QK,21378:CA,21397:SC,21414:XS,21442:SC,21477:JG,21480:TD,21484:ZS,21494:YX,21505:YX,21512:HG,21523:XH,21537:PB,21542:PF,21549:KH,21571:E,21574:DA,21588:TD,21589:O,21618:ZC,21621:KHA,21632:ZJ,21654:KG,21679:LKG,21683:KH,21710:A,21719:YH,21734:WOE,21769:A,21780:WN,21804:XH,21834:A,21899:ZD,21903:RN,21908:WO,21939:ZC,21956:SA,21964:YA,21970:TD,22003:A,22031:JG,22040:XS,22060:ZC,22066:ZC,22079:MH,22129:XJ,22179:XA,22237:NJ,22244:TD,22280:JQ,22300:YH,22313:XW,22331:YQ,22343:YJ,22351:PH,22395:DC,22412:TD,22484:PB,22500:PB,22534:ZD,22549:DH,22561:PB,22612:TD,22771:KQ,22831:HB,22841:JG,22855:QJ,22865:XQ,23013:ML,23081:WM,23487:SX,23558:QJ,23561:YW,23586:YW,23614:YW,23615:SN,23631:PB,23646:ZS,23663:ZT,23673:YG,23762:TD,23769:ZS,23780:QJ,23884:QK,24055:XH,24113:DC,24162:ZC,24191:GA,24273:QJ,24324:NL,24377:TD,24378:QJ,24439:PF,24554:ZS,24683:TD,24694:WE,24733:LK,24925:TN,25094:ZG,25100:XQ,25103:XH,25153:PB,25170:PB,25179:KG,25203:PB,25240:ZS,25282:FB,25303:NA,25324:KG,25341:ZY,25373:WZ,25375:XJ,25384:A,25457:A,25528:SD,25530:SC,25552:TD,25774:ZC,25874:ZC,26044:YW,26080:WM,26292:PB,26333:PB,26355:ZY,26366:CZ,26397:ZC,26399:QJ,26415:ZS,26451:SB,26526:ZC,26552:JG,26561:TD,26588:JG,26597:CZ,26629:ZS,26638:YL,26646:XQ,26653:KG,26657:XJ,26727:HG,26894:ZC,26937:ZS,26946:ZC,26999:KJ,27099:KJ,27449:YQ,27481:XS,27542:ZS,27663:ZS,27748:TS,27784:SC,27788:ZD,27795:TD,27812:O,27850:PB,27852:MB,27895:SL,27898:PL,27973:QJ,27981:KH,27986:HX,27994:XJ,28044:YC,28065:WG,28177:SM,28267:QJ,28291:KH,28337:ZQ,28463:TL,28548:DC,28601:TD,28689:PB,28805:JG,28820:QG,28846:PB,28952:TD,28975:ZC,29100:A,29325:QJ,29575:SL,29602:FB,30010:TD,30044:CX,30058:PF,30091:YSP,30111:YN,30229:XJ,30427:SC,30465:SX,30631:YQ,30655:QJ,30684:QJG,30707:SD,30729:XH,30796:LG,30917:PB,31074:NM,31085:JZ,31109:SC,31181:ZC,31192:MLB,31293:JQ,31400:YX,31584:YJ,31896:ZN,31909:ZY,31995:XJ,32321:PF,32327:ZY,32418:HG,32420:XQ,32421:HG,32438:LG,32473:GJ,32488:TD,32521:QJ,32527:PB,32562:ZSQ,32564:JZ,32735:ZD,32793:PB,33071:PF,33098:XL,33100:YA,33152:PB,33261:CX,33324:BP,33333:TD,33406:YA,33426:WM,33432:PB,33445:JG,33486:ZN,33493:TS,33507:QJ,33540:QJ,33544:ZC,33564:XQ,33617:YT,33632:QJ,33636:XH,33637:YX,33694:WG,33705:PF,33728:YW,33882:SR,34067:WM,34074:YW,34121:QJ,34255:ZC,34259:XL,34425:JH,34430:XH,34485:KH,34503:YS,34532:HG,34552:XS,34558:YE,34593:ZL,34660:YQ,34892:XH,34928:SC,34999:QJ,35048:PB,35059:SC,35098:ZC,35203:TQ,35265:JX,35299:JX,35782:SZ,35828:YS,35830:E,35843:TD,35895:YG,35977:MH,36158:JG,36228:QJ,36426:XQ,36466:DC,36710:JC,36711:ZYG,36767:PB,36866:SK,36951:YW,37034:YX,37063:XH,37218:ZC,37325:ZC,38063:PB,38079:TD,38085:QY,38107:DC,38116:TD,38123:YD,38224:HG,38241:XTC,38271:ZC,38415:YE,38426:KH,38461:YD,38463:AE,38466:PB,38477:XJ,38518:YT,38551:WK,38585:ZC,38704:XS,38739:LJ,38761:GJ,38808:SQ,39048:JG,39049:XJ,39052:HG,39076:CZ,39271:XT,39534:TD,39552:TD,39584:PB,39647:SB,39730:LG,39748:TPB,40109:ZQ,40479:ND,40516:HG,40536:HG,40583:QJ,40765:YQ,40784:QJ,40840:YK,40863:QJG,";
            }
            string resStr = "";
            int i, j, uni;
            uni = (UInt16)HanZi;
            if (uni > 40869 || uni < 19968)
                return resStr;
            //返回该字符在Unicode字符集中的编码值
            if (isMore)
            {
                i = MultiPinyin.IndexOf(uni.ToString());
            }
            else
            {
                i = -1;
            }
            //检查是否是多音字,是按多音字处理,不是就直接在strChineseFirstPY字符串中找对应的首字母
            if (i < 0)
            //获取非多音字汉字首字母
            {
                resStr = strChineseFirstPY[uni - 19968].ToString();
            }
            else
            {   //获取多音字汉字首字母
                j = MultiPinyin.IndexOf(",", i);
                resStr = MultiPinyin.Substring(i + 6, j - i - 6);
            }
            return resStr;

        }

        #endregion

        #endregion

    }
    public class BitAnd
    {
        public int position { get; set; }

        public bool isTrue { get; set; }
    }
    public class StringDictionary
    {

        private Dictionary<string, string> _dic = new Dictionary<string, string>();

        public string this[string key]
        {
            get
            {
                return GetValue(key);
            }
        }

        public string GetValue(string key)
        {
            // if(stirng.i)
            if (string.IsNullOrEmpty(key)) return string.Empty;
            string v = string.Empty;
            if (_dic.ContainsKey(key))
                return _dic[key];
            else
                return string.Empty;
        }

        public void SetValue(string key, string value)
        {
            if (string.IsNullOrEmpty(key)) return;
            _dic[key] = value;
        }

    }


    public static class CopyUtils
    {
        private static string[] NoCopyFields = new string[] { "ID", "IS_DELETED", "FLOW_STATUS", "FLOW_SEND_STATUS", "PARENT_ID", "IS_LEAF", "TEXT", "RowVersion", "FORM_ID", "FLOW_ID" };

        public static void CopyObject(object target, object source, params string[] noCopyFiels)
        {
            Type type1 = target.GetType();
            Type type2 = source.GetType();
            foreach (var mi in type2.GetProperties())
            {
                if (mi.Name.StartsWith("Nav_", StringComparison.OrdinalIgnoreCase) ||
                    NoCopyFields.Contains(mi.Name) || noCopyFiels != null && noCopyFiels.Contains(mi.Name)) continue;
                var des = type1.GetProperty(mi.Name);
                if (des != null && des.PropertyType == mi.PropertyType)
                {
                    try
                    {
                        des.SetValue(target, mi.GetValue(source, null), null);
                    }
                    catch
                    { }
                }
            }
        }

    }




    /// <summary>
    /// 枚举对象
    /// </summary>
    public class EnumInfo
    {
        public EnumInfo()
        {
            this.options = new List<EnumDetailInfo>();
        }

        public string EnumName { get; set; }

        public List<EnumDetailInfo> options { get; set; }
    }

    /// <summary>
    /// 枚举明细
    /// </summary>
    public class EnumDetailInfo
    {
        public string label { get; set; }

        public int value { get; set; }

        public int sortIndex { get; set; }
    }


    public class EnumsResult
    {
        public string NAME { get; set; }

        public int ID { get; set; }
    }
}
