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

namespace SignTokenApi.Controllers
{
    /// <summary>
    /// 用户班别
    /// </summary>
 //   [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class UserGroupController : BaseController
    {
        private readonly ILogger<UserGroupController> _logger;
        private readonly ISys_Work_UserGroupRepository _sys_work_usergroupRepository;
        private readonly ISys_Work_GroupRepository _sys_work_groupRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;

        private readonly ISys_Work_DayGroupRepository _sys_work_daygroupRepository;
        public UserGroupController(ILogger<UserGroupController> logger, ISys_Work_UserGroupRepository sys_work_usergroupRepository, 
            ISys_Work_GroupRepository sys_work_groupRepository, ISys_User_AccountRepository sys_user_accountRepository, ISys_Work_DayGroupRepository sys_work_daygroupRepository)
        {
            _logger = logger;
            _sys_work_usergroupRepository = sys_work_usergroupRepository;
            _sys_work_groupRepository = sys_work_groupRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
            _sys_work_daygroupRepository = sys_work_daygroupRepository;
        }

        /// <summary>
        /// 获取排班人员
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("getuserlist")]
        public IActionResult GetUserList(string projectid, string keyword)
        {
            var result = _sys_work_usergroupRepository.GetUserList(projectid, keyword);

            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取班别
        /// </summary>
        /// <param name="keyword"></param>
        /// <returns></returns>
        [HttpGet("getgrouplist")]
        public async Task<IActionResult> GetGroupList(string projectid, string keyword)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_Work_Group>.Sort.Ascending("sort");

            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_Work_Group>>();
            listApp.Add(Builders<Sys_Work_Group>.Filter.Eq("isdelete", 0));
            if (!string.IsNullOrEmpty(projectid))
                listApp.Add(Builders<Sys_Work_Group>.Filter.Where(s => s.projectid == projectid));
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_Work_Group>.Filter.Where(s => s.name.Contains(keyword) || s.code.Contains(keyword)));
            #endregion

            var filter = Builders<Sys_Work_Group>.Filter.And(listApp);
            var list = await _sys_work_groupRepository.Get(filter);

            return Success("获取成功", list);
        }

        /// <summary>
        /// 获取排班详情
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="startdate"></param>
        /// <param name="enddate"></param>
        /// <param name="usercode"></param>
        /// <param name="groupcode"></param>
        /// <returns></returns>
        [HttpGet("getusergrouplist")]
        public IActionResult GetUserGroupList(string projectid, string startdate, string enddate, string usercode, string groupcode)
        {
            var result = _sys_work_usergroupRepository.GetUserGroupList(projectid,startdate, enddate, usercode, groupcode);
            return Success("成功", result);
        }

        /// <summary>
        /// 获取用户排班详情
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet("getusergroupinfo")]
        public IActionResult GetUserGroupInfo(string usercode, string date)
        {
            var result = _sys_work_usergroupRepository.GetUserGroupInfo(usercode, date);
            return Success("成功", result);
        }

        /// <summary>
        /// 获取用户班别
        /// </summary>
        /// <param name="id">用户班别id</param>
        /// <returns></returns>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingleAsync(string usercode, string date)
        {
            var model = await _sys_work_usergroupRepository.GetSingle(p => p.usercode == usercode && p.date == date && p.isdelete == 0);
            if (model != null)
                return Success("获取成功！", model);

            return Error("获取失败");
        }

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

            var model = await _sys_work_usergroupRepository.GetSingle(id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", model);
        }

        /// <summary>
        /// 设置用户班别
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("setusergroup")]
        public async Task<IActionResult> SetUserGroupAsync(string usercode, string groupcode, string date)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(usercode))
                return Error("用户不能为空");
            if (string.IsNullOrEmpty(date))
                return Error("日期不能为空");
            #endregion

            var model = await _sys_work_usergroupRepository.GetSingle(p => p.usercode == usercode && p.date == date && p.isdelete == 0);
            if (model != null)
            {
                model.usercode = usercode;
                model.groupcode = groupcode;
                model.date = date;

                if (await _sys_work_usergroupRepository.Update(model))
                    return Success("设置成功");
                return Error("设置失败");
            }
            else
            {
                model = new Sys_Work_UserGroup();
                model.usercode = usercode;
                model.groupcode = groupcode;
                model.date = date;
                model.isdelete = 0;
                model.createtime = DateTime.Now;
                model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                model.createbyname = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

                if (await _sys_work_usergroupRepository.Add(model))
                    return Success("设置成功");
                return Error("设置失败");
            }
        }

        /// <summary>
        /// 删除用户班别信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> RemoveAsync(string usercode, string date)
        {
            var ml = await _sys_work_usergroupRepository.GetSingle(p => p.usercode == usercode && p.date == date && p.isdelete == 0);
            //ml.isdelete = 1;
            //ml.deletetime = DateTime.Now;
            //ml.deleteby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //if (await _sys_work_usergroupRepository.Update(ml))
            if (await _sys_work_usergroupRepository.Remove(ml.id))
                return Success("删除成功");
            return Error("删除失败");
        }

        /// <summary>
        /// 删除用户班别信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletes")]
        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_usergroupRepository.GetSingle(item);
                    //ml.isdelete = 1;
                    //ml.deletetime = DateTime.Now;
                    //ml.deleteby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    //if (await _sys_work_usergroupRepository.Update(ml))
                    //    res += 1;

                    if (await _sys_work_usergroupRepository.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("请选择要删除的记录");
        }


    //    [Authorize]
        [HttpPost("addschedual")]
        public async Task<IActionResult> AddAsync(string keshiname, string data, string usercode,string grouptype)
        {
            try
            {
                Sys_Work_DayGroup wdmodel = new Sys_Work_DayGroup();
                wdmodel.usercode = usercode;
                wdmodel.date = data;
                wdmodel.groupcode = grouptype;
                wdmodel.createby= "8000";//User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value; //
                wdmodel.createbyname = "内测账户";// User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
                wdmodel.keshiName = keshiname;

                var res = false;
                
                res = await _sys_work_daygroupRepository.Add(wdmodel);


                if (res)
                    return Success("排班保存成功");
                else
                    return Error("排班保存失败");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "排班保存成功");
                return Error("排班保存成功");
            }
        }


        [HttpGet("getgroupslistsbypage")]
        public IActionResult GetGroupsListsByPage(string grouptype, string usercode, int pageindex = 1, int pagesize = 10)
        {

            int recordCount = 0;
            var result = _sys_work_daygroupRepository.GetGroupList(usercode, grouptype, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }


        [HttpPost("updateusergroup")]
        public async Task<IActionResult> UpdateAsync(DayGroupInput input)
        {

            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
           
            var model = await _sys_work_daygroupRepository.GetSingle(input.id);
            if (model == null)
                return Error("参数错误");

            model.id = input.id;
            model.keshiName = input.keshiname;
            model.groupcode = input.grouptype;
            model.date = input.date;
            model.usercode = input.usercode;

            model.createby = usercode;
            model.createbyname = username;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_work_daygroupRepository.Update(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }


        public class DayGroupInput
        {
            public string id { get; set; }
            public string usercode { get; set; }

            public string keshiname { get; set; }

            public string date { get; set; }

            public string grouptype { get; set; }
        }
    
    }
}