using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Net.Http.Headers;
using Nirvana.Common;
using Nirvana.Common.File;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Application;
using YBDevice.Entity;

namespace YBDevice.NWeb.Pages.OutProduct
{
    public class EditModel : BaseModel
    {
        public YB_OutProduct data = new YB_OutProduct();
        public List<YB_DeviceType> types = new List<YB_DeviceType>();
        public List<SelectListItem> outtypes = new List<SelectListItem>();
        public List<SelectListItem> paytypes = new List<SelectListItem>();
        public List<YB_Business> businesslist = new List<YB_Business>();
        public List<YB_ExPress> expresslist = new List<YB_ExPress>();

        private static readonly FormOptions _defaultFormOptions = new FormOptions();
        private readonly IWebHostEnvironment _hostingEnvironment;

        private IDeviceService _deviceService;
        private IBusinessService _businessService;
        private IProductService _productService;
        public EditModel(IWebHostEnvironment hostingEnvironment, IDeviceService deviceService, IBusinessService businessService, IProductService productService)
        {
            _hostingEnvironment = hostingEnvironment;
            _deviceService = deviceService;
            _businessService = businessService;
            _productService = productService;
        }

        public async Task OnGetAsync(int id = 0)
        {
            types = await _deviceService.GetTypeListAsync();
            outtypes = EnumHelper.GetEnumDictionary<OutProductType>().Select(x => new SelectListItem
            {
                Value = x.Key.ToString(),
                Text = x.Value
            }).ToList();
            paytypes = EnumHelper.GetEnumDictionary<OutProductPayType>().Select(x => new SelectListItem
            {
                Value = x.Key.ToString(),
                Text = x.Value
            }).ToList();
            businesslist = await _businessService.GetAllListAsync(1);
            expresslist = await _productService.GetAllExpressAsync();
            if (id > 0)
            {
                data = await _productService.DetailAsync(id);
            }
        }
        
        public async Task<JsonResult> OnPostUploadFileAsync(string root = "product", int id = 0)
        {
            if (id <= 0)
            {
                return Fail("请先填写上面资料");
            }
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return Fail("只支持multipart/form-data类型");
            }
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, HttpContext.Request.Body);
            var section = await reader.ReadNextSectionAsync();
            List<string> filelist = new List<string>();
            while (section != null)
            {
                var hasContentDispositionHeader =
                   ContentDispositionHeaderValue.TryParse(
                       section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {

                    }
                    else
                    {
                        string[] _permittedExtensions = { ".csv" };
                        long _fileSizeLimit = 1048576 * 5;
                        string rootname = $"/uploadfile/{root}/{DateTime.Now.ToString("yyyyMMdd")}";
                        string savefolder = _hostingEnvironment.WebRootPath;
                        var name = Path.GetRandomFileName() + ".csv";
                        var streamedFileContent = await FileHelpers.ProcessStreamedFile(
                            section, contentDisposition, ModelState,
                            _permittedExtensions, _fileSizeLimit);
                        if (!ModelState.IsValid)
                        {
                            string msg = "上传失败";
                            if (ModelState.Values.Count() > 0)
                            {
                                msg = ModelState.Values.FirstOrDefault().Errors.FirstOrDefault().ErrorMessage;
                            }
                            return Fail(msg);
                        }
                        var thumbnailPath = Path.Combine(savefolder + "/" + rootname, name);
                        if (!Directory.Exists(Path.GetDirectoryName(thumbnailPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(thumbnailPath));
                        }
                        else
                        {
                            //检查文件是否存在
                            if (System.IO.File.Exists(thumbnailPath))
                            {
                                return Fail("此文件已经存在");
                            }
                        }
                        var filepath = Path.Combine("wwwroot" + rootname + "/", name);
                        var virualpath = Path.Combine(rootname + "/", name);
                        var filename = contentDisposition.FileName.Value;
                        using (var targetStream = System.IO.File.Create(filepath))
                        {
                            await targetStream.WriteAsync(streamedFileContent);
                            filelist.Add(virualpath);
                        }
                        var result = await _productService.HandlerFileAsync(thumbnailPath, virualpath, savefolder, id);
                        return ResultJson(result);
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            return Success(filelist);
        }
    }
}
