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 EquipmentApi.IRepositories;
using MadRunFabric.Model;
using MongoDB.Driver;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using EquipmentApi.Model.Dto;
using Api.SignToken;
using Microsoft.Extensions.Configuration;

namespace EquipmentApi.Controllers
{
    /// <summary>
    /// 设备运维 -> 资料管理
    /// </summary>
    //[Authorize] //接口getdetails无需加验证
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class StudyMaterialsInfoController : BaseController
    {
        private readonly ILogger<StudyMaterialsInfoController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly IPro_StudyMaterials_InfoRepository _pro_studyMaterials_inforepository;
        private readonly ISignTokenService _signTokenService;
        private readonly IPro_Project_InfoRepository _pro_project_infoRepository;

        public StudyMaterialsInfoController(
            ILogger<StudyMaterialsInfoController> logger,
            IConfiguration configuration,
            ISys_User_AccountRepository sys_user_accountRepository,
            IPro_StudyMaterials_InfoRepository pro_studyMaterials_inforepository,
            ISignTokenService signTokenService,
            IPro_Project_InfoRepository pro_project_infoRepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_user_accountRepository = sys_user_accountRepository;
            _pro_studyMaterials_inforepository = pro_studyMaterials_inforepository;
            _signTokenService = signTokenService;
            _pro_project_infoRepository = pro_project_infoRepository;
        }

        /// <summary>
        /// 获取所有学习资料列表
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDrop(string projectid)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();

            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            var list = await _pro_studyMaterials_inforepository.Get(x => x.isdelete == 0);
            if (userinfo.isallproject == 0)
                list = list.Where(x => userinfo.projectlist.Contains(x.projectid));
            if (!string.IsNullOrEmpty(projectid))
                list = list.Where(x => x.projectid == projectid || x.projectid == null);

            var listmodel = new List<DropListDto>();
            foreach (var item in list)
            {
                var model = new DropListDto();
                model.id = item.id;
                model.text = item.title;
                listmodel.Add(model);
            }
            return Success("成功",listmodel);
        }

