using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.BsModels;
using Library;

namespace MySystem.Areas.Admin.Controllers
{
    public class BaseController : Controller
    {
        public IHttpContextAccessor _accessor;
        public readonly ILogger<BaseController> _logger;
        public readonly IOptions<Setting> _setting;
        public Setting AppSetting;

        public string ApiKey = "G6H7@J8%";
        public Models.WebCMSEntities db = new Models.WebCMSEntities();
        public BsModels.WebCMSEntities bsdb = new BsModels.WebCMSEntities();
        public SpModels.WebCMSEntities spdb = new SpModels.WebCMSEntities();
        public CashModels.WebCMSEntities cashdb = new CashModels.WebCMSEntities();
        public OpModels.WebCMSEntities opdb = new OpModels.WebCMSEntities();

        public string Host = Library.ConfigurationManager.AppSettings["Host"].ToString();
        public string OpHost = Library.ConfigurationManager.AppSettings["OpHost"].ToString();

        public string ShareHost = "";
        public string SourceHost = OssHelper.Instance.SourceHost;
        public string Database = Library.ConfigurationManager.AppSettings["Database"].ToString();
        public string defaultImage = Library.ConfigurationManager.AppSettings["Host"].ToString() + "/skin/app/default/static/images/default.jpg";

        //jwt参数
        public string JwtSecret = Library.ConfigurationManager.AppSettings["JwtSecret"].ToString();
        public string JwtIss = Library.ConfigurationManager.AppSettings["JwtIss"].ToString();
        public string JwtAud = Library.ConfigurationManager.AppSettings["JwtAud"].ToString();

        //数据库连接字符串
        public string OpConn = Library.ConfigurationManager.AppSettings["OpSqlConnStr"].ToString();
        public string SqlConn = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        
        public int SysId;
        public int SysRealRole;
        public string SysUserName = "";
        public string SysRealName = "";
        public string RightInfo = "";

        public BaseController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting)
        {
            _accessor = accessor;
            _logger = logger;
            _setting = setting;
            AppSetting = setting.Value;
            Host = AppSetting.Host;
            Database = AppSetting.Database;
            if (function.GetSession(_accessor.HttpContext, "IsLogin") != "1")
            {
                function.WriteCookie(_accessor.HttpContext, "SysUserName", "");
                function.WriteCookie(_accessor.HttpContext, "SysRealName", "");
                function.WriteCookie(_accessor.HttpContext, "SysId", "0");
                function.WriteCookie(_accessor.HttpContext, "SysRealRole", "0");
                function.WriteSession(_accessor.HttpContext, "RightInfo", "");
                if (_accessor.HttpContext.Request.Path.Value.ToLower().Contains("admin"))
                {
                    _accessor.HttpContext.Response.WriteAsync("<script>window.top.location.href='/Admin/Home/Login';</script>");
                }
            }
            else
            {
                SysId = int.Parse(function.CheckInt(function.GetCookie(_accessor.HttpContext, "SysId")));
                SysRealRole = int.Parse(function.CheckInt(function.GetCookie(_accessor.HttpContext, "SysRealRole")));
                SysUserName = function.GetCookie(_accessor.HttpContext, "SysUserName");
                SysRealName = function.GetCookie(_accessor.HttpContext, "SysRealName");
                SysAdminRole role = bsdb.SysAdminRole.FirstOrDefault(m => m.Id == SysRealRole);
                if (role != null)
                {
                    RightInfo = role.RightInfo;
                    function.WriteSession(_accessor.HttpContext, "RightInfo", role.RightInfo);
                }
                if (_accessor.HttpContext.Request.Path.Value.ToLower().Contains("admin"))
                {
                    if (!CheckAdminRight())
                    {
                        _accessor.HttpContext.Response.WriteAsync("<script>window.top.location.href='/Admin/Home/Login';</script>");
                    }
                }
            }
            //bsdb.Configuration.ProxyCreationEnabled = false;
        }

        #region 判断权限

