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

namespace SignTokenApi.Controllers
{
    /// <summary>
    /// 班别
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WorkGroupController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<WorkGroupController> _logger;
        private readonly ISys_Work_GroupRepository _sys_work_groupRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public WorkGroupController(IConfiguration configuration, ILogger<WorkGroupController> logger, ISys_Work_GroupRepository sys_work_groupRepository, ISys_User_AccountRepository sys_user_accountRepository)
        {
            _logger = logger;
            _configuration = configuration;
            _sys_work_groupRepository = sys_work_groupRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        /// <summary>
        /// 获取班别分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListsByPageAsync(string projectid,string keyword, int pageindex = 1, int pagesize = 10)
        {
            //#region 条件信息
            ////根据条件查询集合
            //var listApp = new List<FilterDefinition<Sys_Work_Group>>();
            //listApp.Add(Builders<Sys_Work_Group>.Filter.Eq("isdelete", 0));
            ////模糊查询
            //if (!string.IsNullOrEmpty(keyword))
            //    listApp.Add(Builders<Sys_Work_Group>.Filter.Where(s => s.name.Contains(keyword) || s.code.Contains(keyword)));
            //#endregion
            //int recordCount = 0;

            //var filter = Builders<Sys_Work_Group>.Filter.And(listApp);
            //var list = await _sys_work_groupRepository.GetByPage(filter, pageindex, pagesize);
            //var redCount = await _sys_work_groupRepository.CountAsync(filter);   //获取总数

            //recordCount = int.Parse(redCount.ToString());

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

            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            var userinfo = _sys_user_accountRepository.GetUserInfo(nowusercode).ToJson().ToObject<UserInfoModel>();

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

        /// <summary>
        /// 获取班别
        /// </summary>
        /// <param name="id">班别id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public IActionResult GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = _sys_work_groupRepository.GetDetails(id);
            return Success("获取成功！", model);
        }

        /// <summary>
        /// 添加班别
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(WorkGroupInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入代码");
            #endregion

            var model = new Sys_Work_Group();
            model.projectid = input.projectid;
            model.name = input.name;
            model.code = input.code;
            model.starttime = input.starttime;
            model.endtime = input.endtime;
            model.remark = input.remark;
            model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.createbyname = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            model.createtime = DateTime.Now;
            if (await _sys_work_groupRepository.Add(model))
            {
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }

        /// <summary>
        /// 修改班别信息
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(WorkGroupInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.name))
                return Error("请输入名称");
            if (string.IsNullOrEmpty(input.code))
                return Error("请输入代码");
            #endregion

            var model = await _sys_work_groupRepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            model.projectid = input.projectid;
            model.name = input.name;
            model.code = input.code;
            model.starttime = input.starttime;
            model.endtime = input.endtime;
            model.remark = input.remark;
            bool b = await _sys_work_groupRepository.Update(model);
            if (b)
                return Success("修改成功");
            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 ml = await _sys_work_groupRepository.GetSingle(item);
                    //ml.isdelete = 1;
                    //ml.deletetime = DateTime.Now;
                    //ml.deleteby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

                    //if (_sys_work_groupRepository.Update(ml).Result)
                    //    res += 1;

                    if (await _sys_work_groupRepository.Remove(item))
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

    }
}