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;

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 统计机具绑定数据

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

        #region 绑定

        public static void BindUserMachineData(Models.Main.WebCMSEntities db, int UserId, int BrandId, int Count, string PosSn)
        {
            //主库
            Models.Main1.WebCMSEntities main1db = new Models.Main1.WebCMSEntities();
            if(BrandId == 1)
            {
                Models.Main1.PosMachines pos = main1db.PosMachines.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachines();
                pos.BindingState = 1;
                pos.BuyUserId = UserId;
                pos.UserId = UserId;
                pos.BindingTime = DateTime.Now;
            }
            else
            {
                Models.Main1.PosMachinesTwo pos = main1db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachinesTwo();
                pos.BindingState = 1;
                pos.BuyUserId = UserId;
                pos.UserId = UserId;
                pos.BindingTime = DateTime.Now;
            }
            string IdBrand = UserId + "_" + BrandId;
            Models.Main.UserMachineData MachineData = db.UserMachineData.FirstOrDefault(m => m.IdBrand == IdBrand);
            if (MachineData == null)
            {
                MachineData = db.UserMachineData.Add(new Models.Main.UserMachineData()
                {
                    IdBrand = IdBrand,
                }).Entity;
                db.SaveChanges();
            }
            MachineData.UnBindCount -= Count;
            MachineData.BindCount += Count;
            db.SaveChanges();
        }

        #endregion

        #region 划拨记录

        public static void SendRecord(Models.Main1.WebCMSEntities db, int UserId, int ToUserId, int StoreId, string[] PosSnList)
        {
            string ChangeRecordNo = "SC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
            for (int i = 0; i < PosSnList.Length; i++)
            {
                string PosSn = PosSnList[i];
                Models.Main1.PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn) ?? new Models.Main1.PosMachinesTwo();
                pos.StoreId = StoreId;
                pos.TransferTime = DateTime.Now;
                pos.BuyUserId = ToUserId;
                pos.UserId = ToUserId;

                db.PosCouponRecord.Add(new Models.Main1.PosCouponRecord()
                {
                    CreateDate = DateTime.Now,
                    OrderNo = ChangeRecordNo,
                    ToUserId = ToUserId,
                    FromUserId = UserId,
                    PosCouponId = pos.Id,
                });
            }
            int SnCount = PosSnList.Length;
            db.PosCouponOrders.Add(new Models.Main1.PosCouponOrders()
            {
                CreateDate = DateTime.Now,
                ChangeCount = SnCount,
                OrderNo = ChangeRecordNo,
                ToUserId = ToUserId,
                FromUserId = UserId,
            });
            db.SaveChanges();
        }

        #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


        #region 获取jwt的token
        public static string AppToken(int UserId, string JwtSecret, string JwtIss, string tag = "")
        {
            return AppToken(UserId.ToString(), JwtSecret, JwtIss, tag);
        }

        public static string AppToken(string UserId, string JwtSecret, string JwtIss, string tag = "")
        {
            string Token = RedisDbconn.Instance.Get<string>("apptoken:" + UserId + tag);
            if (!string.IsNullOrEmpty(Token))
            {
                return Token;
            }
            string issuer = "new_" + UserId + tag;
            string test = function.get_Random(10);
            var securityKey = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(JwtSecret)), SecurityAlgorithms.HmacSha256);
            var claims = new Claim[] {
                new Claim(JwtRegisteredClaimNames.Iss,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: issuer
            );
            RedisDbconn.Instance.Set("utoken:" + issuer, test);
            RedisDbconn.Instance.SetExpire("utoken:" + issuer, 3600 * 24 * 10);
            //生成jwt令牌
            Token = new JwtSecurityTokenHandler().WriteToken(securityToken);
            RedisDbconn.Instance.Set("apptoken:" + UserId + tag, Token);
            RedisDbconn.Instance.SetExpire("apptoken:" + UserId + tag, 3600 * 24 * 10 - 60);
            //生成jwt令牌
            return new JwtSecurityTokenHandler().WriteToken(securityToken);
        }

        #endregion
    }
}
