using APT.Infrastructure.Core;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using APT.Utility;
using APT.BaseData.Domain.Entities.LG;
using APT.BaseData.Domain.ApiModel.LG;
using System;
using APT.BaseData.Domain.Enums;
using System.Threading.Tasks;
using InfluxData.Net.InfluxDb.Models;
using APT.BaseData.Domain.Entities.FM;
using Microsoft.EntityFrameworkCore.Internal;
using System.Linq;
using APT.BaseData.Domain.ApiModel.Platform;
using Microsoft.Extensions.DependencyInjection;
using APT.Infrastructure.Api.Redis;
using APT.Infrastructure.Api;
namespace APT.LG.WebApi.Controllers.Api
{

    #region  Oprate-表单操作日志表
    /// <summary>
    ///  表单操作日志表
    /// </summary>
    [Route("api/LG/LGOperate")]
    public partial class OprateController : AuthorizeApiController<T_LG_OPRATE>
    {
        /// <summary>
        /// 新增日志
        /// </summary>
        /// <param name="filter">新增日志</param>
        /// <returns></returns>
        [HttpPost, Route("Add")]
        public async Task<JsonActionResult<bool>> Add([FromBody] LgOprateModel model)
        {
            //var redisManager = APT.Infrastructure.Api.ServiceLocator.Instance.GetService<RedisManager>();
            //int num = 0;
            //if (CsRedisManager.KeyExists(RedisCacheKey.HardWarePVInfo))
            //{
            //    num = CsRedisManager.StringGet<int>(RedisCacheKey.HardWarePVInfo);
            //}
            //num++;
            //CsRedisManager.StringSet<int>(RedisCacheKey.HardWarePVInfo, num);
            var isLog = LibUtils.ToBoolean(
              ConfigurationManager.AppSettings["isSqlLog"]);
            bool isSuccess = true;
            if (isLog)
            {
                var user = this.GetEntityByRedis<T_FM_USER>(model.UserId, new Guid(model.OrgId));
                if (user == null)
                    throw new Exception("用户不存在");
                var dt = DateTime.Now;
                var points = new Point
                {
                    Name = dt.Year + dt.Month.PadLeft(2, '0'),
                    Timestamp = dt,
                    Tags = new Dictionary<string, object>()
               {
                    { "Id",  Guid.NewGuid().ToString()}
               },
                    Fields = new Dictionary<string, object>()
               {
                             { "FormCode", model.FormCode },
                             { "FormName", model.FormName },
                             { "BtnCode", model.BtnCode??"" },
                             { "BtnName", model.BtnName??"" },
                             { "OrgId", model.OrgId },
                             { "UserId", model.UserId },
                              { "UserCode",user.CODE },
                              { "OperateType",string.IsNullOrEmpty(model.BtnCode)?(int)LGOperateTypeEnum.表单加载:(int)LGOperateTypeEnum.按钮点击 }
               }
                };

                var response = await InfluxDbHelper.InfluxDbClient.Client.WriteAsync(points, InfluxDbHelper.InfluxLogDbName);
                isSuccess = response.Success;
            }

            return SafeExecute<bool>(() =>
         {
             return isSuccess;

         });
        }

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <param name="filter">过滤实体</param>
        /// <returns></returns>
        [HttpPost, Route("LGOrderPaged")]
        public async Task<PagedActionResult<LgOprateModel>> LGOrderPaged([FromBody] KeywordPageFilter filters)
        {
            var actionResult = new PagedActionResult<LgOprateModel>();
            string timestr = filters.Parameter1;
            if (string.IsNullOrEmpty(timestr))
            {
                this.ThrowError("120001");
            }
            //if (string.IsNullOrEmpty(filters.Parameter2))
            //{
            //    this.ThrowError("120002");
            //}
            var timeAry = timestr.Split(new char[] { ',' });
            if (timeAry.Length != 2)
                this.ThrowError("120001");
            var dtStart = DateTime.Parse(timeAry[0]);
            var dtEnd = DateTime.Parse(timeAry[1]);
            T_FM_USER user = null;
            if (!string.IsNullOrEmpty(filters.Keyword))
            {
                user = this.GetEntity<T_FM_USER>(i => i.NAME == filters.Keyword || i.CODE == filters.Keyword, new BaseFilter(filters.OrgId));
                if (user == null)
                    return actionResult;
            }
            List<string> querys = new List<string>();
            List<string> queryCounts = new List<string>();
            for (var x = dtStart; x <= dtEnd; x = x.AddMonths(1))
            {
                var tableName = x.Year + x.Month.PadLeft(2, '0');
                var query = $" FROM \"{tableName}\" WHERE time >= '{dtStart.ToString("yyyy-MM-dd HH:mm:ss")}' and time<='{dtEnd.ToString("yyyy-MM-dd HH:mm:ss")}'";
                if (user != null)
                    query += $" and UserId='{user.ID.ToString()}'";
                //表单
                if (!string.IsNullOrEmpty(filters.Parameter3))
                {
                    query += $" and FormCode='{filters.Parameter3}'";
                }
                var offSet = (filters.PageIndex - 1) * filters.Limit;
                var querySql = query + $" order by time desc limit {filters.Limit} OFFSET {offSet}";
                querySql = "SELECT * " + querySql;
                querys.Add(querySql);
                var queryCount = "SELECT COUNT(OrgId)  " + query;
                queryCounts.Add(queryCount);
            }

            var response = await InfluxDbHelper.InfluxDbClient.Client.MultiQueryAsync(querys, InfluxDbHelper.InfluxLogDbName);
            if (!response.Any())
                return actionResult;
            //得到Serie集合对象（返回执行多个查询的结果）
            //取出第一条命令的查询结果，是一个集合
            List<LgOprateModel> opList = new List<LgOprateModel>();
            //从集合中取出第一条数据
            foreach (var list in response)
            {
                foreach (var table in list)
                {
                    foreach (var item in table.Values)
                    {
                        var point = new LgOprateModel
                        {
                            BtnCode = item[1].ToString(),
                            BtnName = item[2].ToString(),
                            FormCode = item[3].ToString(),
                            FormName = item[4].ToString(),
                            ID = item[5].ToString(),
                            OrgId = item[7].ToString(),
                            UserCode = item[8].ToString(),
                            UserId = item[9].ToString(),
                            Datetime = item[0].ToString(),
                        };
                        opList.Add(point);
                    }


                }
            }
            opList = opList.OrderByDescending(t => t.Datetime).Take(filters.Limit).ToList();
            actionResult.Data = opList;

            var responseCount = await InfluxDbHelper.InfluxDbClient.Client.MultiQueryAsync(queryCounts, InfluxDbHelper.InfluxLogDbName);
            var totalCount = 0;
            foreach (var list in responseCount)
            {
                foreach (var table in list)
                {
                    foreach (var item in table.Values)
                    {
                        totalCount += int.Parse(item[1].ToString());
                    }
                }
            }
            actionResult.TotalCount = totalCount;

            return actionResult;
        }


    }
    #endregion
}

