using FluentValidation.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Internal;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.Infrastructure;
using Performance.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Performance.Extract.Api.Controllers
{
    [Route("api/[controller]")]
    public class ExtractController : Controller
    {
        private readonly ExtractService extractService;
        private readonly NewExtractService newExtractService;
        private readonly HospitalService hospitalService;
        private readonly WebapiUrl url;
        private readonly ILogger<ExtractController> logger;
        private readonly IHostingEnvironment evn;
        public ExtractController(ExtractService extractService,
            NewExtractService newExtractService,
            HospitalService hospitalService,
            IOptions<WebapiUrl> url,
            ILogger<ExtractController> logger,
            IHostingEnvironment evn)
        {
            this.extractService = extractService;
            this.newExtractService = newExtractService;
            this.hospitalService = hospitalService;
            this.url = url.Value;
            this.logger = logger;
            this.evn = evn;
        }

        /// <summary>
        /// 保存首次文件
        /// </summary>
        /// <param name="form"></param>
        /// <param name="type">1、历史绩效文件  2、首次模板文件</param>
        /// <param name="hospitalId"></param>
        /// <returns></returns>
        [Route("import")]
        [HttpPost]
        public ApiResponse Import([FromForm] IFormCollection form, int type, int hospitalId, int year, int month)
        {
            var file = ((FormFileCollection)form.Files).FirstOrDefault();
            if (file == null)
                return new ApiResponse(ResponseType.Error, "上传文件无效");

            var dpath = Path.Combine(evn.ContentRootPath, "Files", $"{hospitalId}", "first");
            if (type == 1)
                dpath = Path.Combine(evn.ContentRootPath, "Files", $"{hospitalId}", $"{year}{month.ToString().PadLeft(2, '0')}");
            FileHelper.CreateDirectory(dpath);

            var path = Path.Combine(dpath, FileHelper.GetFileName(file.FileName));

            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.Error, "保存失败");
            }
            if (!string.IsNullOrEmpty(path) && FileHelper.IsExistFile(path))
                return new ApiResponse(ResponseType.OK, path);
            else
                return new ApiResponse(ResponseType.Error, "获取首次文件失败！");
        }

        /// <summary>
        /// 提取数据
        /// </summary>
        /// <param name="request"></param>
        [HttpPost]
        [Route("index")]
        public void Index([FromBody]AllotRequest request)
        {
            var token = Guid.NewGuid().ToString("N");
            logger.LogInformation(token + ",开始提取数据，请求参数：" + JsonHelper.Serialize(request));
            var hospital = hospitalService.GetHopital(request.HospitalId.Value);
            var filepath = extractService.ExtractData(request.ID, request.Mail, hospital, request.Path);
            if (!string.IsNullOrEmpty(filepath) && FileHelper.IsExistFile(filepath))
            {
                int i = 1;
                while (i <= 5)
                {
                    string retJson = HttpHelper.HttpClient(url.ImportFile + $"?allotId={request.ID}&hospitalId={hospital.ID}", filepath);

                    logger.LogInformation(retJson);
                    var ret = JsonHelper.Deserialize<ApiResponse>(retJson);
                    if ((int)ret.State == 1)
                        break;
                    i++;
                }
            }
            logger.LogInformation(token + ",提取结束，请求参数：" + JsonHelper.Serialize(request));
        }

        #region 新版提取

        /// <summary>
        /// 提取绩效数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("extract")]
        [HttpPost]
        public void ExtractData([CustomizeValidator, FromBody]ExtractRequest request)
        {
            LogHelper.Information("请求参数：" + JsonHelper.Serialize(request), "提取绩效数据");
            string filePath = newExtractService.ExtractData(request.AllotId, request.Email, request.HospitalId);
            if (!string.IsNullOrEmpty(filePath) && FileHelper.IsExistFile(filePath))
            {
                LogHelper.Information("请求路径：" + url.ImportFile + ",请求参数" + JsonHelper.Serialize(new { allotId = request.AllotId, hospitalId = request.HospitalId }), "保存提取文件");
                int i = 1;
                while (i <= 5)
                {
                    if (i == 5)
                        LogHelper.Information($"保存文件失败，已尝试执行五次，请联系开发人员！", "保存提取文件");
                    else
                        LogHelper.Information($"正在尝试第{i}次保存！", "保存提取文件");

                    //保存文件
                    string retJson = HttpHelper.HttpClient(url.ImportFile + $"?allotId={request.AllotId}&hospitalId={request.HospitalId}", filePath);
                    LogHelper.Information("返回结果：" + JsonHelper.Serialize(retJson), "保存提取文件");
                    logger.LogInformation(retJson);
                    var ret = JsonHelper.Deserialize<ApiResponse>(retJson);
                    if (ret != null && (int)ret.State == 1)
                    {
                        LogHelper.Information("保存成功！", "保存提取文件");
                        break;
                    }
                    i++;
                }
            }
            else
                LogHelper.Information($"提取文件不存在！", "保存提取文件");
        }
        #endregion

    }
}