using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.Http;
using FactorySystemBll;
using FactorySystemCommon;
using FactorySystemModel.BusinessModel;
using FactorySystemModel.ResponseModel;
using Newtonsoft.Json.Linq;

namespace FactorySystemApi.Controllers
{
    /// <summary>
    /// 操作日志
    /// </summary>
    [UserLoginFilter]
    public class OperateLogController : ApiController
    {
        private readonly OperateLogBll _operateLogBll = new OperateLogBll();

        /// <summary>
        /// 获取分页
        /// </summary>
        [HttpPost]
        public ApiResult GetPageList(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();

            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = new
                {
                    List = _operateLogBll.GetPageList(inParam, out int totalCount)
                };
            }, apiResult, Request);
        }

        /// <summary>
        /// 获取分页
        /// </summary>
        [HttpPost]
        public ApiResult GetPageListByParams(Dictionary<string, object> inParam)
        {
            var apiResult = new ApiResult();
            int pageNumber = int.Parse(inParam.ContainsKey("current") && !string.IsNullOrEmpty(inParam["current"].ToString()) ? inParam["current"].ToString() : "0");
            int pageSize = int.Parse(inParam.ContainsKey("limit") && !string.IsNullOrEmpty(inParam["limit"].ToString()) ? inParam["limit"].ToString() : "10");
            string FName = inParam.ContainsKey("FName") ? inParam["FName"].ToString() : "";
            int FType = int.Parse(inParam.ContainsKey("FType") && !string.IsNullOrEmpty(inParam["FType"].ToString()) ? inParam["FType"].ToString() : "0");
            int FModule = int.Parse(inParam.ContainsKey("FModule") && !string.IsNullOrEmpty(inParam["FModule"].ToString()) ? inParam["FModule"].ToString() : "0");
            string FDateRangeStr = inParam.ContainsKey("FDateRange") ? inParam["FDateRange"].ToString() : "";
            string dateFrom = null;
            string dateTo = null;

            if (!string.IsNullOrEmpty(FDateRangeStr))
            {
                var dataRange = JArray.Parse(FDateRangeStr);
                dateFrom = dataRange[0].ToString();
                dateTo = dataRange[1].ToString();
            }            

            return ExceptionHelper.TryReturnException(() =>
            {
                apiResult.Data = new
                {
                    //List = _operateLogBll.GetPageList(inParam, out int totalCount),
                    List  = _operateLogBll.GetLogsByPage(FName, FType, FModule, dateFrom, dateTo, pageNumber, pageSize, out var totalNumber),
                    Total = totalNumber
                };
            }, apiResult, Request);
        }

        /// <summary>
        /// 保存操作日志
        /// </summary>
        [HttpPost]
        public ApiResult Save(Dictionary<string, object> inParams)
        {
            var teamId = int.Parse(inParams["teamId"].ToString());
            var type = int.Parse(inParams["type"].ToString());
            var desc = inParams["desc"].ToString();
            var module = inParams.ContainsKey("module") ? int.Parse(inParams["module"].ToString()) : 0;
            var apiResult = new ApiResult();
            return ExceptionHelper.TryReturnException(() =>
            {
                if (Request.Properties["token"] is ApiAuthInfo user)
                {
                    OperateLogBll.Add(module, teamId, type, desc, user.FID);
                }
            }, apiResult, Request);
        }

        /// <summary>
        /// 导出操作日志
        /// </summary>
        [HttpPost]
        public ApiResult DownloadLogs(Dictionary<string, object> inParams)
        {
            ApiResult apiResult = new ApiResult();

            return ExceptionHelper.TryReturnException(() =>
            {
                string basePath = AppDomain.CurrentDomain.BaseDirectory.Trim('\\');
                string savePath = basePath + string.Format("\\File\\Temp\\logs\\");
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

                int limit = inParams.ContainsKey("limit") ? int.Parse(inParams["limit"].ToString()) : 1000;
                if (!Directory.Exists(savePath)) Directory.CreateDirectory(savePath);

                CreateExeclFileLogs(fileName, savePath, limit);
                string url = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, "") + savePath.Replace(basePath, "").Replace("\\", "/") + fileName;
                apiResult.Data = url;

            }, apiResult, Request);
        }

        private void CreateExeclFileLogs(string fName, string savePath, int limit)
        {
            DataTable dataList = new DataTable();

            dataList = OperateLogBll.GetLogs(limit);
            NPOIHelper.ExportDTtoExcel(dataList, "Sheet1", savePath + fName);
        }
    }
}
