using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text.RegularExpressions;
using MySystem.Models;
using Library;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;

namespace MySystem
{
    public class PublicFunction
    {
        public WebCMSEntities db = new WebCMSEntities();
        public BsModels.WebCMSEntities bsdb = new BsModels.WebCMSEntities();
        public OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();

        #region 获取权限JSON数据

        public string GetRightJson()
        {
            string result = "[";
            List<BsModels.RightDic> list = bsdb.RightDic.ToList();
            List<BsModels.RightDic> Level1 = list.Where(m => m.RightLevel == 1).ToList();
            foreach (BsModels.RightDic sub1 in Level1)
            {
                result += "{title: '" + sub1.Name + "', id: '" + sub1.Id + "', spread: false, children: [";
                List<BsModels.RightDic> Level2 = list.Where(m => m.RightLevel == 2 && m.Id.StartsWith(sub1.Id)).ToList();
                if (Level2.Count > 0)
                {
                    foreach (BsModels.RightDic sub2 in Level2)
                    {
                        result += "{title: '" + sub2.Name + "', id: '" + sub2.Id + "', spread: false, children: [";
                        List<BsModels.RightDic> Level3 = list.Where(m => m.RightLevel == 3 && m.Id.StartsWith(sub2.Id)).ToList();
                        if (Level3.Count > 0)
                        {
                            foreach (BsModels.RightDic sub3 in Level3)
                            {
                                result += "{title: '" + sub3.Name + "', id: '" + sub3.Id + "', spread: false, children: [";
                                string rightString = ForOperateRight(sub3.Id);
                                if (!string.IsNullOrEmpty(rightString))
                                {
                                    result += rightString;
                                }
                                else
                                {
                                    result += "{title: '基本权限', id: '" + sub3.Id + "_base'}";
                                }
                                result += "]},";
                            }
                            result = result.TrimEnd(',');
                        }
                        else
                        {
                            string rightString = ForOperateRight(sub2.Id);
                            if (!string.IsNullOrEmpty(rightString))
                            {
                                result += rightString;
                            }
                            else
                            {
                                result += "{title: '基本权限', id: '" + sub2.Id + "_base'}";
                            }
                        }
                        result += "]},";
                    }
                    result = result.TrimEnd(',');
                }
                else
                {
                    result += ForOperateRight(sub1.Id);
                    string rightString = ForOperateRight(sub1.Id);
                    if (!string.IsNullOrEmpty(rightString))
                    {
                        result += rightString;
                    }
                    else
                    {
                        result += "{title: '基本权限', id: '" + sub1.Id + "_base'}";
                    }
                }
                result += "]},";
            }
            result = result.TrimEnd(',');
            result += "]";
            return result;
        }
        //读取当前菜单有哪些权限
        public string ForOperateRight(string Id)
        {
            string result = "";
            List<BsModels.MenuRight> rights = bsdb.MenuRight.Where(m => m.MenuId.StartsWith(Id)).OrderBy(m => m.MenuId).ToList();
            foreach (BsModels.MenuRight right in rights)
            {
                result += "{title: '" + right.Name + "', id: '" + right.MenuId + "'},";
            }
            BsModels.RightDic rightDic = bsdb.RightDic.FirstOrDefault(m => m.Id == Id) ?? new BsModels.RightDic();
            if (!string.IsNullOrEmpty(rightDic.OtherRight))
            {
                string[] OtherRightList = rightDic.OtherRight.Split('\n');
                foreach (string SubOtherRight in OtherRightList)
                {
                    string[] SubOtherRightData = SubOtherRight.Split('_');
                    result += "{title: '" + SubOtherRightData[1] + "', id: '" + Id + "_" + SubOtherRightData[0] + "'},";
                }
            }
            result = result.TrimEnd(',');
            return result;
        }

