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

namespace YBDevice.NWeb.Pages
{
    public class IndexModel : BaseModel
    {
        private static readonly FormOptions _defaultFormOptions = new FormOptions();
        private readonly IWebHostEnvironment _hostingEnvironment;
        public IndexModel(IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        public void OnGet()
        {

        }

        #region 枚举
        /// <summary>
        /// 获取枚举类
        /// </summary>
        /// <returns></returns>
        public JsonResult OnGetClientsData()
        {
            var data = new
            {
                StatusType = this.StatusType(),
                AccountType = this.AccountType(),
                AuthorizerStatus = this.AuthorizerStatus(),
                DeviceVerType = this.DeviceVerType(),
                DeviceStatus =this.DeviceStatus(),
                DeviceProType = this.DeviceProType(),
                AdStatus = this.AdStatus(),
                AdPositionType =this.AdPositionType(),
                AdType=this.AdType(),
                OutProductPayType =this.OutProductPayType(),
                OutProductType =this.OutProductType(),
                OutProductStatus = this.OutProductStatus(),
                GenderType  =this.GenderType(),
                OrderStatus = this.OrderStatus(),
                OrderType  =this.OrderType()
            };
            return Success(data);
        }
        private object OrderType()
        {
            return EnumHelper.GetEnumDictionary<OrderType>();
        }
        private object OrderStatus()
        {
            return EnumHelper.GetEnumDictionary<OrderStatus>();
        }
        private object GenderType()
        {
            return EnumHelper.GetEnumDictionary<GenderType>();
        }
        private object OutProductStatus()
        {
            return EnumHelper.GetEnumDictionary<OutProductStatus>();
        }
        private object OutProductType()
        {
            return EnumHelper.GetEnumDictionary<OutProductType>();
        }


        private object OutProductPayType()
        {
            return EnumHelper.GetEnumDictionary<OutProductPayType>();
        }
        private object AdType()
        {
            return EnumHelper.GetEnumDictionary<AdType>();
        }
        private object AdPositionType()
        {
            return EnumHelper.GetEnumDictionary<AdPositionType>();
        }

        private object AdStatus()
        {
            return EnumHelper.GetEnumDictionary<AdStatus>();
        }
        private object DeviceStatus()
        {
            return EnumHelper.GetEnumDictionary<DeviceStatus>();
        }
        private object DeviceProType()
        {
            return EnumHelper.GetEnumDictionary<DeviceProType>();
        }

        private object DeviceVerType()
        {
            return EnumHelper.GetEnumDictionary<DeviceVerType>();
        }
        private object AuthorizerStatus()
        {
            return EnumHelper.GetEnumDictionary<AuthorizerStatus>();
        }
        private object StatusType()
        {
            return EnumHelper.GetEnumDictionary<StatusType>();
        }

        private object AccountType()
        {
            return EnumHelper.GetEnumDictionary<AccountType>();
        }
        #endregion
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public async Task<JsonResult> OnPostUploadAsync(string root = "info")
        {
            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 = { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
                        long _fileSizeLimit = 1048576 * 5;
                        string rootname = $"/images/{root}/{DateTime.Now.ToString("yyyyMMdd")}";
                        string savefolder = _hostingEnvironment.WebRootPath;
                        var name = Path.GetRandomFileName() + ".jpg";
                        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);
                        }
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            return Success(filelist);
        }

        public async Task<JsonResult> OnPostUploadFileAsync(string root = "product")
        {
            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);
                        }
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            return Success(filelist);
        }
    }
}
