using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
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.ApiBase;
using Nirvana.Common.File;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace YBDevice.NApi.Application.BusinessClient.AccountInfo
{
    /// <summary>
    /// 商户管理接口
    /// </summary>
    [ApiDescriptionSettings("BusinessClient")]
    [AppAuthorize]
    public class BusinessAppService : IDynamicApiController
    {
        private readonly IBusinessService _businessService;
        private static readonly FormOptions _defaultFormOptions = new FormOptions();
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IResultService _resultService;
        public BusinessAppService(IBusinessService businessService, IWebHostEnvironment webHostEnvironment, IHttpContextAccessor httpContextAccessor, IResultService resultService)
        {
            _businessService = businessService;
            _hostingEnvironment = webHostEnvironment;
            _httpContextAccessor = httpContextAccessor;
            _resultService = resultService;
        }
        /// <summary>
        /// 修改商户昵称
        /// </summary>
        /// <param name="name">昵称</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<ResultInfo> ChanageNicNameAsync(
            [Required(ErrorMessage ="请先输入昵称")]
            [MaxLength(20,ErrorMessage ="昵称长度最多为20位")]
            string name
            )
        {
            return await _businessService.ChangeNickName(name);
        }

        /// <summary>
        /// 获取商户资料
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> GetUserInfoAsync()
        {
            return await _businessService.GetUserInfoAsync();
        }
        /// <summary>
        /// 头像上传
        /// </summary>
        /// <returns></returns>
        public async Task<ResultInfo> UploadImg([FromQuery] string root = "user")
        {
            var Request = _httpContextAccessor.HttpContext.Request;
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return new ResultInfo(ResultState.FAIL, "只支持multipart/form-data类型");
            }
            var boundary = MultipartRequestHelper.GetBoundary(MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit);
            var reader = new MultipartReader(boundary, 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";
                        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 ResultInfo(ResultState.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 new ResultInfo(ResultState.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);
                        }
                        await _businessService.UploadImgAsync(virualpath);
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            return new ResultInfo(ResultState.SUCCESS, "上传成功", filelist);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public async Task<ResultInfo> ChangePwd(BusinessChangePwdDto businessChangePwdDto)
        {
            return await _businessService.ChangePwd(businessChangePwdDto);
        }
        /// <summary>
        /// 测量记录列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetResultList(BusinessResultC2SDto queryParams)
        {
            return await _resultService.GetListAsync(queryParams);
        }
        /// <summary>
        /// 获取指定用户的汇总数据
        /// </summary>
        /// <param name="id">指定记录的ID</param>
        /// <returns></returns>
        [QueryParameters]
        public async Task<ResultInfo> GetResultUserData(Guid id)
        {
            return await _resultService.GetUserData(id);
        }
        /// <summary>
        /// 获取指定用户的体重历史记录列表
        /// </summary>
        /// <param name="measureUserQueryDto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetResultUserWeightListAsync(MeasureUserQueryDto measureUserQueryDto)
        {
            return await _resultService.GetUserWeightListAsync(measureUserQueryDto);
        }
        /// <summary>
        /// 获取用户所有测量项记录
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="queryParams"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetUserResultListAsync([FromQuery] Guid id,QueryParams queryParams)
        {
            return await _resultService.GetUserResultListAsync(id,queryParams);
        }

        /// <summary>
        /// 获取用户测量记录详情
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<ResultInfo> GetUserResultDetailAsync(Guid id)
        {
            return await _resultService.GetUserResultDetailAsync(id);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<ResultInfo> OutLogin(string sessionId)
        {
            return await _businessService.OutLogin(sessionId);
        }
    }
}
