using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Redis.Model;
using Siger.Middlelayer.Redis.Repositories;
using Siger.Middlelayer.Common.Extensions;
using Siger.ApiCommon.Result;

namespace Siger.ApiConfig.Controller
{
    public class ApiHistoryController : BaseController
    {
        public ApiHistoryController()
        {

        }

        [HttpGet]
        public IActionResult GetHistories(int type, string start, string end, int page = PageIndex, int pagesize = PageSize)
        {
            var entities = GetAllList(type);
            var count = 0;
            if(!string.IsNullOrWhiteSpace(start) && !string.IsNullOrWhiteSpace(end))
            {
                var starttime = start.ToDateTime().Date;
                var endtime = end.ToDateTime().Date.AddDays(1).AddMilliseconds(-1);
                entities = entities.Where(q => q.dateTime >= starttime && q.dateTime <= endtime).ToList();
            }
            count = entities.Count();
            entities = entities.OrderByDescending(q => q.dateTime).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            return new PagedObjectResult(entities, count, page, pagesize);
        }

        private List<ApiHistoryEntity> GetAllList(int type)
        {
            var rep = new ApiCountRepository(CompanyId, ProjectId);
            var list = new List<ApiHistoryEntity>();
            if (type == 1) //成功
            {
                var records = rep.GetSuccessEntities();
                foreach (var record in records)
                {
                    list.Add(new ApiHistoryEntity
                    {
                        url = record.url,
                        time = record.lastupdatetime,
                        count = record.count,
                        dateTime = record.lastupdatetime.ToDateTime()
                    });
                }
            }
            else if (type == 2) //失败
            {
                var records = rep.GetFailedEntities();
                foreach (var record in records)
                {
                    list.Add(new ApiHistoryEntity
                    {
                        url = record.url,
                        time = record.time,
                        count = 1,
                        userid = record.userid.ToStr(),
                        parameter = record.parameter,
                        error = record.error,
                        msg = record.msg,
                        dateTime = record.time.ToDateTime()
                    });
                }
            }
            return list;
        }
    }
}