        public string GetRightJsonNew()
        {
            string result = "[";
            List<BsModels.RightDicNew> list = bsdb.RightDicNew.ToList();
            List<BsModels.RightDicNew> Level1 = list.Where(m => m.RightLevel == 1).ToList();
            foreach (BsModels.RightDicNew sub1 in Level1)
            {
                result += "{title: '" + sub1.Name + "', id: '" + sub1.Id + "', spread: false, children: [";
                List<BsModels.RightDicNew> Level2 = list.Where(m => m.RightLevel == 2 && m.Id.StartsWith(sub1.Id)).ToList();
                if (Level2.Count > 0)
                {
                    foreach (BsModels.RightDicNew sub2 in Level2)
                    {
                        result += "{title: '" + sub2.Name + "', id: '" + sub2.Id + "', spread: false, children: [";
                        List<BsModels.RightDicNew> Level3 = list.Where(m => m.RightLevel == 3 && m.Id.StartsWith(sub2.Id)).ToList();
                        if (Level3.Count > 0)
                        {
                            foreach (BsModels.RightDicNew sub3 in Level3)
                            {
                                result += "{title: '" + sub3.Name + "', id: '" + sub3.Id + "', spread: false, children: [";
                                string rightString = ForOperateRight(sub3.Id);
                                if (!string.IsNullOrEmpty(rightString))
                                {
                                    result += rightString;
                                }
                                else
                                {
                                    result += "{title: '基本权限', id: '" + sub3.Id + "_base'}";
                                }
                                result += "]},";
                            }
                            result = result.TrimEnd(',');
                        }
                        else
                        {
                            string rightString = ForOperateRightNew(sub2.Id);
                            if (!string.IsNullOrEmpty(rightString))
                            {
                                result += rightString;
                            }
                            else
                            {
                                result += "{title: '基本权限', id: '" + sub2.Id + "_base'}";
                            }
                        }
                        result += "]},";
                    }
                    result = result.TrimEnd(',');
                }
                else
                {
                    result += ForOperateRightNew(sub1.Id);
                    string rightString = ForOperateRightNew(sub1.Id);
                    if (!string.IsNullOrEmpty(rightString))
                    {
                        result += rightString;
                    }
                    else
                    {
                        result += "{title: '基本权限', id: '" + sub1.Id + "_base'}";
                    }
                }
                result += "]},";
            }
            result = result.TrimEnd(',');
            result += "]";
            return result;
        }
        //读取当前菜单有哪些权限
        public string ForOperateRightNew(string Id)
        {
            string result = "";
            List<BsModels.MenuRightNew> rights = bsdb.MenuRightNew.Where(m => m.MenuId.StartsWith(Id)).OrderBy(m => m.MenuId).ToList();
            foreach (BsModels.MenuRightNew right in rights)
            {
                result += "{title: '" + right.Name + "', id: '" + right.MenuId + "'},";
            }
            BsModels.RightDicNew rightDic = bsdb.RightDicNew.FirstOrDefault(m => m.Id == Id) ?? new BsModels.RightDicNew();
            if (!string.IsNullOrEmpty(rightDic.OtherRight))
            {
                string[] OtherRightList = rightDic.OtherRight.Split('\n');
                foreach (string SubOtherRight in OtherRightList)
                {
                    string[] SubOtherRightData = SubOtherRight.Split('_');
                    result += "{title: '" + SubOtherRightData[1] + "', id: '" + Id + "_" + SubOtherRightData[0] + "'},";
                }
            }
            result = result.TrimEnd(',');
            return result;
        }
        public string TranslateRightString(string RightString)
        {
            string result = "";
            if (!string.IsNullOrEmpty(RightString))
            {
                string[] RightList = RightString.Split(',');
                foreach (string sub in RightList)
                {
                    string EndString = sub.Substring(sub.LastIndexOf("_") + 1);
                    if (EndString.Length > 1 && !function.IsInt(EndString))
                    {
                        result += sub + ",";
                    }
                }
            }
            return result.TrimEnd(',');
        }

        #endregion

        #region 中译英

        public string TranslateZHToEn(string Source)
        {
            string result = function.GetWebRequest("http://fanyi.youdao.com/translate?&doctype=json&type=ZH_CN2EN&i=" + Source);
            //{"type":"ZH_CN2EN","errorCode":0,"elapsedTime":2,"translateResult":[[{"src":"大事件","tgt":"The big event"}]]}
            Match match = Regex.Match(result, "\"tgt\":\".*?\"");
            if (match.Success)
            {
                return match.Value.Replace("\"tgt\":", "").Trim('"');
            }
            return "";
        }

        #endregion

