using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Performance.DtoModels;
using Performance.DtoModels.AppSettings;
using Performance.Infrastructure;
using Performance.Services.ExtractExcelService;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Performance.Extract.Api.Controllers
{
    [Route("api/[controller]")]
    public class ExtractController : Controller
    {
        private readonly IHostingEnvironment evn;
        private readonly ILogger logger;
        private readonly WebapiUrl options;
        private readonly ExtractService extractService1;

        public ExtractController(
            IHostingEnvironment evn,
            ILogger<ExtractController> logger,
            IOptions<WebapiUrl> options,
            ExtractService extractService1)
        {
            this.evn = evn;
            this.logger = logger;
            this.options = options.Value;
            this.extractService1 = extractService1;
        }

        #region 新版提取

        /// <summary>
        /// 提取绩效数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [Route("extract")]
        [HttpPost]
        public void ExtractData()
        {
            string json = JsonHelper.Serialize(Request.Form.ToDictionary());
            logger.LogInformation("提取绩效数据请求参数：" + json);

            var request = JsonHelper.Deserialize<ExtractRequest>(json);

            if (request == null || request.AllotId == 0 || request.HospitalId == 0)
                return;

            var path = string.Empty;
            if (Request.Form.Files == null || !Request.Form.Files.Any())
                logger.LogInformation($"文件为空，以模板文件进行数据提取！");
            else
                path = SaveFileAsTemplate(Request.Form.Files[0], request.HospitalId);

            string filePath = extractService1.Main(request.AllotId, request.HospitalId, request.Email, "User" + request.UserId, path);

            logger.LogInformation($"抽取的文件地址: {filePath}");

            if (!string.IsNullOrEmpty(filePath) && FileHelper.IsExistFile(filePath))
                ImportFileAsAllotExtractFile(request.AllotId, request.HospitalId, filePath);
            else
                logger.LogInformation($"保存提取文件提取文件不存在！");
        }

        #endregion 新版提取

        #region 保存历史绩效文件

        private string SaveFileAsTemplate(IFormFile file, int hospitalId)
        {
            var dpath = Path.Combine(evn.ContentRootPath, "Files", "HospitalAllot", $"{hospitalId}");
            FileHelper.CreateDirectory(dpath);

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

            if (!string.IsNullOrEmpty(path) && FileHelper.IsExistFile(path))
                FileHelper.DeleteFile(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($"保存历史绩效文件保存失败");
                else
                    return "";
            }
            return path;
        }

        #endregion 保存历史绩效文件

        #region 保存文件到网站下

        private void ImportFileAsAllotExtractFile(int allotId, int hospitalId, string filePath)
        {
            var http = new RestSharpHelper();
            var importUrl = http.SetUrl(options.ImportFile, "template/savefile");

            var obj = new { allotId, hospitalId };

            string json = JsonHelper.Serialize(obj);
            var parameter = JsonHelper.Deserialize<Dictionary<string, object>>(json);
            var request = http.CreateFileRequest(new string[] { filePath }, parameter);
            int i = 1;
            while (i <= 5)
            {
                logger.LogInformation($"正在尝试第{i}次保存！");

                var response = http.GetResponse(importUrl, request);
                var result = http.GetContent<ApiResponse>(response);
                if (result != null && (int)result.State == 1)
                {
                    logger.LogInformation("保存提取文件保存成功！");
                    return;
                }
                i++;
            }
            logger.LogInformation($"保存文件失败，已尝试执行五次，请联系开发人员！");
        }

        #endregion 保存文件到网站下
    }
}
