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

namespace SignTokenApi.Controllers
{
    /// <summary>
    /// 排班管理 - 普通排班（保洁，保安） - 公示系统展示
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class WorkClassUserController : BaseController
    {
        private readonly ILogger<WorkClassUserController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_Work_ClassGroup_User_MapRepository _sys_work_classgroup_user_maprepository;
        //private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        private readonly ISys_Work_ClassGroupRepository _sys_work_classgroupRepository;
        private readonly ISys_Work_UserRepository _sys_work_userRepository;
        private readonly ISys_DictionaryValueRepository _sys_dictionaryvalueRepository;
        public WorkClassUserController(
            ILogger<WorkClassUserController> logger,
            IConfiguration configuration,
            ISys_Work_ClassGroup_User_MapRepository sys_work_classgroup_user_maprepository,
            //ISys_User_AccountRepository sys_user_accountRepository,
            ISys_Work_ClassGroupRepository sys_work_classgroupRepository,
            ISys_Work_UserRepository sys_work_userRepository,
            ISys_DictionaryValueRepository sys_dictionaryvalueRepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_work_classgroup_user_maprepository = sys_work_classgroup_user_maprepository;
            _sys_work_classgroupRepository = sys_work_classgroupRepository;
            _sys_work_userRepository = sys_work_userRepository;
            _sys_dictionaryvalueRepository = sys_dictionaryvalueRepository;
        }

        /// <summary>
        /// 获取角色分类(角色，班次，用户)
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="startdate"></param>
        /// <returns></returns>
        [HttpGet("getclassanduserlist")]
        public async Task<IActionResult> GetClassAndUserListAsync(string projectid, string usertype)
        {
            //获取班次
            var list_class = await _sys_work_classgroupRepository.Get(x => x.isdelete == 0);
            //获取用户
            var list_user = await _sys_work_userRepository.Get(x => x.isdelete == 0);

            #region 条件查询
            if (!string.IsNullOrEmpty(projectid))
            {
                list_class = list_class.Where(x => x.projectid == projectid);
                list_user = list_user.Where(x => x.projectid == projectid);
            }
            //获取角色分类（字典）
            var list_usertype = list_user.Select(x => x.usertype).Distinct().ToList();
            var list_dic = await _sys_dictionaryvalueRepository.Get(x => list_usertype.Contains(x.id));
            #endregion

            var list = list_dic.Select(p =>
            {
                var list_c = list_class.Where(x => x.usertype == p.id).Select(s=> {
                    return new
                    {
                        s.code,
                        s.name,
                        s.starttime,
                        s.endtime
                    };
                });
                var list_u = list_user.Where(x => x.usertype == p.id).Select(s =>
                {
                    return new
                    {
                        s.id,
                        s.username
                    };
                });
                return new
                {
                    p.id,            //code
                    p.name,                 //角色
                    list_class = list_c,    //班别list
                    list_user = list_u      //用户list
                };
            });
            return Success("获取成功", list);
        }

        /// <summary>
        /// 获取排班标记
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="startdate"></param>
        /// <returns></returns>
        [HttpGet("getusermarker")]
        public IActionResult GetClassGroupMarker(string projectid, string usercode,string starttime,string endtime)
        {
            var result = _sys_work_classgroup_user_maprepository.GetWorkClassGroupUserMarker(projectid, usercode, starttime, endtime);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 添加排班用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("saveuser")]
        public async Task<IActionResult> SaveClassGroupUserAsync(WorkClassGroupUserMapInput 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.projectid))
                return Error("请选择项目");
            if (string.IsNullOrEmpty(input.usertype))
                return Error("请选择职务");
            if (string.IsNullOrEmpty(input.date.ToString()))
                return Error("请选择日期");
            if (input.userlist == null && input.userlist.Count <= 0)
                return Error("请选中员工");            
            #endregion
            var model = new Sys_Work_ClassGroup_User_Map();
            model.projectid = input.projectid;
            model.classcode = input.classcode;
            model.usertype = input.usertype;
            model.userlist = input.userlist;
            model.date = input.date;
            model.remark = input.remark;
            model.isdelete = 0;
            model.createby = usercode;
            model.createname = username;
            model.createtime = DateTime.Now;
            if (await _sys_work_classgroup_user_maprepository.Add(model))
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 修改排班用户
        /// </summary>
        /// <param name="id"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(WorkClassGroupUserMapInput input)
        {

            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            if (string.IsNullOrEmpty(input.id))
                return Error("参数错误");
            if (string.IsNullOrEmpty(input.date.ToString()))
                return Error("日期不能为空");
            var model = await _sys_work_classgroup_user_maprepository.GetSingle(input.id);
            if (model == null)
                return Error("参数错误!");
            model.date = input.date;
            bool b = await _sys_work_classgroup_user_maprepository.UpdateOne(model);
            if (b)
                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)
                {
                    if (await _sys_work_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("请选择要删除的记录");
        }

        #region 公示系统 - 省三院
        /// <summary>
        /// 获取当天排班信息 - 树形
        /// </summary>
        /// <param name="projectid"></param>
        /// <param name="code">字典编码</param>
        /// <returns></returns>
        [HttpGet("getuserlistbyday")]
        public IActionResult GetUserListByDayAsync(string projectid,string code)
        {
            var result = _sys_work_classgroup_user_maprepository.GetUserListByDay(projectid, code);
            return Success("获取成功", result);
        }
        #endregion

    }
}