        #region 解析编辑器里的视频代码
        public string CheckMediaFromHtml(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return "";
            }
            string result = content;
            MatchCollection mc = Regex.Matches(content, "<embed.*?/>");
            foreach (Match submc in mc)
            {
                string info = submc.Value;
                Match match = Regex.Match(info, "src=\".*?\"");
                if (match.Success)
                {
                    string path = match.Value;
                    path = path.Replace("src=\"", "");
                    path = path.TrimEnd(new char[] { '"' });
                    string html = "";
                    string width = "600";
                    string height = "300";
                    Match width_match = Regex.Match(info, "width=\".*?\"");
                    if (width_match.Success)
                    {
                        width = width_match.Value.Replace("width=", "").Trim('"');
                    }
                    Match height_match = Regex.Match(info, "height=\".*?\"");
                    if (height_match.Success)
                    {
                        height = height_match.Value.Replace("height=", "").Trim('"');
                    }
                    if (path.EndsWith(".mp4"))
                    {
                        if (string.IsNullOrEmpty(html))
                        {
                            html = "<video controls=\"controls\" autoplay=\"autoplay\" poster=\"\" onplay=\"true\" width=\"" + width + "\" height=\"" + height + "\" onclick=\"this.play();\">" +
                                                "<source src=\"" + path + "\">" +
                                                "<source src=\"" + path + "\" type=\"video/mp4\">" +
                                                "<source src=\"" + path + "\" type=\"video/webm\">" +
                                                "<source src=\"" + path + "\" type=\"video/ogg\">" +
                                            "</video>";
                        }
                    }
                    else if (path.EndsWith(".mp3"))
                    {
                        html = "<audio controls=\"controls\" width=\"" + width + "\" height=\"" + height + "\" onclick=\"this.play();\">" +
                                        "<source src=\"" + path + "\" type=\"audio/mp3\" />" +
                                        "<embed src=\"" + path + "\" height=\"100\" width=\"100\" />" +
                                    "</audio>";
                    }
                    result = result.Replace(info, html);
                }
            }
            return result;
        }
        #endregion

        #region 对象转Json字符串

        public static string ObjectToJsonString(object obj)
        {
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }

        #endregion

        #region Json字符串转对象

        public static T DeserializeJSON<T>(string json)
        {
            return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
        }

        #endregion

        #region 删除文件

        public static bool DeleteFile(string VirtualPath)
        {
            string FilePath = function.getPath(VirtualPath);
            if (System.IO.File.Exists(FilePath))
            {
                System.IO.File.Delete(FilePath);
                return true;
            }
            return false;
        }

        #endregion

        #region 两点距离

        public static double GetDistanceNumber(string start, string end)
        {
            if (!string.IsNullOrEmpty(start) && !string.IsNullOrEmpty(end))
            {
                string[] startpos = start.Split(',');
                string[] endpos = end.Split(',');
                double lng1 = double.Parse(startpos[0]);
                double lat1 = double.Parse(startpos[1]);
                double lng2 = double.Parse(endpos[0]);
                double lat2 = double.Parse(endpos[1]);
                double radLat1 = rad(lat1);
                double radLat2 = rad(lat2);
                double a = radLat1 - radLat2;
                double b = rad(lng1) - rad(lng2);
                double s = 2 * Math.Asin(Math.Sqrt(Math.Pow(Math.Sin(a / 2), 2) + Math.Cos(radLat1) * Math.Cos(radLat2) * Math.Pow(Math.Sin(b / 2), 2)));
                s = s * EARTH_RADIUS;
                s = Math.Round(s * 10000) / 10000;
                return s;
            }
            return 10000000;
        }
        private static double rad(double d)
        {
            return d * Math.PI / 180.0;
        }
        private static double EARTH_RADIUS = 6378.137;

        #endregion

        #region 短信条数

        public int SMSCount()
        {
            SystemSet check = db.SystemSet.FirstOrDefault() ?? new SystemSet();
            return check.QueryCount;
        }

        #endregion

        #region 短信消耗

        public void UseSMS()
        {
            SystemSet check = db.SystemSet.FirstOrDefault();
            if (check != null)
            {
                check.QueryCount -= 1;
                db.SaveChanges();
            }
        }

        #endregion

        #region 获取OSS开关
        public string GetOssStatus()
        {
            SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet();
            return set.UploadOss == 1 ? "-oss" : "";
        }
        #endregion

