using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Models;
using Models.Models.LOGDB;
using Microsoft.Data.SqlClient;
using System.Linq;
using DB_Server;
using static Models.TCPDATA;
using SERVER;
using System.Collections.Generic;
using SERVER.LIB;
using System;
using Models.Models.DEBUGGER_DB;
using COMMON;
using Models.Models;
using System.Text.RegularExpressions;

namespace WebUI.Controllers
{
    /// <summary>
    ///  服务器管理
    /// </summary>
    public class ServerController : BaseController
    {
        //~ServerController()
        //{
        //   LogHelp.Warning($"志祥教的折构函数~");
        //}
        private readonly LOG_DBContext _logdb;
        private readonly HotelServiceContext _db;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        /// <param name="logdb"></param>
        public ServerController(LOG_DBContext logdb, HotelServiceContext db)
        {
            _logdb = logdb;
            _db = db;
        }

        public IActionResult LOGFILENAME(string type = "0", int length = 100, int start = 0, string name = null, string startDate = null, string endDate = null)
        {
            try
            {
                DateTime starttime = DateTime.Parse("2022-03-25 00:00:01");
                DateTime endtime = DateTime.Now;
                if (!DateTime.TryParse(startDate, out starttime) && starttime < ConfigEntity.Instance.STARTTIME)
                    starttime = DateTime.Parse("2022-03-25 00:00:01");
                if (!DateTime.TryParse(endDate, out endtime))
                    endtime = DateTime.Now;
                // 阿里云查询出的mac
                var DATA = new ASLS().GetLogs_(2, @$" * | select * where lower(logfilename) like '%{name.ToLower()}%'{(string.IsNullOrEmpty(type) || type.Trim() == "0" ? string.Empty : " and log_type = " + type.Trim() + "")} {" and createdatetime >= '" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "'"} {" and createdatetime < '" + endtime.ToString("yyyy-MM-dd HH:mm:ss")+ "'"} limit 10000").Result.ToArray();
                return Json(DATA);
            }
            catch (Exception ex)
            {
                LogHelp.Error(ex.ToString());
                return Json(null);
            }
        }

        /// <summary>
        /// UDP通讯日志
        /// </summary>
        /// <returns></returns>
        public IActionResult UDPLOG()
        {
            return View();
        }

        /// <summary>
        /// UDP通讯统计
        /// </summary>
        /// <returns></returns>
        public IActionResult UDPINFO()
        {
            return View();
        }

        /// <summary>
        /// Rucs服务管理
        /// </summary>
        /// <returns></returns>
        public IActionResult RUCS()
        {
            return View();
        }


        /// <summary>
        /// 获取调试LOG数据 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RUCS_Log()
        {
            return View(XC_Redis.Redis.GetKey<List<PARAs_Class>>("RUCS_DEBUGLOG") ?? new List<PARAs_Class>());
        }

        #region TBL_RUCS_UDP_LOG 分页 

