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 DFExtractService dfExtractService;
        private readonly HospitalService hospitalService;
        private readonly WebapiUrl url;
        private readonly ILogger<ExtractController> logger;
        private readonly IHostingEnvironment evn;
        public ExtractController(ExtractService extractService,
            NewExtractService newExtractService,
            DFExtractService dfExtractService,
            HospitalService hospitalService,
            IOptions<WebapiUrl> url,
            ILogger<ExtractController> logger,
            IHostingEnvironment evn)
        {
            this.extractService = extractService;
            this.newExtractService = newExtractService;
            this.dfExtractService = dfExtractService;
            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([FromForm] IFormCollection form, int allotId, int hospitalId, string email)
        {
            logger.LogInformation("提取绩效数据请求参数：" + JsonHelper.Serialize(new { allotId, hospitalId, email }));
            if (allotId == 0 || hospitalId == 0)
                return;

            var path = string.Empty;
            #region 保存历史绩效文件
            var file = ((FormFileCollection)form.Files).FirstOrDefault();
            if (file == null)
                logger.LogInformation($"文件为空！");
            else
            {
                var dpath = Path.Combine(evn.ContentRootPath, "Files", "HospitalAllot", $"{hospitalId}");
                FileHelper.CreateDirectory(dpath);

                path = Path.Combine(dpath, FileHelper.GetFileName(file.FileName));
                logger.LogInformation($"保存历史绩效文件保存路径：" + path);

                using (var stream = file.OpenReadStream())
                {
                    byte[] bytes = new byte[stream.Length];
                    stream.Read(bytes, 0, bytes.Length);
                    if (!FileHelper.CreateFile(path, bytes))
                    {
                        logger.LogInformation($"保存历史绩效文件保存失败");
                    }
                }
            }
            #endregion

            //string filePath = newExtractService.ExtractData(allotId, request.Email, hospitalId);
            string filePath = dfExtractService.ExtractData(allotId, email, hospitalId, path); //抽取

            if (!string.IsNullOrEmpty(path) && FileHelper.IsExistFile(path))
                FileHelper.DeleteFile(path);

            #region 保存文件到网站下

            if (!string.IsNullOrEmpty(filePath) && FileHelper.IsExistFile(filePath))
            {
                logger.LogInformation("请求路径：" + url.ImportFile + ",请求参数" + JsonHelper.Serialize(new { allotId, hospitalId }));
                int i = 1;
                while (i <= 5)
                {
                    if (i == 5)
                        logger.LogInformation($"保存文件失败，已尝试执行五次，请联系开发人员！");
                    else
                        logger.LogInformation($"正在尝试第{i}次保存！");

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

            #endregion
        }
        #endregion

    }
}