        #region 获取上传文件参数
        public string GetUploadParam(string buttonId)
        {
            string tag = function.MD5_16(buttonId);
            string param = RedisDbconn.Instance.Get<string>("btn:" + tag);
            if (!string.IsNullOrEmpty(param))
            {
                return param;
            }
            SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet();
            return "{width:" + set.UploadAutoZoomWidth + ",height:" + set.UploadAutoZoomHeight + ",quality:" + set.UploadAutoZoomQuality + "},{max_file_size:" + set.UploadMaxSize + "}";
        }
        #endregion

        #region 获取上传文件提示文字
        public string GetUploadHint(string buttonId, bool ispic = true)
        {
            string tag = function.MD5_16(buttonId);
            string param = RedisDbconn.Instance.Get<string>("btn:" + tag);
            if (string.IsNullOrEmpty(param))
            {
                SystemSet set = db.SystemSet.FirstOrDefault() ?? new SystemSet();
                param = "{width:" + set.UploadAutoZoomWidth + ",height:" + set.UploadAutoZoomHeight + ",quality:" + set.UploadAutoZoomQuality + "},{max_file_size:" + set.UploadMaxSize + "}";
            }
            string[] json = param.Replace(" ", "").Replace("},{", "}#cut#{").Split(new string[] { "#cut#" }, StringSplitOptions.None);
            Dictionary<string, string> resize = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(json[0]);
            Dictionary<string, string> size = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(json[1]);
            int max_file_size = int.Parse(size["max_file_size"]) / 1024;
            string unit = "KB";
            if (max_file_size / 1024 > 0)
            {
                max_file_size = max_file_size / 1024;
                unit = "MB";
            }
            if (max_file_size / 1024 > 0)
            {
                max_file_size = max_file_size / 1024;
                unit = "GB";
            }
            if (ispic)
            {
                return "建议尺寸" + resize["width"] + "x" + resize["height"] + "," + max_file_size + unit + "以内";
            }
            return "建议" + max_file_size + "以内";
        }
        #endregion

        #region 通过表名、文本、值获得字典数据

        public Dictionary<string, string> GetDictionaryByTableName(string tableEnName, string Text, string Value)
        {
            Text = Text.Split('_')[0];
            Value = Value.Split('_')[0];
            Dictionary<string, string> dic = new Dictionary<string, string>();
            DataTable dt = dbconn.dtable("select " + Text + "," + Value + " from " + tableEnName + " order by Sort desc,Id asc");
            foreach (DataRow dr in dt.Rows)
            {
                dic.Add(dr[1].ToString(), dr[0].ToString());
            }
            return dic;
        }

        #endregion

