using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Performance.DtoModels;
using Performance.Infrastructure;
using Performance.Services;
using Performance.Services.ExtractExcelService;
using System;
using System.IO;
using System.Linq;

namespace Performance.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class HistoryController : ControllerBase
    {
        private readonly HistoryService historyService;
        private readonly ClaimService claim;
        private readonly IWebHostEnvironment evn;
        public HistoryController(
            HistoryService historyService,
            ClaimService claim,
            IWebHostEnvironment evn)
        {
            this.historyService = historyService;
            this.claim = claim;
            this.evn = evn;
        }

        /// <summary>
        /// 上传历史绩效数据
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [Route("import")]
        [HttpPost]
        public ApiResponse Import([FromForm] IFormCollection form)
        {
            var hospitalid = form.ToDictionary().GetValue("hospitalid", 0);
            if (hospitalid <= 0)
                return new ApiResponse(ResponseType.Fail, "参数错误", "hospitalid无效");

            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 = $"History_{FileHelper.GetFileNameNoExtension(file.FileName)}{DateTime.Now:yyyyMMddHHmmssfff}";
            var ext = FileHelper.GetExtension(file.FileName);
            var dpath = Path.Combine(evn.ContentRootPath, "Files", hospitalid.ToString());
            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}上传失败");
            }
            historyService.ImportHistoryData(hospitalid, path);
            return new ApiResponse(ResponseType.OK);
        }
    }
}