        /// <summary>
        ///  获取TBL_RUCS_UDP_LOG 分页信息 
        /// </summary>
        /// <param name="start"></param>
        /// <param name="endDate"></param>
        /// <param name="startDate"></param>
        /// <param name="length"></param>
        /// <param name="draw"></param>
        /// <param name="DESTINATION"></param>
        /// <param name="DATA_VALID"></param>
        /// <param name="SOURCE_PORT"></param>
        /// <param name="SOURCE_IP"></param>
        /// <param name="DIRECTION"></param>
        /// <param name="DESTINATION_PORT"></param>
        /// <param name="CONTENT_DECRYPT"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetUDPLog(
            int start,
            string endDate = "",
            string startDate = "",
            int length = 15,
            int draw = 1,
            string DESTINATION = "",
            string DATA_VALID = "",
            string SOURCE_PORT = "",
            string SOURCE_IP = "",
            string DIRECTION = "",
            string DESTINATION_PORT = "",
            string CONTENT_DECRYPT = ""

            )
        {
            DateTime starttime = DateTime.Parse("2022-03-25 00:00:01");
            DateTime endtime = DateTime.Now;
            if (!DateTime.TryParse(startDate, out starttime) && starttime < ConfigEntity.Instance.STARTTIME)
                starttime = DateTime.Parse("2022-03-25 00:00:01");

            if (!DateTime.TryParse(endDate, out endtime))
                endtime = DateTime.Now;

            int count = CacheData.UDPcount, filtcount = 0;

            string sql = $@"{(string.IsNullOrEmpty(DESTINATION) ? string.Empty : " and destination like '%" + DESTINATION + "%'")}{" and datetime < '" + endtime.ToString("yyyy-MM-dd HH:mm:ss") + "'"}{" and datetime >= '" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "'"}{(string.IsNullOrEmpty(CONTENT_DECRYPT) ? string.Empty : " and udp_cmd = '" + CONTENT_DECRYPT + " 0'")}{(string.IsNullOrEmpty(DESTINATION_PORT) ? string.Empty : " and destination_port = " + DESTINATION_PORT)}{(string.IsNullOrEmpty(DATA_VALID) ? string.Empty : " and data_valid = " + DATA_VALID)}{(string.IsNullOrEmpty(DIRECTION) ? string.Empty : " and direction = '" + DIRECTION + "'")}{(string.IsNullOrEmpty(SOURCE_PORT) ? string.Empty : " and source_port = " + SOURCE_PORT)}{(string.IsNullOrEmpty(SOURCE_IP) ? string.Empty : " and source_ip like '%" + SOURCE_IP + "%'")}";
            filtcount = int.Parse(new ASLS().GetLogs_(0, @$"* | select COUNT(*) sum where  1 = 1{sql}", starttime.AddHours(-1), endtime.AddHours(1)).Result[0]["sum"]);


            var DATE_WHERE = "";
            int _start = start;

            while (_start + length >= 100000)
            {
                var S = new ASLS().GetLogs_(0, @$"* | select datetime where 1 = 1 {(DATE_WHERE == "" ? "" : "AND datetime > '" + DATE_WHERE + "'")} {sql}  order by datetime LIMIT {(_start > 99999 ? "99999" : _start)},1", starttime.AddHours(-1), endtime.AddHours(1)).Result;
                DATE_WHERE = S[0]["datetime"];
                _start -= (_start > 99999 ? 99999 : _start);
                start = 0;
            }
            var new_data = new ASLS().GetLogs_(0, @$"* | select mac,data_valid,udp_id,direction,direction,content_decrypt,direction,source_port,source_ip,datetime,destination,destination_port where 1 = 1 {(DATE_WHERE == "" ? "" : "AND datetime > '" + DATE_WHERE + "'")}  {sql} order by datetime  limit {start},{length}", starttime.AddHours(-1), endtime.AddHours(1)).Result;

            var DATA_ = DicObject<TBL_RUCS_UDP_LOG>.GetList(new_data.ToArray());

            // throw new Exception("分页查询未完成！");
            //    db.GetData<TBL_RUCS_UDP_LOG>(new string[,] {
            //    { "DESTINATION"," like ",string.IsNullOrEmpty(DESTINATION)?"":DESTINATION,"DESTINATION"},
            //    { "DATETIME"," <= ",(string.IsNullOrEmpty(endDate)?"":endDate) ,"endDate"},
            //    { "UDP_CMD"," = ",(string.IsNullOrEmpty(CONTENT_DECRYPT)?"":CONTENT_DECRYPT+" 0") ,"CONTENT_DECRYPT"},
            //    { "DATETIME"," >= ",string.IsNullOrEmpty(startDate)?"":startDate ,"startDate"},
            //    { "DESTINATION_PORT"," like ",  string.IsNullOrEmpty (DESTINATION_PORT)?"":DESTINATION_PORT,"DESTINATION_PORT"  },
            //    { "DATA_VALID"," like ",  (string.IsNullOrEmpty(DATA_VALID)?"":DATA_VALID),"DATA_VALID"  },
            //    { "DIRECTION"," like ",  (string.IsNullOrEmpty(DIRECTION)?"":DIRECTION),"DIRECTION"  },
            //    { "SOURCE_PORT"," like ",  (string.IsNullOrEmpty(SOURCE_PORT)?"":SOURCE_PORT),"SOURCE_PORT"  },
            //    { "SOURCE_IP"," like ",  (string.IsNullOrEmpty(SOURCE_IP)?"":SOURCE_IP),"SOURCE_IP"  },
            //    { "PackageTime"," > ", "2022-05-01","PackageTime"  },
            //}, "TBL_RUCS_UDP_LOG", (start / length) + 1, length, out count, out filtcount, " order by id desc");
            return Json(new
            {
                draw,
                recordsTotal = count,
                recordsFiltered = filtcount,
                data = DATA_
            });
        }
        #endregion TBL_RUCS_UDP_LOG 分页 


