using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
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.IO;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;
using YBDevice.NApi.Application.UserInfo;

namespace YBDevice.NApi.Controllers
{
    /// <summary>
    /// 用户管理接口
    /// </summary>
    public class UserController : BaseController
    {
        private static readonly FormOptions _defaultFormOptions = new FormOptions();
        private readonly IWebHostEnvironment _hostingEnvironment;
        private readonly IUserService _userService;
        public UserController(IWebHostEnvironment hostingEnvironment,IUserService userService)
        {
            _hostingEnvironment = hostingEnvironment;
            _userService = userService;
        }

        /// <summary>
        /// 获取用户使用过的设备类型列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> GetDevTypeListAsync(string appid)
        {
            return await _userService.GetDevTypeListAsync(appid);
        }
        /// <summary>
        /// 添加设备类型
        /// </summary>
        /// <param name="devtype"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> AddDevTypeAsync(int devtype)
        {
            return await _userService.AddDevTypeAsync(devtype);
        }
        /// <summary>
        /// 获取用户基本信息
        /// </summary>
        /// <param name="familyid">家庭成员ID</param>
        /// <param name="devtype">设备类型</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> GetUserInfoAsync(int familyid=0,int devtype=0)
        {
            return await _userService.GetUserInfoAsync(familyid,devtype);
        }
        /// <summary>
        /// 获取用户测量数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetMeasureInfoAsync([FromBody] UserMeasureInfoModel data)
        {
            return await _userService.GetMeasureInfoAsync(data);
        }
        /// <summary>
        /// 获取八电极测量数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetBodyMeasureInfoAsync([FromBody] UserBodyMeasureInfoModel data)
        {
            return await _userService.GetBodyMeasureInfoAsync(data);
        }

        /// <summary>
        /// 获取八电极趋势信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetBodyTrendListAsync([FromBody] BodyQueryTrandDto data)
        {
            return await _userService.GetBodyTrendListAsync(data);
        }

        /// <summary>
        /// 获取趋势信息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> GetTrendListAsync([FromBody] BodyQueryTrandDto data)
        {
            return await _userService.GetTrendListAsync(data);
        }

        /// <summary>
        /// 解密手机号
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ApiAuthorizeFilter(ignore:true)]
        public async Task<ResultInfo> DecryptPhoneAsync([FromBody] WxOpenDecryptSubmitModel model)
        {
            return await _userService.DecryptPhoneAsync(model);
        }


        /// <summary>
        /// 解密微信运动
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> DecryptWxRunAsync([FromBody] WxOpenDecryptSubmitModel model)
        {
            var wxrun = await _userService.DecodeWxRunBySessionIdAsync(model.sessionId, model.encryptedData, model.iv);
            if(wxrun == null)
            {
                return new ResultInfo(ResultState.FAIL, "步数获取失败");
            }
            else
            {
                return new ResultInfo(ResultState.SUCCESS, "success", wxrun);
            }
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> OnPostUploadAsync(string root = "user")
        {
            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, 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 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);
                        }
                    }
                }
                section = await reader.ReadNextSectionAsync();
            }
            return new ResultInfo(ResultState.SUCCESS, "success", filelist);
        }

        /// <summary>
        /// 设备激活
        /// </summary>
        /// <param name="sn">设备机器码</param>
        /// <param name="code">设备序列号,贴纸上,支持二维码和条形码</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> ActiveAsync(string sn, string code)
        {
            return await _userService.ActiveAsync(sn, code);
        }

        /// <summary>
        /// 退出登录
        /// </summary>
        /// <param name="sessionId"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResultInfo> OutLogin(string sessionId)
        {
            return await _userService.OutLogin(sessionId);
        }
        /// <summary>
        /// 修改初始体重
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> SubmitFirstWeight(UserFirstWeightC2SDto data)
        {
            return await _userService.SubmitFirstWeight(data);
        }
    }
}