        public bool CheckAdminRight()
        {
            string url = _accessor.HttpContext.Request.Path.Value;
            if(url.Contains("/RightDic/")) return true;
            if(url.Contains("/OperateRightList/")) return true;
            if(url.Contains("/PageUpdateInfo/")) return true;
            if(url.Contains("/FileUpdateInfo/")) return true;
            if(url.Contains("/AppBottomNavs/")) return true;
            if(url.Contains("/UploadParams/")) return true;
            if(url.Contains("/SystemSet/")) return true;
            if(url.Contains("Task")) return true;
            if(url.Contains("ProfitObject")) return true;
            if(url.Contains("ExportTable")) return true;
            if (url.Contains("/KqProductBrand/"))
            {
                url = url.Replace("/KqProductBrand/", "/KqProducts/");
            }
            if (url.Contains("/KqProductOrgs/"))
            {
                url = url.Replace("/KqProductOrgs/", "/KqProducts/");
            }
            if (url.Contains("/KqProductRuleSet/"))
            {
                url = url.Replace("/KqProductRuleSet/", "/KqProducts/");
            }
            if (url.Contains("/UserProfit/"))
            {
                url = url.Replace("/UserProfit/", "/Users/");
            }
            if (url.Contains("/Product"))
            {
                url = "/Admin/Products/Index";
            }
            if (url.Contains("/MerchantAddInfo/"))
            {
                url = url.Replace("/MerchantAddInfo/", "/MerchantInfo/");
            }
            if (url.Contains("/MerchantParamSet/"))
            {
                url = url.Replace("/MerchantParamSet/", "/MerchantInfo/");
            }
            if (url.Contains("/PosCouponRecord/"))
            {
                url = url.Replace("/PosCouponRecord/", "/PosCouponOrders/");
            }
            if (url.Contains("/CustomQueryDo/"))
            {
                url = url.Replace("/CustomQueryDo/", "/CustomQuery/");
            }
            if (url.Contains("/CustomQuerySub/"))
            {
                url = url.Replace("/CustomQuerySub/", "/CustomQuery/");
            }
            if (!string.IsNullOrEmpty(url))
            {
                url = url.Substring(0, url.LastIndexOf("/"));
            }
            string[] RightInfo = function.GetSession(_accessor.HttpContext, "RightInfo").Split(',');
            bool check = bsdb.RightDic.Any(m => m.Url.Contains(url) && RightInfo.Contains(m.Id));
            return check;
        }

        #endregion

        #region 通用添加创客迁移数据
        public string AddUserMoveInfo(int UserId = 0, string PayPwd = null, string LoginPwd = null)
        {
            if (UserId > 0)
            {
                var check = db.UserMoveInfo.Any(m => m.UserId == UserId);
                if (check)
                {
                    var info = db.UserMoveInfo.FirstOrDefault(m => m.UserId == UserId) ?? new Models.UserMoveInfo();
                    if (!string.IsNullOrEmpty(PayPwd)) info.PayPwd = PayPwd;
                    if (!string.IsNullOrEmpty(LoginPwd)) info.LoginPwd = LoginPwd;
                }
                else
                {
                    Models.UserMoveInfo query = db.UserMoveInfo.Add(new Models.UserMoveInfo()
                    {
                        UserId = UserId,
                        PayPwd = PayPwd,
                        LoginPwd = LoginPwd
                    }).Entity;
                }
                db.SaveChanges();
            }
            return "成功";
        }

        #endregion

        #region 根据数字获取订单状态名称

        public string getOrderStatus(int status)
        {
            string result = "";
            switch (status)
            {
                case -1:
                    result = "已取消";
                    break;
                case 0:
                    result = "未付款";
                    break;
                case 1:
                    result = "待发货";
                    break;
                case 2:
                    result = "待确认";
                    break;
                case 3:
                    result = "已完成";
                    break;
                case 4:
                    result = "已评价";
                    break;
                case 5:
                    result = "退款中";
                    break;
                case 6:
                    result = "已退款";
                    break;
                default: break;
            }
            return result;
        }

        #endregion

        #region 根据数字获取报名状态名称

        public string getSignUpStatus(int status)
        {
            string result = "";
            switch (status)
            {
                case -1:
                    result = "已取消";
                    break;
                case 0:
                    result = "未付款";
                    break;
                case 1:
                    result = "已付款";
                    break;
                default: break;
            }
            return result;
        }

        #endregion

        #region 根据数字获取创客等级名称

