using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Performance.DtoModels;
using Performance.EntityModels;
using Performance.Infrastructure;
using Performance.Services;
using Performance.Services.ExtractExcelService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Performance.Api.Controllers
{
    [ApiController]
    [Route("api/{hospitalId}/report/global")]
    public class ReportGlobalController : Controller
    {
        private readonly IWebHostEnvironment env;
        private readonly AllotService allotService;
        private readonly ReportGlobalService reportGlobalService;
        private readonly ClaimService claimService;

        public ReportGlobalController(
            IWebHostEnvironment env,
            AllotService allotService,
            ReportGlobalService reportGlobalService,
            ClaimService claimService
            )
        {
            this.env = env;
            this.allotService = allotService;
            this.reportGlobalService = reportGlobalService;
            this.claimService = claimService;
        }

        /// <summary>
        /// 获取报表配置信息
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiResponse GetAllReportGlobal([FromRoute] int hospitalId)
        {
            //reportGlobalService.CopyPreviousGlobalData(new per_allot
            //{
            //    ID = 101,
            //    HospitalId = 13,
            //    Year = 2020,
            //    Month = 8
            //});

            var result = reportGlobalService.GetReportGlobals(hospitalId);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 添加报表配置
        /// </summary>
        /// <param name="global"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResponse CreateReportGlobal([FromBody] report_global global)
        {
            var result = reportGlobalService.CreateReportGlobal(global);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 修改报表配置
        /// </summary>
        /// <param name="global"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public ApiResponse UpdateReportGlobal([FromBody] report_global global)
        {
            var result = reportGlobalService.UpdateReportGlobal(global);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 删除报表配置
        /// </summary>
        /// <param name="globalId"></param>
        /// <returns></returns>
        [HttpPost("{globalId}")]
        public ApiResponse DeleteReportGlobal([FromRoute] int globalId)
        {
            var result = reportGlobalService.DeleteReportGlobal(globalId);
            return new ApiResponse(ResponseType.OK, result);
        }

        /// <summary>
        /// 上传人员绩效文件
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [Route("import")]
        [HttpPost]
        public ApiResponse Import(int hospitalId, [FromForm] IFormCollection form)
        {
            var file = ((FormFileCollection)form.Files).FirstOrDefault();
            if (file == null)
                return new ApiResponse(ResponseType.Fail, "参数错误", "文件无效");

            if (!ExtractHelper.IsXlsxFile(file.FileName))
                return new ApiResponse(ResponseType.Fail, "文件格式错误", "文件暂只支持xlsx文件");

            var name = FileHelper.GetFileNameNoExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssfff");
            var ext = FileHelper.GetExtension(file.FileName);
            var dpath = Path.Combine(env.ContentRootPath, "Files", $"{hospitalId}", $"ImportDataFiles");
            FileHelper.CreateDirectory(dpath);

            var path = Path.Combine(dpath, $"{name}{ext}");

            using (var stream = file.OpenReadStream())
            {
                byte[] bytes = new byte[stream.Length];
                stream.Read(bytes, 0, bytes.Length);
                if (!FileHelper.CreateFile(path, bytes))
                    return new ApiResponse(ResponseType.Fail, $"{file.FileName}上传失败");
            }
            reportGlobalService.ImportAllotData(hospitalId, path);
            return new ApiResponse(ResponseType.OK);
        }

        #region 人员、科室标签配置

        /// <summary>
        /// 获取人员标签配置
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("ReportPersonTag")]
        [HttpPost]
        public ApiResponse ReportPersonTag(int hospitalId, int allotId)
        {
            if (hospitalId <= 0)
            {
                return new ApiResponse(ResponseType.Fail, "参数错误", "hospitalId无效");
            }
            var relust = reportGlobalService.GetReportPersonTag(hospitalId, allotId);
            return new ApiResponse(ResponseType.OK, relust);
        }

        /// <summary>
        /// 获取人员标签配置
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("GetReportPersonTag")]
        [HttpPost]
        public ApiResponse GetReportPersonTag(int hospitalId, int allotId)
        {
            if (hospitalId <= 0)
            {
                return new ApiResponse(ResponseType.Fail, "参数错误", "hospitalId无效");
            }
            var relust = reportGlobalService.GetReportPersonTag(hospitalId, allotId);
            return new ApiResponse(ResponseType.OK, new 
            {
                relust.handsonTable.ColHeaders,
                relust.handsonTable.Data
            });
        }
        /// <summary>
        /// 下载人员标签配置
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="allotId"></param>
        /// <returns></returns>
        [Route("DownloadReportPersonTag")]
        [HttpPost]
        [AllowAnonymous]
        public ActionResult DownloadReportPersonTag(int hospitalId, int allotId)
        {

            var (result, colHeaders) = reportGlobalService.GetReportPersonTag(hospitalId, allotId);

            var ser = JsonHelper.Serialize(result.Data);
            var rows = JsonHelper.Deserialize<List<Dictionary<string, object>>>(ser);


            var filepath = reportGlobalService.ReportPersonTagDownload(rows, colHeaders, "人员标签");

            var memoryStream = new MemoryStream();
            using (var stream = new FileStream(filepath, FileMode.Open))
            {
                stream.CopyToAsync(memoryStream).Wait();
            }
            memoryStream.Seek(0, SeekOrigin.Begin);
            var provider = new FileExtensionContentTypeProvider();
            FileInfo fileInfo = new FileInfo(filepath);
            var memi = provider.Mappings[".xlsx"];
            return File(memoryStream, memi, Path.GetFileName(fileInfo.Name));
        }

        /// <summary>
        /// 保存人员标签配置
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="allotId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("saveReportPersonTag/{allotId}")]
        [HttpPost]
        public ApiResponse SaveReportPersonTag(int hospitalId, int allotId, [FromBody] SaveCollectData request)
        {
            if (hospitalId <= 0)
            {
                return new ApiResponse(ResponseType.Fail, "参数错误", "hospitalId无效");
            }
            return reportGlobalService.SaveReportPersonTag(hospitalId, allotId, claimService.GetUserId(), request);
        }

        /// <summary>
        /// 获取人员标签配置
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <returns></returns>
        [Route("ReportTag")]
        [HttpPost]
        public ApiResponse ReportTag(int hospitalId)
        {
            if (hospitalId <= 0)
            {
                return new ApiResponse(ResponseType.Fail, "参数错误", "hospitalId无效");
            }
            var relust = reportGlobalService.GetReportTag(hospitalId);
            return new ApiResponse(ResponseType.OK, relust);
        }

        /// <summary>
        /// 保存科室标签配置
        /// </summary>
        /// <param name="hospitalId"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("saveReportTag")]
        [HttpPost]
        public ApiResponse SaveReportTag(int hospitalId, [FromBody] SaveCollectData request)
        {
            if (hospitalId <= 0)
            {
                return new ApiResponse(ResponseType.Fail, "参数错误", "hospitalId无效");
            }
            reportGlobalService.SaveReportTag(hospitalId, request);
            return new ApiResponse(ResponseType.OK);
        }
        #endregion
    }
}