        #region  BLV_UdpDebug    数据查询
        /// <summary>
        /// 职业
        /// </summary>
        /// <returns></returns>
        public IActionResult BLV_UdpDebug()
        {
            return View();
        }
        #endregion


        #region  BLV_UdpDebug   分页 
        /// <summary>
        /// BLV_UdpDebug   分页
        /// </summary>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="draw"></param>
        /// <param name="endDate"></param>
        /// <param name="startDate"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetBLV_UdpDebug(
            int start,
            int length = 15,
            int draw = 1,
            string endDate = "",
            string startDate = ""
            )
        {
            DateTime starttime = DateTime.Parse("2022-03-25 00:00:01");
            DateTime endtime = DateTime.Now;
            if (!DateTime.TryParse(startDate, out starttime) && starttime < ConfigEntity.Instance.STARTTIME)
                starttime = DateTime.Parse("2022-03-25 00:00:01");

            if (!DateTime.TryParse(endDate, out endtime))
                endtime = DateTime.Now;
            DbHelperSQL db = new DbHelperSQL(DbHelperSQL.DBSel.DEBUGGER_DB);
            int count = 0, filtcount = 0;

            var new_data = db.GetData<TBL_UDP_DEBUGGER>(new string[,] {
                { "CreateDateTime"," <= ",(string.IsNullOrEmpty(endDate)?"":endDate) ,"endDate"},
                { "CreateDateTime"," >= ",(string.IsNullOrEmpty(startDate)?"":startDate) ,"startDate"},
            }, "TBL_UDP_DEBUGGER", (start / length) + 1, length, out count, out filtcount, " order by id desc", sumhc: 30);

            return Json(new
            {
                draw,
                recordsTotal = count,
                recordsFiltered = filtcount,
                data = new_data
            });
        }
        #endregion


        /// <summary>
        /// 调试信息饼图
        /// </summary>
        /// <returns></returns>
        public IActionResult BLV_UdpDebugImg()
        {
            return View();
        }

        /// <summary>
        /// 事件跟踪信息
        /// </summary>
        /// <returns></returns>
        public IActionResult EVENTLOGGING()
        {
            return View();
        }

        /// <summary>
        /// 事件跟踪信息 分页
        /// </summary>
        /// <returns></returns>
        /// <param name="startDate">查询起始时间</param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="endDate">查询结束时间</param>
        /// <param name="evenid">事件id</param>
        /// <param name="mac">mac地址</param>
        /// <param name="hotelid">巫工酒店id</param>
        /// <param name="roomid">房间</param>
        /// <param name="draw"></param>
        /// <returns></returns>
        public IActionResult EVENTLOGGING_(int start, int length, string startDate = null, string endDate = null, string mac = null, string evenid = "", string hotelid = "", string roomid = "", int draw = 0)
        {
            DateTime starttime = DateTime.Parse("2022-03-25 00:00:01");
            DateTime endtime = DateTime.Now;
            if (!DateTime.TryParse(startDate, out starttime) && starttime < ConfigEntity.Instance.STARTTIME)
                starttime = DateTime.Parse("2022-03-25 00:00:01");
            if (!DateTime.TryParse(endDate, out endtime))
                endtime = DateTime.Now;

            int count = CacheData.UDPcount, filtcount = 0;


            string sql = $@"{(string.IsNullOrEmpty(mac) ? string.Empty : " and mac like '%" + mac + "%'")}{" and create_timemark < '" + endtime.ToString("yyyy-MM-dd HH:mm:ss") + "'"}{" and create_timemark >= '" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "'"}{(string.IsNullOrEmpty(evenid) ? string.Empty : " and evenid = '" + evenid + "'")}{(string.IsNullOrEmpty(hotelid) ? string.Empty : " and hotelid = " + hotelid)}{(string.IsNullOrEmpty(roomid) ? string.Empty : " and roomid = " + roomid)}";

            filtcount = int.Parse(new ASLS().GetLogs_(1, @$"* | select COUNT(*) sum where  1 = 1 {sql}", starttime.AddHours(-1), endtime.AddHours(1)).Result[0]["sum"]);

            var DATE_WHERE = "";
            int _start = start;

            while (_start + length >= 100000)
            {
                var S = new ASLS().GetLogs_(1, @$"* | select create_timemark where 1 = 1 {(DATE_WHERE == "" ? "" : "AND create_timemark > '" + DATE_WHERE + "'")} {sql}  order by create_timemark LIMIT {(_start > 99999 ? "99999" : _start)},1", starttime.AddHours(-1), endtime.AddHours(1)).Result;
                DATE_WHERE = S[0]["create_timemark"];
                _start -= (_start > 99999 ? 99999 : _start);
                start = 0;
            }

            var new_data = new ASLS().GetLogs_(1, @$"* | select mac,data_valid,udp_id,direction,direction,content_decrypt,direction,source_port,source_ip,datetime,destination,destination_port where 1 = 1 {(DATE_WHERE == "" ? "" : "AND datetime > '" + DATE_WHERE + "'")}  {sql} order by datetime  limit {start},{length}", starttime.AddHours(-1), endtime.AddHours(1)).Result;

            var DATA_ = DicObject<TBL_EVENTLOGGING>.GetList(new_data.ToArray());


            return Json(new
            {
                draw,
                recordsTotal = count,
                recordsFiltered = filtcount,
                data = new { }
            });
        }



        /// <summary>
        /// 事件跟踪信息
        /// </summary>
        /// <returns></returns>
        public IActionResult RcuDataLog(string mac = "")
        {
            if (string.IsNullOrEmpty(mac))
            {
                return Content("window.history.back();location.reload();", "application/javascript");
            }
            return View();
        }
        /// <summary>
        /// 查询mac
        /// </summary>
        /// <returns></returns>
        public IActionResult Find_Mac()
        {
            return View();
        }
        /// <summary>
        /// 查询mac 分页
        /// </summary>
        /// <returns></returns>
        /// <param name="startDate">查询起始时间</param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="endDate">查询结束时间</param>
        /// <param name="mac">事件id</param>
        /// <param name="hotelid">巫工酒店id</param>
        /// <param name="draw"></param>
        [HttpPost]
        public IActionResult Find_Mac(int draw = 0, int start = 0, int length = 10, string mac = "", string startDate = null, string endDate = null, string hotelid = "")
        {
            try
            {
                if (string.IsNullOrEmpty(mac))
                    mac = "";
                mac = mac.Replace("34D0", "").Trim();
                DateTime starttime = DateTime.Parse("2022-03-25 00:00:01");
                DateTime endtime = DateTime.Now;
                if (!DateTime.TryParse(startDate, out starttime) && starttime < ConfigEntity.Instance.STARTTIME)
                    starttime = DateTime.Parse("2022-03-25 00:00:01");
                if (!DateTime.TryParse(endDate, out endtime))
                    endtime = DateTime.Now;

                int filtcount = int.Parse(new ASLS().GetLogs_(2, @$"* | select count(distinct mac) sum where lower(mac) like '%{mac.ToLower()}%' {" and createdatetime >= '" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "'"} {" and createdatetime < '" + endtime.ToString("yyyy-MM-dd HH:mm:ss") + $"'"}").Result[0]["sum"]), count = int.Parse(new ASLS().GetLogs_(2, @$"* | select count(distinct mac) sum").Result[0]["sum"]); ;

                // 阿里云查询出的mac
                var DATA = new List<string>();
                DATA = DicObject<TBL_ROOM_BASIC_INFO>.GetList(new ASLS().GetLogs_(2, @$" * | select distinct lower(mac) mac where lower(mac) like '%{mac.ToLower()}%' {" and createdatetime >= '" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "'"} {" and createdatetime < '" + endtime.ToString("yyyy-MM-dd HH:mm:ss") + $"' limit {start},{length}"}").Result.ToArray()).Select(X => string.Join("-", Regex.Split(("34D0" + X.MAC).ToLower(), "(?<=\\G.{2})")).TrimEnd('-')).ToList();

                // 查询权限酒店下的mac
                var macdata =
                    (from val1 in _db.TBL_ROOM_BASIC_INFOS
                     join val2 in _db.TBL_HOTEL_BASIC_INFOS on val1.HOTEL_OLD_ID equals val2.IDOLD
                     where DATA.Contains(val1.MAC.ToLower())
                     select new { mac = val1.MAC.ToUpper(), hotelname = val2.HOTEL_NAME_CN, hotelid = val2.IDOLD, room_number = val1.ROOM_NUMBER, id = val1.ROOM_OLD_ID }).ToList();
                // 这是sls 存在  但是 数据表没有的mac
                DATA = DATA.Where(x => macdata.FirstOrDefault(w => w.mac.ToLower() == x.ToLower()) == null).ToList();
                // 这是sls 存在但是没有酒店的mac
                foreach (var item in DATA)
                {
                    macdata.Add(new { mac = item.ToUpper(), hotelname = "无酒店信息", hotelid = -1, room_number = "无", id = -1 });
                }
                return Json(new
                {
                    draw,
                    recordsTotal = count,
                    recordsFiltered = filtcount,
                    data = macdata
                });
            }
            catch (Exception EX)
            {
                LogHelp.Error(EX.ToString());
                return Json(null);
            }

        }


        /// <summary>
        /// 事件跟踪信息 分页
        /// </summary>
        /// <returns></returns>
        /// <param name="startDate">查询起始时间</param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <param name="endDate">查询结束时间</param>
        /// <param name="mac">mac地址</param>
        /// <param name="hotelid">巫工酒店id</param>
        /// <param name="roomid">房间</param>
        /// <param name="draw"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult RcuDataLog_(int start, int length, string startDate = null, string endDate = null, string mac = null, string hotelid = "", string type = "", string roomid = "", int draw = 0)
        {
            DateTime starttime = DateTime.Parse("2022-03-25 00:00:01");
            DateTime endtime = DateTime.Now;
            if (!DateTime.TryParse(startDate, out starttime) && starttime < ConfigEntity.Instance.STARTTIME)
                starttime = DateTime.Parse("2022-03-25 00:00:01");
            if (!DateTime.TryParse(endDate, out endtime))
                endtime = DateTime.Now;
            int count = CacheData.UDPcount, filtcount = 0;

            string mac_new = string.Empty;
            //mac_new = "'"+string.Join("','",
            //    // MAC 不为 null 并且 长度大于 0
            //    _db.TBL_ROOM_BASIC_INFOS.Where(x => x.MAC != null && x.MAC.Length > 0
            //    // 酒店 未传入时  取房间的值
            //     && ((hotelid.Trim() == "0" && roomid.Trim()!="0" && "" + x.ROOM_OLD_ID == roomid)
            //      ||
            //     // 房间 未传入时  取酒店的值
            //     (roomid.Trim() == "0" && hotelid.Trim() != "0" && "" + x.HOTEL_OLD_ID == hotelid)
            //     || 
            //     //  取房间 取酒店的值
            //     ("" + x.HOTEL_OLD_ID == hotelid &&  "" + x.ROOM_OLD_ID == roomid)
            //     )).Select(x => x.MAC))+ "'"; 

            string sql = $@"{(string.IsNullOrEmpty(mac) ? string.Empty : " and lower(mac) = '" + mac.ToStringMac() + "'")}{" and createdatetime >= '" + starttime.ToString("yyyy-MM-dd HH:mm:ss") + "'"}{" and createdatetime < '" + endtime.ToString("yyyy-MM-dd HH:mm:ss") + "'"} {(string.IsNullOrEmpty(type) || type.Trim() == "0" ? string.Empty : " and log_type = " + type.Trim() + "")}{(mac_new.Length <= 2 ? "" : $" and mac in ({mac_new})")} ";

            filtcount = int.Parse(new ASLS().GetLogs_(2, @$"* | select count(distinct logfilename) sum where  1 = 1 {sql}", starttime.AddHours(-1), endtime.AddHours(1)).Result[0]["sum"]);

            var DATE_WHERE = "";

            int _start = start;

            //  这快代码待验证 错误 
            while (_start + length >= 100000)
            {
                var S = new ASLS().GetLogs_(2, @$"* | select createdatetime where 1 = 1 {(DATE_WHERE == "" ? "" : "AND createdatetime > '" + DATE_WHERE + "'")} {sql}  order by createdatetime LIMIT {(_start > 99999 ? "99999" : _start)},1", starttime.AddHours(-1), endtime.AddHours(1)).Result;
                DATE_WHERE = S[0]["createdatetime"];
                _start -= (_start > 99999 ? 99999 : _start);
                start = 0;
            }

            var new_data = new ASLS().GetLogs_(2, @$"* | select logfilename,COUNT(*) sum where 1 = 1 {(DATE_WHERE == "" ? "" : "AND datetime > '" + DATE_WHERE + "'")}  {sql} group by logfilename order by  '__tag__:__receive_time__' desc  limit {start},{length}", starttime.AddHours(-1), endtime.AddHours(1)).Result;

            var DATA_ = DicObject<LOGFILENAME>.GetList(new_data.ToArray());

            return Json(new
            {
                draw,
                recordsTotal = count,
                recordsFiltered = filtcount,
                data = DATA_
            });

        }


    }

}