        public string getUserLevel(int level)
        {
            string result = "";
            return result;
        }

        #endregion

        #region 根据数字获取配送方式

        public string getMeterMode(int num)
        {
            string result = "";
            switch (num)
            {
                case 1:
                    result = "快递";
                    break;
                case 2:
                    result = "EMS";
                    break;
                case 3:
                    result = "平邮";
                    break;
                default:
                    break;
            }
            return result;
        }

        #endregion

        #region 根据数字获取文章显示类型

        public string getShowTypeName(int ShowType)
        {
            string result = "";
            switch (ShowType)
            {
                case 2:
                    result = "专题";
                    break;
                case 3:
                    result = "图文(大)";
                    break;
                case 4:
                    result = "文本";
                    break;
                case 5:
                    result = "图集";
                    break;
                case 6:
                    result = "直播";
                    break;
                case 7:
                    result = "视频";
                    break;
                case 8:
                    result = "音频";
                    break;
                case 9:
                    result = "图文(小)";
                    break;
                default: break;
            }
            return result;
        }

        #endregion

        #region 获取文章内链

        public string getLocalUrl(int ShowType, int Id)
        {
            string result = "";
            switch (ShowType)
            {
                case 2:
                    result = "subject?ArticleId=" + Id;
                    break;
                case 5:
                    result = "atlas-detail?ArticleId=" + Id;
                    break;
                case 6:
                    result = "live-detail?ArticleId=" + Id;
                    break;
                case 7:
                    result = "video-detail?ArticleId=" + Id;
                    break;
                default:
                    result = "article-detail?ArticleId=" + Id;
                    break;
            }
            return result;
        }

        #endregion

        #region 获取文章内链

        public string getSchemeUrl(int ShowType, int Id)
        {
            string result = "";
            switch (ShowType)
            {
                case 2:
                    result = "安卓：ggsj://com.ggsj.ggsj?id=subject?ArticleId=" + Id;
                    result += "<br>IOS：ggsj://?id=subject?ArticleId=" + Id;
                    break;
                case 5:
                    result = "安卓：ggsj://com.ggsj.ggsj?id=atlas-detail?ArticleId=" + Id;
                    result += "<br>IOS：ggsj://?id=atlas-detail?ArticleId=" + Id;
                    break;
                case 6:
                    result = "安卓：ggsj://com.ggsj.ggsj?id=live-detail?ArticleId=" + Id;
                    result += "<br>IOS：ggsj://?id=live-detail?ArticleId=" + Id;
                    break;
                case 7:
                    result = "安卓：ggsj://com.ggsj.ggsj?id=video-detail?ArticleId=" + Id;
                    result += "<br>IOS：ggsj://?id=video-detail?ArticleId=" + Id;
                    break;
                default:
                    result = "安卓：ggsj://com.ggsj.ggsj?id=article-detail?ArticleId=" + Id;
                    result += "<br>IOS：ggsj://?id=article-detail?ArticleId=" + Id;
                    break;
            }
            return result;
        }

        #endregion

        #region 两点距离

        public 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 double rad(double d)
        {
            return d * Math.PI / 180.0;
        }
        private double EARTH_RADIUS = 6378.137;

        #endregion
        
        #region 记录后台操作日志

        public void AddSysLog(string Id, string Table, string Operation)
        {
            if (!string.IsNullOrEmpty(Id))
            {
                string[] idlist = Id.Split(new char[] { ',' });
                foreach (string subid in idlist)
                {
                    bsdb.SysLog.Add(new BsModels.SysLog()
                    {
                        CreateDate = DateTime.Now,
                        CreateMan = SysUserName,
                        Contents = SysUserName + "," + Operation + "," + "了" + Table + ",Id:" + subid,
                    });
                }
                bsdb.SaveChanges();
            }
        }

        public void AddSysLog(int Id, string Table, string Operation)
        {
            bsdb.SysLog.Add(new BsModels.SysLog()
            {
                CreateDate = DateTime.Now,
                CreateMan = SysUserName,
                Contents = SysUserName + "," + Operation + "," + "了" + Table + ",Id:" + Id,
            });
            bsdb.SaveChanges();
        }

        #endregion

        #region 接口通用DES解密

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

        #endregion
    }
}