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 System.Security.Claims;
using SignTokenApi.IRepositories;
using SignTokenApi.Model.Input;
using MadRunFabric.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Configuration;
using SignTokenApi.Repositories;
using SignTokenApi.Areas.ThirdHospitals.Models.Input;

namespace SignTokenApi.Areas.ThirdHospitals.Controllers
{
    /// <summary>
    /// 排班管理 - 省三院
    /// </summary>
    [Area("ssy")]
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class ClassGroupUserController : BaseController
    {
        private readonly ILogger<ClassGroupUserController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_ClassGroup_User_MapRepository _sys_classGroup_user_maprepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public ClassGroupUserController(
            ILogger<ClassGroupUserController> logger,
            IConfiguration configuration,
            ISys_ClassGroup_User_MapRepository sys_classGroup_user_maprepository,
            ISys_User_AccountRepository sys_user_accountRepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_classGroup_user_maprepository = sys_classGroup_user_maprepository;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        /// <summary>
        /// 获取排班用户列表
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="listday"></param>
        /// <param name="card">1、默认card == 0，说明是排班；2、如果card>0，说明是打卡，显示是当前用户打卡</param>
        /// <returns></returns>
        [HttpGet("getusergrouplist")]
        public IActionResult GetClassGroupUserList(string projectid, string listday, int card = 0)
        {
            //, string usercode, string groupcode
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            var userinfo = _sys_user_accountRepository.GetUserInfo(nowusercode).ToJson().ToObject<UserInfoModel>();

            var result = _sys_classGroup_user_maprepository.GetClassGroupUserList(projectid, listday, card, userinfo);
            return Success("成功", result);
        }

        /// <summary>
        /// 获取当月排班标记
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="startdate"></param>
        /// <returns></returns>
        [HttpGet("getusergroupmarker")]
        public IActionResult GetClassGroupMarker(string projectid, string usercode)
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            var userinfo = _sys_user_accountRepository.GetUserInfo(nowusercode).ToJson().ToObject<UserInfoModel>();

            var result = _sys_classGroup_user_maprepository.GetClassGroupMarker(projectid, usercode, userinfo);
            return Success("成功", result);
        }

        /// <summary>
        /// 获取班次时间段上班的人员 - 今天
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="listday"></param>
        /// <param name="card">1、默认card == 0，说明是排班；2、如果card>0，说明是打卡，显示是当前用户打卡</param>
        /// <returns></returns>
        [HttpGet("getworkuserlistbyday")]
        public IActionResult GetWorkUserListByDay()
        {
            //, string usercode, string groupcode
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            var userinfo = _sys_user_accountRepository.GetUserInfo(nowusercode).ToJson().ToObject<UserInfoModel>();

            var result = _sys_classGroup_user_maprepository.GetWorkUserListByDay(userinfo);
            return Success("成功", result);
        }

        ///// <summary>
        ///// 获取班别详情 by id
        ///// </summary>
        ///// <param name="id"></param>
        ///// <returns></returns>
        //[HttpGet("getdetailes")]
        //public async Task<IActionResult> GetDetailsAsync(string id)
        //{
        //    if (string.IsNullOrEmpty(id))
        //        return Error("参数错误");
        //    var model = await _sys_classGroup_user_maprepository.GetSingle(id);
        //    if (model != null)
        //    {
        //        return Success("获取成功！", model);
        //    }
        //    return Error("获取失败");
        //}

        /// <summary>
        /// 保存排班用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("saveclassuser")]
        public async Task<IActionResult> SaveClassGroupUserAsync(ClassGroupUserMapInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            #region 验证判断
            if (string.IsNullOrEmpty(input.listday))
                return Error("请选中日期");
            if (input.listuserinfo == null && input.listuserinfo.Count <= 0)
                return Error("需要排班设置才能保存");

            var listMaps = (await _sys_classGroup_user_maprepository.Get(p => p.isdelete == 0 && p.projectid == input.projectid)).ToList();
            if (!string.IsNullOrEmpty(input.projectid))
                listMaps = listMaps.Where(x => x.projectid == input.projectid).ToList();
            #endregion
            int res = 0;
            string[] split = input.listday.Trim().Split(',');
            foreach (var itemday in split)
            {

                foreach (var item in input.listuserinfo)
                {
                    var listMaps_date = listMaps.Where(p => p.date == itemday).ToList();
                    foreach (var item_d in listMaps_date)
                    {
                        await _sys_classGroup_user_maprepository.Remove(item_d.id);
                    }

                   var userinfo = item;
                    var model = new Sys_ClassGroup_User_Map();
                    model.projectid = input.projectid;
                    model.usercode = userinfo.usercode;
                    //model.groupcode = userinfo.groupcode;
                    model.date = itemday;
                    model.isstatus = userinfo.isstatus;
                    model.classgroupList = userinfo.isstatus == (int)EnumClassGroupUserIsStatus.正常 ? userinfo.classgroupList : new List<ClassGroupList>();
                    model.isjoin = userinfo.isjoin;
                    model.distri_planList = userinfo.isjoin == true ? userinfo.distri_planList : new List<DistriPlanList>();
                    //model.remark = userinfo.remark;
                    model.isdelete = 0;
                    model.createtime = DateTime.Now;
                    model.createby = usercode;
                    model.createbyname = username;
                    if (await _sys_classGroup_user_maprepository.Add(model))
                        res += 1;
                }
            }
            //两个foreach循环
            int i = split.Length * input.listuserinfo.Count;
            if (res == i)
                return Success("保存成功");
            else if (res > 0 && res < i)
                return Error("部分保存失败，请查看后重新操作");
            else
                return Error("保存失败，请查看后重新操作");
        }

        /// <summary>
        /// 删除排班信息 by usercode
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletebyuserdate")]
        public async Task<IActionResult> RemoveAsync(string usercode, string date)
        {
            var ml = await _sys_classGroup_user_maprepository.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_classGroup_user_maprepository.Remove(ml.id))
                return Success("删除成功");
            return Error("删除失败");
        }

        /// <summary>
        /// 删除排班信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(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 _sys_classGroup_user_maprepository.GetSingle(item);
                    //ml.isdelete = 1;
                    //ml.deleteby = usercode;
                    //ml.deletetime = DateTime.Now.ToLocalTime();
                    //if (_sys_classGroup_user_maprepository.Update(ml).Result)
                    if (await _sys_classGroup_user_maprepository.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("请选择要删除的记录");
        }
    }
}