        #region 获取Excel文件内容
        public DataTable ExcelToDataTable(string filepath)
        {
            List<string> result = new List<string>();
            DataTable dtTable = new DataTable();
            List<string> rowList = new List<string>();
            try
            {
                ISheet sheet;
                using (var stream = new FileStream(filepath, FileMode.Open))
                {
                    stream.Position = 0;
                    XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream);
                    sheet = xssWorkbook.GetSheetAt(0);
                    IRow headerRow = sheet.GetRow(0);
                    int cellCount = headerRow.LastCellNum;
                    for (int j = 0; j < cellCount; j++)
                    {
                        ICell cell = headerRow.GetCell(j);
                        if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
                        {
                            dtTable.Columns.Add(cell.ToString());
                        }
                    }
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue;
                        if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            string cellVal = "";
                            if (row.GetCell(j) != null)
                            {
                                cellVal = row.GetCell(j).ToString();
                            }
                            rowList.Add(cellVal);
                        }
                        if (rowList.Count > 0)
                            dtTable.Rows.Add(rowList.ToArray());
                        rowList.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\r\n" + ex.ToString(), "获取Excel文件内容异常");
            }
            return dtTable;
        }
        #endregion

        #region 重置创客机具数量

        public static void SycnMachineCount(int Id = 0, int BrandId = 0)
        {
            RedisDbconn.Instance.AddList("SycnUserMachineCountQueue", "{\"UserId\":\"" + Id + "\",\"BrandId\":\"" + BrandId + "\"}");
        }

        #endregion

        #region 统计机具绑定数据

        public static void StatUserMachineData(int UserId, int BrandId, int Count)
        {
            using (WebCMSEntities db = new WebCMSEntities())
            {
                string IdBrand = UserId + "_" + BrandId;
                UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
                if (MachineData == null)
                {
                    MachineData = db.UserMachineData.Add(new UserMachineData()
                    {
                        IdBrand = IdBrand,
                    }).Entity;
                    db.SaveChanges();
                }
                if (Count < 0)
                {
                    MachineData.TotalMachineCount -= Math.Abs(Count);
                    MachineData.UnBindCount -= Math.Abs(Count);
                }
                else
                {
                    MachineData.TotalMachineCount += Count;
                    MachineData.UnBindCount += Count;
                }
                db.SaveChanges();
            }
        }

        #endregion

        #region 退回仓库，清除历史记录

        public static void ClearPosHistory(WebCMSEntities db, string PosSn)
        {
            PreSendStockDetail prepos = db.PreSendStockDetail.FirstOrDefault(m => m.SnNo == PosSn && m.Status == 1);
            if (prepos != null)
            {
                prepos.Status = -1;
                prepos.ApplyFlag = 0;
                SmallStoreHouse sstore = db.SmallStoreHouse.FirstOrDefault(m => m.UserId == prepos.ToUserId);
                if (sstore != null)
                {
                    sstore.LaveNum += 1;
                    sstore.TotalNum -= 1;
                }
                StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.UserId == prepos.FromStoreId);
                if (store != null)
                {
                    store.LaveNum += 1;
                }
            }
            MachineApply apply = db.MachineApply.FirstOrDefault(m => m.SwapSnExpand.Contains(PosSn));
            if (apply != null)
            {
                apply.SwapSnExpand = apply.SwapSnExpand.Replace(PosSn, PosSn.Substring(0, 3) + "d" + PosSn.Substring(4));
            }

        }

        #endregion



        #region 测试创客Id

        public static int[] testids = { };

        #endregion

        #region 数据库结构
        public static Dictionary<string, Dictionary<string, string>> MainTables = new Dictionary<string, Dictionary<string, string>>();
        public static Dictionary<string, Dictionary<string, string>> CashTables = new Dictionary<string, Dictionary<string, string>>();
        public static Dictionary<string, Dictionary<string, string>> BsTables = new Dictionary<string, Dictionary<string, string>>();
        public static Dictionary<string, Dictionary<string, string>> JobTables = new Dictionary<string, Dictionary<string, string>>();
        public static Dictionary<string, Dictionary<string, string>> SpTables = new Dictionary<string, Dictionary<string, string>>();
        public static Dictionary<string, Dictionary<string, string>> OpTables = new Dictionary<string, Dictionary<string, string>>();//运营中心数据模型

        #endregion


        #region 发送分表数据

        public static void SplitTradeRecord(TradeRecord obj, string TradeMonth = "")
        {
            if (string.IsNullOrEmpty(TradeMonth))
            {
                TradeMonth = DateTime.Now.ToString("yyyyMM");
            }
            RedisDbconn.Instance.AddList("AddTradeRecordQueue", Newtonsoft.Json.JsonConvert.SerializeObject(obj) + "#cut#" + TradeMonth);
        }

        public static void SplitUserAccountRecord(UserAccountRecord obj, string TradeMonth = "")
        {
            if (string.IsNullOrEmpty(TradeMonth))
            {
                TradeMonth = DateTime.Now.ToString("yyyyMM");
            }
            RedisDbconn.Instance.AddList("AddUserAccountRecordQueue", Newtonsoft.Json.JsonConvert.SerializeObject(obj) + "#cut#" + TradeMonth);
        }

        #endregion


        #region 设置押金添加记录公共方法
        public static void MerchantDepositSet(int BrandId, int UserId, int SnId, string SnNo, int BeforeDeposit, decimal DepositAmount, string ReturnNote)
        {
            try
            {
                WebCMSEntities maindb = new WebCMSEntities();
                MerchantDepositSet query = maindb.MerchantDepositSet.Add(new MerchantDepositSet()
                {
                    CreateDate = DateTime.Now, //创建时间
                    Sort = BrandId,//品牌
                    SeoTitle = BeforeDeposit.ToString(),//变更前押金
                    DepositAmount = DepositAmount,//押金
                    ReturnNote = ReturnNote,//返回信息
                    SnNo = SnNo,//机具Sn
                    UserId = UserId,//创客Id
                }).Entity;
                maindb.SaveChanges();

            }
            catch (Exception ex)
            {

                function.WriteLog(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + ex.ToString(), "设置押金队列异常");
            }
        }
        #endregion

    }
}
