using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using MessageApi.IRepositories;
using Microsoft.Extensions.Logging;
using MadRunFabric.Model.MessageApi;
using System.Security.Claims;
using MongoDB.Driver;
using Microsoft.AspNetCore.Authorization;

namespace MessageApi.Controllers.Application
{
    /// <summary>
    /// 3D版本 - 升级提示接口
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class AppVersion3DController : BaseController
    {
        private readonly ILogger<AppVersion3DController> _logger;
        private readonly IApp_Version3DRepository _app_version3DRepository;

        public AppVersion3DController(
            ILogger<AppVersion3DController> logger,
            IApp_Version3DRepository app_version3DRepository
            )
        {
            _logger = logger;
            _app_version3DRepository = app_version3DRepository;
        }

        /// <summary>
        /// 获取3D版本分页
        /// </summary>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(int apptype, string projectid, string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _app_version3DRepository.GetListsByPage(apptype, projectid, keyword, stime, etime, pageindex, pagesize, out recordCount);

            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取3D版本详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public IActionResult GetDetailsAsync(string id)
        {
            var model = _app_version3DRepository.GetDetails(id);

            return Success("获取成功", model);
        }

        /// <summary>
        /// 添加3D版本信息
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="versionname"></param>
        /// <param name="versioncode"></param>
        /// <param name="ordernum"></param>
        /// <param name="downurl"></param>
        /// <param name="note"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(int apptype, string projectid, string versionname, string versioncode, List<FileBaseModel> downurl, string note)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            if (string.IsNullOrEmpty(versionname))
                return Error("版本名称不能为空");
            if (string.IsNullOrEmpty(versioncode))
                return Error("版本号不能为空");
            var model = new App_Version3D();
            model.apptype = apptype;
            model.projectid = projectid;
            model.versionname = versionname;
            model.versioncode = versioncode;
            model.createby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            model.downurl = downurl.ToList<FileBaseModel>();
            model.note = note;
            model.isdelete = 0;
            bool b = await _app_version3DRepository.Add(model);
            if (b)
                return Success("添加成功");
            //日志
            _logger.LogError($"版本名称：{versionname}，版本号：{versioncode}添加失败");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改3D版本信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="projectid"></param>
        /// <param name="versionname"></param>
        /// <param name="versioncode"></param>
        /// <param name="ordernum"></param>
        /// <param name="downurl"></param>
        /// <param name="httpurl"></param>
        /// <param name="note"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id,int apptype, string projectid, string versionname, string versioncode, int ordernum, List<FileBaseModel> downurl, string httpurl, string note)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(versionname))
                return Error("版本名称不能为空");
            if (string.IsNullOrEmpty(versioncode))
                return Error("版本号不能为空");
            var model = new App_Version3D();
            model = await _app_version3DRepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.apptype = apptype;
            model.projectid = projectid;
            model.versionname = versionname;
            model.versioncode = versioncode;
            model.createby = usercode;
            model.updatetime = DateTime.Now.ToLocalTime();
            model.downurl = downurl.ToList<FileBaseModel>();
            model.note = note;
            bool b = await _app_version3DRepository.Update(model);
            if (b)
                return Success("保存成功");
            //日志
            _logger.LogError($"版本名称：{versionname}，版本号：{versioncode}修改失败");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除3D版本信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            int num = 0;
            if (ids == null && ids.Length <= 0)
                return Error("请选择要删除的记录");
            foreach (var item in ids)
            {
                var model = await _app_version3DRepository.GetSingle(item);
                model.isdelete = -1;
                if (await _app_version3DRepository.Update(model))
                    num += 1;
            }
            if (num == ids.Length)
                return Success("删除成功");
            if (num > 0 && num < ids.Length)
                return Error("部分删除失败，请查看后重新操作");
            return Error("删除失败，请查看后重新操作");
        }

        #region App版本升级提示

        /// <summary>
        /// 获取最新3D版本详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("getnewdetailes")]
        public async Task<IActionResult> GetNewDetailsAsync(string projectid, int apptype = 1)
        {
            #region 判断验证
            if (string.IsNullOrEmpty(projectid))
                return Error("参数错误");
            #endregion
            //排序字段
            var sort = Builders<App_Version3D>.Sort.Descending("createtime");
            var model = await _app_version3DRepository.GetSingle(x => x.isdelete == 0 && x.projectid == projectid && x.apptype == apptype, sort);
            //其他方法
            //Task<IEnumerable<App_Version3D>> list = _app_version3DRepository.Get(null, null, sort);
            //var model = list.Result.SingleOrDefault();
            if (model != null)
            {
                var result = new
                {
                    id = model.id,
                    apptype = model.apptype,
                    projectid = model.projectid,
                    versionname = model.versionname,
                    versioncode = model.versioncode,
                    downurl = model.downurl,
                    createby = model.createby,
                    createtime = model.createtime,
                    updatetime = model.updatetime,
                    note = model.note
                };
                return Success("获取成功！", result);
            }
            return Success("获取成功！", null);
        }

        #endregion

    }
}