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

namespace EquipmentApi.Controllers
{
    /// <summary>
    /// 检查事项管理控制器，对项目信息的操作
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MattersMgrController : BaseController
    {
        private readonly ILogger<MattersMgrController> _logger;
        private readonly IWo_MattersRepository _wo_mattersRepository;
        public MattersMgrController(ILogger<MattersMgrController> logger, IWo_MattersRepository wo_mattersRepository)
        {
            _wo_mattersRepository = wo_mattersRepository;
            _logger = logger;
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string keyword, string projectid, int type, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _wo_mattersRepository.GetListsByPage(projectid, keyword, type, pageindex, pagesize, out recordCount);
            var list = result.ToList();

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

        /// <summary>
        /// 根据项目id获取下拉列表
        /// </summary>
        /// <param name="projectid"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public IActionResult GetListsAsync(string projectid,int type=0)
        {
            var vlist = _wo_mattersRepository.GetLists(projectid,type);
            var obj = new
            {
                list = vlist
            };
            return Success("根据条件获取数据成功", obj);
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [HttpGet("getsingle")]
        public IActionResult GetSingleAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = _wo_mattersRepository.GetDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(string projectid, string matter, List<string> contents,int type)
        {
            if (string.IsNullOrWhiteSpace(projectid))
            {
                return Error("请选择项目");
            }
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            Wo_Matters clmodel = new Wo_Matters();
            var b = false;
            #region 赋值
            clmodel.id = ObjectId.GenerateNewId().ToString();
            clmodel.projectid = projectid;
            clmodel.matter = matter;
            if (contents != null && contents.Count > 0)
            {
                clmodel.contents = contents;
            }
            else
                clmodel.contents = new List<string>();
            clmodel.checktype = type;
            clmodel.createuser = usercode;
            clmodel.createtime = DateTime.Now;
            clmodel.isdelete = false;
            #endregion


            b = await _wo_mattersRepository.Add(clmodel);
            if (b)
            {
                return Success("保存成功");
            }
            return Error("保存失败");
        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> EditAsync(string id, string projectid, string matter, List<string> contents, int type)
        {
            if (string.IsNullOrWhiteSpace(projectid))
            {
                return Error("请选择项目");
            }
            var res = false;
            var clmodel = await _wo_mattersRepository.GetSingle(id);
            if (clmodel == null)
                return Error("操作失败");
            clmodel.projectid = projectid;//项目名称
            clmodel.matter = matter;
            if (contents != null && contents.Count > 0)
            {
                clmodel.contents = contents;
            }
            else
                clmodel.contents = new List<string>();
            clmodel.checktype = type;
            res = _wo_mattersRepository.UpdateOne(clmodel).Result;
            if (res)
                return Success("保存成功");
            else
            {
                return Error("保存失败");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                try
                {
                    foreach (var item in ids)
                    {
                        var ml = await _wo_mattersRepository.GetSingle(item);
                        ml.isdelete = true;
                        ml.deleteuser = usercode;
                        ml.deletetime = DateTime.Now;
                        if (await _wo_mattersRepository.UpdateOne(ml))
                        {
                            res += 1;
                        }
                    }
                    if (res == ids.Length)
                        return Success("删除成功");
                    else if (res > 0 && res < ids.Length)
                        return Error("部分删除失败，请查看后重新操作");
                    else
                        return Error("删除失败，请查看后重新操作");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "删除异常");
                    return Error("删除失败");
                }
            }
            else
                return Error("请选择要删除的记录");
        }
    }
}