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

namespace CallCenterApi.Controllers.systemmanagement
{
    /// <summary>
    /// 上班时间段控制器
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class SysWorkTimesController : BaseController
    {
        private readonly ILogger<SysWorkTimesController> _logger;
        private readonly ISys_WorkTimesRepository _sys_worktimesRepository;

        public SysWorkTimesController(ILogger<SysWorkTimesController> logger, ISys_WorkTimesRepository sys_worktimesRepository)
        {
            _logger = logger;
            _sys_worktimesRepository = sys_worktimesRepository;
        }

        /// <summary>
        /// 获取上班时间段列表
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPage(string key,string groupcode, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _sys_worktimesRepository.GetListsByPage(groupcode,key, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);
            #region
            ////排序字段
            //var sort = Builders<Sys_WorkTimes>.Sort.Descending("createtime");

            ////根据条件查询集合
            //var flist = new List<FilterDefinition<Sys_WorkTimes>>();
            //flist.Add(Builders<Sys_WorkTimes>.Filter.Eq("isdelete", false));

            //if (!string.IsNullOrWhiteSpace(key))
            //    flist.Add(Builders<Sys_WorkTimes>.Filter.Where(s =>s.remark.Contains(key)));
            //if (!string.IsNullOrWhiteSpace(groupcode))
            //    flist.Add(Builders<Sys_WorkTimes>.Filter.Where(s => s.groupcode.Contains(groupcode)));

            //var filter = Builders<Sys_WorkTimes>.Filter.And(flist);
            //var list = await _sys_worktimesRepository.GetByPage(filter, pageindex, pagesize, sort);
            //var count = await _sys_worktimesRepository.CountAsync(filter);
            //var obj = new
            //{
            //    state = "success",
            //    message = "根据条件获取分页数据成功",
            //    rows = list,
            //    total = count,
            //};
            //return Content(obj.ToJson());
            #endregion
        }

        /// <summary>
        /// 获取实体
        /// </summary>
        [HttpGet("getsingle")]
        public async Task<IActionResult> GetSingle(string id)
        {
            var dModel = _sys_worktimesRepository.GetDetails(id.Trim());

            if (dModel != null)
            {
                return Success("获取上班时间段成功", dModel);
            }
            else
            {
                return Error("获取上班时间段失败");
            }
        }

        /// <summary>
        /// 添加上班时间段
        /// </summary>
        [HttpPost("add")]
        public async Task<IActionResult> Add(string workstart, string workend, string groupcode,int type, string remark)
        {
            if (string.IsNullOrWhiteSpace(workstart))
                return Error("开始时间不能为空");
            if (string.IsNullOrWhiteSpace(workend))
                return Error("结束时间不能为空");
            Sys_WorkTimes clmodel = new Sys_WorkTimes();
            clmodel.workstarttimes = workstart;
            clmodel.workendtimes = workend;
            clmodel.groupcode = groupcode.Trim();
            clmodel.type = type;
            clmodel.remark = remark;
            clmodel.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            clmodel.createtime = DateTime.Now.ToLocalTime();
            clmodel.isdelete = false;

            var res = await _sys_worktimesRepository.Add(clmodel);
            if (res)
                return Success("上班时间段保存成功");
            else
            {
                return Error("上班时间段保存失败");
            }
        }

        /// <summary>
        /// 修改上班时间段
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> Edit(string id, string workstart, string workend, string groupcode, int type, string remark)
        {
            if (string.IsNullOrWhiteSpace(workstart))
                return Error("开始时间不能为空");
            if (string.IsNullOrWhiteSpace(workend))
                return Error("结束时间不能为空");
            var clmodel = await _sys_worktimesRepository.GetSingle(id);
            if (clmodel != null)
            {
                clmodel.workstarttimes = workstart;
                clmodel.workendtimes = workend;
                clmodel.groupcode = groupcode.Trim();
                clmodel.type = type;
                clmodel.remark = remark;

                var res = await _sys_worktimesRepository.Update(clmodel);
                if (res)
                    return Success("上班时间段保存成功");
                else
                {
                    return Error("上班时间段保存失败");
                }
            }
            else
            {
                return Error("上班时间段保存失败");
            }
        }

        [HttpPost("delete")]
        public async Task<IActionResult> Remove(string[] ids)
        {
            //使用逻辑删除
            //物理删除的数据无法恢复
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_worktimesRepository.GetSingle(item);
                    ml.isdelete = true;
                    if (await _sys_worktimesRepository.Update(ml))
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }
    }
}