using Furion.DynamicApiController;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
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 Waste.Application.SubscribeInfo;
using Waste.Domain.DataModel;

namespace Waste.Application.ThirdApiInfo
{
    /// <summary>
    /// 开放数据
    /// </summary>
    [ApiDescriptionSettings("DevApi")]
    [NonUnify]
    public class OpenAppService : IDynamicApiController
    {
        private readonly IOpenService _openService;
        private static IWebHostEnvironment _hostingEnvironment;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private static readonly FormOptions _defaultFormOptions = new FormOptions();

        public OpenAppService(IOpenService openService, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor)
        {
            _openService = openService;
            _hostingEnvironment = webHostEnvironment;
            _httpContextAccessor = httpContextAccessor;
        }

        /// <summary>
        /// 获取设备上报相关信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetDevInfoAsync(GetDevInfoRequestDto data)
        {
            return await _openService.GetDevInfoAsync(data);
        }

        /// <summary>
        /// 心跳数据上报
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> PostHeartAsync(DevHeartRequestDto data)
        {
            return await _openService.PostHeartAsync(data);
        }

        /// <summary>
        /// 获取设备注册信息,第一次开机使用
        /// </summary>
        /// <param name="ecode"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<ResultInfo> RegInfoAsync(string ecode)
        {
            return await _openService.RegInfoAsync(ecode);
        }

        /// <summary>
        /// 更新上报状态
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> UpdateStatusAsync(UpdateStatusDto data)
        {
            return await _openService.UpdateStatusAsync(data);
        }

        /// <summary>
        /// BUG上报
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/reportbug/Post")]
        public async Task<object> PostAsync([FromQuery] string ecode = "")
        {
            var Request = _httpContextAccessor.HttpContext.Request;
            //先保存上传的图片
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return new
                {
                    status = new
                    {
                        code = 0,
                        name = "FAIL",
                        message = "上传失败"
                    }
                };
            }
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, Request.Body);
            var section = await reader.ReadNextSectionAsync();
            while (section != null)
            {
                var hasContentDispositionHeader =
             ContentDispositionHeaderValue.TryParse(
                 section.ContentDisposition, out var contentDisposition);
                if (hasContentDispositionHeader)
                {
                    if (!MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
                    {
                    }
                    else
                    {
                        string[] _permittedExtensions = { };
                        long _fileSizeLimit = 1048576 * 10;
                        string rootname = $"/bugs/{DateTime.Now.ToString("yyyyMMdd")}";
                        string savefolder = _hostingEnvironment.WebRootPath;

                        ModelStateDictionary modelState = new ModelStateDictionary();
                        var streameFileData = await FileHelpers.ApiProcessStreamedFile(
                            section, contentDisposition, modelState,
                            _permittedExtensions, _fileSizeLimit);
                        var streamedFileContent = streameFileData.data;
                        modelState = streameFileData.modelState;
                        if (!modelState.IsValid)
                        {
                            string msg = "上传失败";
                            if (modelState.Values.Count() > 0)
                            {
                                msg = modelState.Values.FirstOrDefault().Errors.FirstOrDefault().ErrorMessage;
                            }
                            return new
                            {
                                status = new
                                {
                                    code = 0,
                                    name = "FAIL",
                                    message = msg
                                }
                            };
                        }
                        var name = $"{Path.GetRandomFileName()}{Path.GetExtension(contentDisposition.FileName.Value)}";
                        if (!string.IsNullOrEmpty(ecode))
                        {
                            name = $"{ecode}_{name}";
                        }
                        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 new
                                {
                                    status = new
                                    {
                                        code = 0,
                                        name = "FAIL",
                                        message = "此文件已存在"
                                    }
                                };
                            }
                        }
                        var filepath = Path.Combine("wwwroot" + rootname + "/", name);
                        var filename = contentDisposition.FileName.Value;
                        using (var targetStream = File.Create(filepath))
                        {
                            await targetStream.WriteAsync(streamedFileContent);
                        }
                    }
                }
            }
            return new
            {
                status = new
                {
                    code = 1,
                    name = "SUCCESS",
                    message = ""
                }
            };
        }

        /// <summary>
        /// BUG上报
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/reportbug/postbug")]
        public object PostBug(BugModel bug)
        {
            var errmsg = $"机器码:{bug.ecode},位置:{bug.ExceptionPos},信息:{bug.ExceptionInfo}";
            return new
            {
                status = new
                {
                    code = 1,
                    name = "SUCCESS",
                    message = ""
                }
            };
        }

        /// <summary>
        /// 正式升级
        /// </summary>
        /// <param name="ecode">机器码</param>
        /// <param name="myver">版本号</param>
        /// <param name="type">类型</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        [Route("api/upgrade/get")]
        public async Task<object> GetAsync(string type, string ecode = "", int myver = 400)
        {
            await _openService.UpdateVersionAsync(new DeviceVerS2SDto
            {
                ecode = ecode,
                ver = myver.ToString()
            });
            string rootpath = _hostingEnvironment.WebRootPath;
            //读取文件,返回升级信息
            var path = $"{rootpath}/apks/upgrade/{type}.txt";
            var ulist = new List<string> { "419b553e92986112", "8f259824aef42c36", "fa324b8fa8da1fc0", "be6d6ef03519d42e", "352050657b2b2608", "d3fc9a38d7f67604" };
            if (ulist.Contains(ecode))
            {
                path = $"{rootpath}/apks/upgrade/OTHER.txt";
            }
            if (!File.Exists(path))
            {
                return new
                {
                    status = new
                    {
                        code = 0,
                        name = "FAIL",
                        message = "不存在任何信息"
                    }
                };
            }
            FileStream fileStream = new FileStream(path, FileMode.Open);
            string result = string.Empty;
            using (StreamReader reader = new StreamReader(fileStream))
            {
                result = await reader.ReadToEndAsync();
            }
            if (string.IsNullOrEmpty(result))
            {
                return new
                {
                    status = new
                    {
                        code = 0,
                        name = "FAIL",
                        message = "不存在任何信息"
                    }
                };
            }
            return result.ToJson();
        }

        /// <summary>
        /// 获取机器到期时间
        /// </summary>
        /// <param name="ecode"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        [Route("api/machine/getisenable")]
        public Object GetIsEnable(string ecode)
        {
            if (string.IsNullOrEmpty(ecode))
            {
                return new
                {
                    status = new
                    {
                        code = 0,
                        name = "FAIL",
                        message = "参数错误"
                    }
                };
            }
            return new
            {
                status = new
                {
                    code = 1,
                    name = "SUCCESS",
                    message = ""
                },
                data = new
                {
                    isenable = true,
                    deadline = DateTime.Now.AddYears(2).ToString("yyyy-MM-dd")
                }
            };
        }

        /// <summary>
        /// 通过ailink wifi模式发送的数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<object> WifiAsync(WifiRequestC2SDto data)
        {
            return await _openService.WifiPostAsync(data);
        }

        /// <summary>
        /// 新增电子秤
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> AddProductAsync(ProductInfoDto data)
        {
            return await _openService.AddProductAsync(data);
        }

        [HttpPost]
        public async Task<PageParms<W_Product>> GetProductAsync(QueryParams param)
        {
            return await _openService.GetProductAsync(param);
        }
    }
}