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

namespace MessageApi.Controllers
{
    /// <summary>
    /// App版本信息控制器 - 升级提示接口
    /// </summary>    
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class ApplicationsVersionController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<ApplicationsVersionController> _logger;
        private readonly IApp_ApplicationsVersionRepository _app_applicationsVersionRepository;

        public ApplicationsVersionController(
            IConfiguration configuration,
            ILogger<ApplicationsVersionController> logger, 
            IApp_ApplicationsVersionRepository app_applicationsVersionRepository
            
            )
        {
            _configuration = configuration;
            _logger = logger;
            _app_applicationsVersionRepository = app_applicationsVersionRepository;
        }

        /// <summary>
        /// 获取所有App版本列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getall")]
        public async Task<IActionResult> GetAllListsAsync()
        {
            //Task<IEnumerable<App_ApplicationsVersion>>
            var list = await _app_applicationsVersionRepository.GetAll();
            return Success("获取全部数据成功", list);
        }

        /// <summary>
        /// 获取App版本列表 by page
        /// </summary>
        /// <param name="apptype">应用分类（0android 1ios）</param>
        /// <param name="keyword">版本编号</param>
        /// <param name="createtime">添加开始时间</param>
        /// <param name="createtime">添加结束时间</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(int apptype, string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<App_ApplicationsVersion>.Sort.Descending("createtime");
            var list = await _app_applicationsVersionRepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _app_applicationsVersionRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listApp = new List<FilterDefinition<App_ApplicationsVersion>>();
            listApp.Add(Builders<App_ApplicationsVersion>.Filter.Eq("isdelete", 0));
            if (apptype>0)
                listApp.Add(Builders<App_ApplicationsVersion>.Filter.Eq("apptype", apptype));
            if (!string.IsNullOrEmpty(stime))
                listApp.Add(Builders<App_ApplicationsVersion>.Filter.Gt("createtime", stime));
            if (!string.IsNullOrEmpty(etime))
                listApp.Add(Builders<App_ApplicationsVersion>.Filter.Lt("createtime", etime));
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<App_ApplicationsVersion>.Filter.Where(s => s.versionname.Contains(keyword) || s.versioncode.Contains(keyword)));
            #endregion

            int recordCount = 0;
            if (listApp.Count > 0)
            {
                var filter = Builders<App_ApplicationsVersion>.Filter.And(listApp);
                list = await _app_applicationsVersionRepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _app_applicationsVersionRepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

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

        /// <summary>
        /// 获取App版本详情 by id
        /// </summary>
        /// <param name="id">App版本id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            
            var model = await _app_applicationsVersionRepository.GetSingle(id);
            if (model != null)
            {
                var result = new
                {
                    apptype = model.apptype,
                    versionname = model.versionname,
                    versioncode = model.versioncode,
                    createby = model.createby,
                    createtime = model.createby,
                    updatetime = model.updatetime,
                    ordernum = model.ordernum,
                    downurl = model.downurl,
                    httpurl = model.httpurl,
                    note = model.note,
                };
                return Success("获取成功！", result);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加App版本信息
        /// </summary>
        /// <param name="apptype">应用分类（0android 1ios）</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 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(versionname))
                return Error("版本名称不能为空");
            if (string.IsNullOrEmpty(versioncode))
                return Error("版本号不能为空");
            //if (string.IsNullOrEmpty(downurl))
            //    return Error("版本下载地址不能为空");
            var model = new App_ApplicationsVersion();
            model.apptype = apptype;
            model.versionname = versionname;
            model.versioncode = versioncode;
            model.createby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            model.ordernum = ordernum;
            model.downurl = downurl.ToList<FileBaseModel>();
            model.httpurl = httpurl;
            model.note = note;
            model.isdelete = 0;
            //var model = new App_ApplicationsVersion();
            //model.apptype = 0;
            //model.versionname = "2018App端版本v1.1";
            //model.versioncode = "1.1";
            //model.createby = "8000";
            //model.createtime = DateTime.Now.ToLocalTime();
            //model.ordernum = 1;
            //model.downurl = null;
            //model.httpurl = "http://www.iciba.com";
            //model.note = "";
            //model.isdelete = 0;
            bool b = await _app_applicationsVersionRepository.Add(model);
            if (b)
                return Success("添加成功");
            //日志
            _logger.LogError($"版本名称：{versionname}，版本号：{versioncode}添加失败");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改App版本信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="apptype">应用分类（0android 1ios）</param>
        /// <param name="versionname">版本名称</param>
        /// <param name="versioncode">版本号</param>
        /// <param name="ordernum">排序</param>
        /// <param name="downurl">下载地址</param>
        /// <param name="note">备注</param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, int apptype, 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("版本号不能为空");
            //if (string.IsNullOrEmpty(downurl))
            //    return Error("版本下载地址不能为空");
            App_ApplicationsVersion model = new App_ApplicationsVersion();
            model = await _app_applicationsVersionRepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.apptype = apptype;
            model.versionname = versionname;
            model.versioncode = versioncode;
            model.createby = usercode;
            //model.createtime = DateTime.Now.ToLocalTime();
            model.updatetime = DateTime.Now.ToLocalTime();
            model.ordernum = ordernum;
            model.downurl = downurl.ToList<FileBaseModel>();
            model.httpurl = httpurl;
            model.note = note;
            //model.isdelete = 0;
            bool b = await _app_applicationsVersionRepository.Update(model);
            if(b)
                return Success("保存成功");
            //日志
            _logger.LogError($"版本名称：{versionname}，版本号：{versioncode}修改失败");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除App版本信息 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_applicationsVersionRepository.GetSingle(item);
                model.isdelete = -1;
                if (await _app_applicationsVersionRepository.Update(model))
                    num += 1;
            }
            if (num == ids.Length)
                return Success("删除成功");
            if (num > 0 && num < ids.Length)
                return Error("部分删除失败，请查看后重新操作");
            return Error("删除失败，请查看后重新操作");
        }

        #region App版本升级提示

        /// <summary>
        /// 获取最新App版本详情
        /// </summary>
        /// <returns></returns>
        [HttpGet("getnewdetailes")]
        public async Task<IActionResult> GetNewDetailsAsync(int apptype = 1)
        {
            string  oldurl =  _configuration["downurl:oldurls"].ToString().ToLower();
            string newurl = _configuration["downurl:newurls"].ToString().ToLower();
            //排序字段
            var sort = Builders<App_ApplicationsVersion>.Sort.Descending("createtime");
            var model = await _app_applicationsVersionRepository.GetSingle(x => x.isdelete == 0 && x.apptype == apptype, sort);
            //其他方法
            //Task<IEnumerable<App_ApplicationsVersion>> list = _app_applicationsVersionRepository.Get(null, null, sort);
            //var model = list.Result.SingleOrDefault();
            if (model.downurl != null)
            {

                foreach (var item in model.downurl.ToArray())
                {
                        if (item.fileurl.Contains(oldurl))
                        {
                            item.fileurl = item.fileurl.Replace(oldurl, newurl);
                        }
                }
             }
            if (model != null)
            {
                var result = new
                {
                    id = model.id,
                    apptype = model.apptype,
                    versionname = model.versionname,
                    versioncode = model.versioncode,
                    createby = model.createby,
                    createtime = model.createtime.ToLocalTime(),
                    updatetime = model.updatetime.ToLocalTime(),
                    ordernum = model.ordernum,
                    downurl = model.downurl,
                    httpurl = model.httpurl,
                    note = model.note,
                };
                return Success("获取成功！", result);
            }
            return Success("获取成功！", null);
        }

        #endregion
    }
}