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 Microsoft.AspNetCore.Authorization;
using MadRunFabric.Model.ConfigurationApi.Model;
using ConfigurationApi.Models.Input;
using ConfigurationApi.Model.Dto;
using ConfigurationApi.IRepositories;

namespace ConfigurationApi.Controllers
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class AuthorizationU3DController : BaseController
    {
        private readonly ILogger<AuthorizationU3DController> _logger;
        private readonly ISys_AuthorizationU3DRepository _sys_authorizationU3DRepository;
        public AuthorizationU3DController(
            ILogger<AuthorizationU3DController> logger,
            ISys_AuthorizationU3DRepository sys_authorizationU3DRepository)
        {
            _logger = logger;
            _sys_authorizationU3DRepository = sys_authorizationU3DRepository;
        }

        /// <summary>
        /// 获取授权加密客户端列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword, string projectid, string stime, string etime, int isopen = -1, int pageIndex = 1, int pageSize = 10)
        {
            int recordCount = 0;
            var result = _sys_authorizationU3DRepository.GetListsByPage(keyword, projectid, stime, etime, isopen, pageIndex, pageSize, out recordCount);
            var list = new List<U3DDto>();
            foreach (var item in result)
            {
                var model = new U3DDto();
                TimeSpan ts = item.duedate - DateTime.Now;
                model = item;
                model.duedate = item.duedate;    //剩余到期天数
                model.duedate_day = ts.Days;    //剩余到期天数
                list.Add(model);
            }
            var obj = new
            {
                rows = list,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 添加客户端（授权验证） - 前后端端
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(U3DInput input)
        {
            var ip = IPHelper.GetIp(this.HttpContext);
            #region 验证判断
            if (string.IsNullOrEmpty(input.authorizationcode))
                return Error("验证序列号不能为空");
            #endregion
            var model_code = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(input.authorizationcode) && x.isdelete == 0);
            if (model_code == null)
            {
                var model = new Sys_AuthorizationU3D();
                model.authorizationcode = input.authorizationcode;
                model.projectid = input.projectid;
                //到期时间处理
                string duedate = input.duedate.ToString("yyyy-MM-dd") + " 23:59:59";
                model.duedate = DateTime.Parse(duedate);
                model.ip = ip;
                model.remark = input.remark;
                if (await _sys_authorizationU3DRepository.Add(model))
                {
                    _logger.LogInformation("U3D设备信息添加成功");
                    return Success("添加成功");
                }
                else
                {
                    _logger.LogError("U3D设备信息添加失败");
                    return Error("添加失败");
                }
            }
            return Success("设备信息已经存在");
        }

        /// <summary>
        /// 修改客户端（授权验证）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(U3DInput input)
        {
            var ip = IPHelper.GetIp(this.HttpContext);
            #region 验证判断
            if (string.IsNullOrEmpty(input.authorizationcode))
                return Error("序列号不能为空");
            if (string.IsNullOrEmpty(input.projectid))
                return Error("项目名称不能为空");
            if (string.IsNullOrEmpty(input.duedate.ToString()))
                return Error("到期时间不能为空");
            #endregion
            var model = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(input.authorizationcode) && x.isdelete == 0);
            if (model != null)
            {
                model.authorizationcode = input.authorizationcode;    //加密序列号---
                model.projectid = input.projectid;
                //到期时间处理
                string duedate = input.duedate.ToString("yyyy-MM-dd") + " 23:59:59";
                model.duedate = DateTime.Parse(duedate);
                model.remark = input.remark;
                if (await _sys_authorizationU3DRepository.UpdateOne(model))
                {
                    _logger.LogInformation("U3D设备信息更新成功");
                    return Success("更新成功");
                }
                else
                {
                    _logger.LogError("U3D设备信息修改失败");
                    return Error("修改失败");
                }
            }
            else
            {
                _logger.LogError("U3D设备信息无权修改");
                return Error("无权修改");
            }
        }

        /// <summary>
        /// 开启（授权验证）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("open")]
        public async Task<IActionResult> OpenAsync(U3DInput input)
        {
            var ip = IPHelper.GetIp(this.HttpContext);
            #region 验证判断
            if (string.IsNullOrEmpty(input.authorizationcode))
                return Error("序列号不能为空");
            #endregion

            var model = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(input.authorizationcode) && x.isdelete == 0);
            if (model != null)
            {
                #region 验证
                //if (model.isdelete == 1)
                //    return Error("此设备验证授权已删除,请联系厂家重新验证授权");
                if (model.isopen == 1)
                    return Error("此设备验证授权已开启,无需再操作");
                //验证是否到期
                if (string.IsNullOrEmpty(model.duedate.ToString()))
                    return Error("到期时间无效");
                DateTime dt1 = DateTime.Now;
                DateTime dt2 = model.duedate;
                //TimeSpan ts = dt2 - dt1;
                int days = (dt2 - dt1).Days;
                if (dt2 < dt1)
                    return Error($"此设备验证授权已到期{days}天,无权开启");
                #endregion

                model.isopen = 1;
                if (await _sys_authorizationU3DRepository.UpdateOne(model))
                {
                    _logger.LogInformation($"U3D设备信息开启成功(验证序列号：{input.authorizationcode})");
                    return Success("开启成功");
                }
                else
                {
                    _logger.LogError($"U3D设备信息开启失败(验证序列号：{input.authorizationcode})");
                    return Error("开启失败");
                }
            }
            else
            {
                _logger.LogError($"U3D设备信息无权开启(验证序列号：{input.authorizationcode})");
                return Error("无权开启");
            }
        }

        /// <summary>
        /// 禁用（授权验证）
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("close")]
        public async Task<IActionResult> CloseAsync(U3DInput input)
        {
            var ip = IPHelper.GetIp(this.HttpContext);
            #region 验证判断
            if (string.IsNullOrEmpty(input.authorizationcode))
                return Error("序列号不能为空");
            #endregion

            var model = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(input.authorizationcode) && x.isdelete == 0);
            if (model != null)
            {
                #region 验证
                if (model.isopen == 0)
                    return Error("此设备验证授权已禁用,无需再操作");
                #endregion

                model.isopen = 0;
                if (await _sys_authorizationU3DRepository.UpdateOne(model))
                {
                    _logger.LogInformation($"U3D设备信息禁用成功(验证序列号：{input.authorizationcode})");
                    return Success("禁用成功");
                }
                else
                {
                    _logger.LogError($"U3D设备信息禁用失败(验证序列号：{input.authorizationcode})");
                    return Error("禁用失败");
                }
            }
            else
            {
                _logger.LogError($"U3D设备信息无权禁用(验证序列号：{input.authorizationcode})");
                return Error("无权禁用");
            }
        }

        /// <summary>
        /// 删除（授权验证） by ids
        /// <summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var model = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(item) && x.isdelete == 0);
                    model.isdelete = 1;
                    model.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_authorizationU3DRepository.Update(model).Result)
                        res += 1;
                }
                if (res == ids.Length)
                {
                    _logger.LogInformation($"U3D设备信息部分删除失败(验证序列号：{ids})");
                    return Success("删除成功");
                }
                else if (res > 0 && res < ids.Length)
                {
                    _logger.LogInformation($"U3D设备信息部分删除失败(验证序列号：{ids})");
                    return Error("部分删除失败，请查看后重新操作");
                }
                else
                {
                    _logger.LogError($"U3D设备信息禁用成功(验证序列号：{ids})");
                    return Error("删除失败，请查看后重新操作");
                }
            }
            return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 获取到期时间 - 暂不用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("getinfo")]
        public async Task<IActionResult> GetInfoAsync(U3DInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.authorizationcode))
                return Error("序列号不能为空");
            #endregion

            var model = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(input.authorizationcode) && x.isdelete == 0);
            if (model != null)
                return Success("获取成功！", model);
            return Error("获取失败");
        }

        /// <summary>
        /// 定时验证注册码（授权验证） - 前端定时验证
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("verification")]
        public async Task<IActionResult> VerificationAsync(U3DInput input)
        {
            var ip = IPHelper.GetIp(this.HttpContext);
            #region 验证判断
            if (string.IsNullOrEmpty(input.authorizationcode))
                return Error("序列号不能为空");
            #endregion
            var model = await _sys_authorizationU3DRepository.GetSingle(x => x.authorizationcode.Equals(input.authorizationcode) && x.isdelete == 0);
            if (model != null)
            {
                #region 验证
                //if (model.isdelete == 1)
                //    return Error("此设备验证授权已删除,请联系厂家重新验证授权");
                if (model.isopen == 0)
                    return Error("此设备验证授权已禁用,请联系厂家重新验证授权");
                //验证是否到期
                if (string.IsNullOrEmpty(model.duedate.ToString()))
                    return Error("到期时间无效");
                DateTime dt1 = DateTime.Now;
                DateTime dt2 = model.duedate;
                //TimeSpan ts = dt2 - dt1;
                int days = (dt2 - dt1).Days;
                if (dt2 < dt1)
                {
                    //到期时，自动禁用
                    model.isopen = 0;
                    await _sys_authorizationU3DRepository.UpdateOne(model);
                    return Error($"此设备验证授权已到期{days}天,请联系厂家重新验证授权");
                }
                #endregion
                var obj = new
                {
                    duedate = model.duedate.ToString("yyyy-MM-dd"),
                    dueday = days
                };
                return Success("验证成功", obj);
            }
            else
            {
                _logger.LogError("U3D设备信息验证失败");
                return Error("验证失败");
            }

        }
    }
}