using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text.RegularExpressions;
using Library;
using System.IO;
using System.Web;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using Aop.Api.Util;

namespace MySystem
{
    public class PublicFunction
    {

        #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 获取OSS开关
        public string GetOssStatus()
        { 
            return "-oss";
        }
        #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 接口通用DES解密

        public static string DesDecrypt(string content)
        {
            content = HttpUtility.UrlDecode(content);
            return dbconn.DesDecrypt(content, "*ga34|^7");
        }

        #endregion

        #region 获取jwt的token
        public static string AppToken(string username)
        {
            string test = function.get_Random(10);
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtConfig.JwtSecret)), SecurityAlgorithms.HmacSha256);
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Iss, JwtConfig.JwtIss),
                new Claim(JwtRegisteredClaimNames.Aud, test),
                new Claim("Guid", Guid.NewGuid().ToString("D")),
                new Claim(ClaimTypes.Role, "system"),
                new Claim(ClaimTypes.Role, "admin"),
            };
            SecurityToken securityToken = new JwtSecurityToken(
                signingCredentials: securityKey,
                expires: DateTime.Now.AddDays(10),//过期时间
                claims: claims,
                audience: test,
                issuer: username
            );
            RedisDbconn.Instance.Set("utoken:" + username, test);
            RedisDbconn.Instance.SetExpire("utoken:" + username, 3600 * 24 * 10);
            //生成jwt令牌
            return new JwtSecurityTokenHandler().WriteToken(securityToken);
        }
        #endregion
    
    
        public static decimal NumberFormat(decimal number, int floatCount = 2)
        {
            string str = number.ToString();
            if (str.Contains("."))
            {
                string[] list = str.Split('.');
                if (list[1].Length > floatCount)
                {
                    str = list[0] + "." + list[1].Substring(0, floatCount);
                }
            }
            else
            {
                str += ".00";
            }
            return decimal.Parse(str);
        }
    




        #region 获取网络文件内容

        public static string GetNetFileContent(string url)
        {
            string textContent = "";     
            using (var client = new System.Net.WebClient())
            {
                try
                {
                    textContent = client.DownloadString(url); // 通过 DownloadString 方法获取网页内容
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件内容异常");
                }
            }
            return textContent;
        }

        public static byte[] GetNetFileData(string url)
        {
            byte[] textContent = new byte[] { };
            using (var client = new System.Net.WebClient())
            {
                try
                {
                    textContent = client.DownloadData(url); // 通过 DownloadString 方法获取网页内容
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件流异常");
                }
            }
            return textContent;
        }

        public static FileItem GetNetFileItem(string url)
        {
            string fileName = url;
            if(fileName.Contains("/"))
            {
                fileName = fileName.Substring(fileName.LastIndexOf("/") + 1);
            }
            FileItem item = new FileItem(fileName, GetNetFileData(url));
            return item;
        }

        #endregion
    }
}