        /// <summary>
        /// 学习资料管理列表 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>
        [Authorize]
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string keyword, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Pro_StudyMaterials_Info>.Sort.Descending("createtime");
            var list = await _pro_studyMaterials_inforepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _pro_studyMaterials_inforepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Pro_StudyMaterials_Info>>();
            listApp.Add(Builders<Pro_StudyMaterials_Info>.Filter.Eq("isdelete", 0));
            if (!string.IsNullOrEmpty(stime))
                listApp.Add(Builders<Pro_StudyMaterials_Info>.Filter.Gt("createtime", stime + " 00:00:00"));
            if (!string.IsNullOrEmpty(etime))
                listApp.Add(Builders<Pro_StudyMaterials_Info>.Filter.Lt("createtime", etime + " 23:59:59"));
            //模糊查询(学习资料标题)
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Pro_StudyMaterials_Info>.Filter.Where(s => s.title.Contains(keyword) || s.content.Contains(keyword)));
            #endregion
            int recordCount = 0;
            if (listApp.Count > 0)
            {
                var filter = Builders<Pro_StudyMaterials_Info>.Filter.And(listApp);
                list = await _pro_studyMaterials_inforepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _pro_studyMaterials_inforepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
                total = recordCount,
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 学习资料管理列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword, string stime, string etime,string projectid, int pageindex = 1, int pagesize = 10)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //部分项目-在方法里面去掉了userinfo
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            int recordCount = 0;
            var result = _pro_studyMaterials_inforepository.GetListsByPage(keyword, stime, etime, projectid, userinfo, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 学习资料详情 by id
        /// </summary>
        /// <param name="id">学习资料id</param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _pro_studyMaterials_inforepository.GetSingle(id);
            if (model == null)
                return Error("获取失败");
            var result = new
            {
                id = model.id,
                title = model.title,
                content = model.content,
                createtime = model.createtime,
            };
            return Success("获取成功！", result);
        }

        /// <summary>
        /// 学习资料详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public IActionResult GetDetails(string id)
        {
            try
            {
                if (string.IsNullOrEmpty(id))
                    return Error("参数错误");
                var model = _pro_studyMaterials_inforepository.GetDetails(id);
                if (model != null)
                {
                    return Success("获取成功！", model);
                }
                return Error("获取失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "学习资料异常");
                return Error("学习资料失败");
            }
        }

        /// <summary>
        /// 添加学习资料信息
        /// </summary>
        /// <param name="input">学习资料参数</param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string title,string content, string projectid, List<FileBaseModel> studymaterfile)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            #region 验证判断
            if (string.IsNullOrEmpty(title))
                return Error("学习资料标题不能为空");
            if (string.IsNullOrEmpty(content))
                return Error("学习资料内容不能为空");
            #endregion
            var model = new Pro_StudyMaterials_Info();
            model.projectid = projectid;
            model.title = title;
            model.content = content;
            if (studymaterfile != null)
            {
                model.studymaterfile = studymaterfile;
            }
            else
            {
                model.studymaterfile = new List<FileBaseModel>();
            }
            //model.studymaterfile = studymaterfile;
            model.createby = usercode;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _pro_studyMaterials_inforepository.Add(model);
            if (b)
                return Success("添加成功");
            //日志
            _logger.LogError($"学习资料标题：{title}添加失败");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改学习资料信息
        /// </summary>
        [Authorize]
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(string id, string title, string content, string projectid, List<FileBaseModel> studymaterfile)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(title))
                return Error("学习资料标题不能为空");
            if (string.IsNullOrEmpty(content))
                return Error("学习资料内容不能为空");
            #endregion
            var model = new Pro_StudyMaterials_Info();
            model = await _pro_studyMaterials_inforepository.GetSingle(id);
            if (model == null)
                return Error("操作失败");
            model.projectid = projectid;
            model.title = title;
            model.content = content;
            if (studymaterfile != null)
            {
                model.studymaterfile = studymaterfile;
            }
            else
            {
                model.studymaterfile = new List<FileBaseModel>();
            }
            //model.studymaterfile = studymaterfile;
            bool b = await _pro_studyMaterials_inforepository.Update(model);
            if (b)
                return Success("保存成功");
            //日志
            _logger.LogError($"学习资料标题：{title}修改失败");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除学习资料信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authorize]
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _pro_studyMaterials_inforepository.GetSingle(item);
                    ml.isdelete = -1;
                    ml.deleteby = usercode;
                    ml.deletetime= DateTime.Now.ToLocalTime();
                    if (_pro_studyMaterials_inforepository.Update(ml).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        #region 学习资料管理(设备运维 -> 资料管理 -> 学习资料) - APP
        /// <summary>
        /// 获取所有学习资料列表 - App
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getapplist")]
        public IActionResult GetAppList(string keyword, string stime, string etime, string projectid)
        {
            string rolecode = User.Claims.FirstOrDefault(c => c.Type == "RoleCode").Value;
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //var userstr = _signTokenService.GetUserInfoAsync(usercode).Result;
            //var userinfo = userstr.ToJObject()["data"].ToString().ToObject<UserInfoModel>();
            
            var userinfos = _sys_user_accountRepository.GetUserInfo(usercode);
            var userinfo = JsonHelper.JsonToEntity<UserAccountInfoModel>(userinfos.ToJson());

            try
            {
                var result = _pro_studyMaterials_inforepository.GetAppLists(keyword, stime, etime, projectid, userinfo);
                return Success("获取成功", result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "设备运行工单异常");
                return Error("设备运行工单失败");
            }
        }

        /// <summary>
        /// 学习资料详情 by id
        /// </summary>
        /// <param name="id">学习资料id</param>
        /// <returns></returns>
        [Authorize]
        [HttpGet("getappdetailes")]
        public async Task<IActionResult> GetAppDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _pro_studyMaterials_inforepository.GetSingle(id);
            if (model == null)
                return Error("获取失败");
            var result = new
            {
                id = model.id,
                proname = model.title,
                province = model.content,
                city = model.createtime,
            };
            return Success("获取成功！", result);
        }

        #endregion

    }
}