using System.Collections.Generic;
using System.Linq;
using Edu.Cache.User;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.ViewModel.Duty;
using Edu.Module.Duty;
using Edu.Module.User;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;

namespace Edu.WebApi.Controllers.Duty
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class DutyController : BaseController
    {
        /// <summary>
        /// 值班配置处理类对象
        /// </summary>
        public readonly DutyModule dutyModule = new DutyModule();

        /// <summary>
        /// 校区处理类对象
        /// </summary>
        public readonly SchoolModule schoolModule = new SchoolModule();

        #region 班次管理

        /// <summary>
        /// 获取班次分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyFrequencyPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Duty_Frequency_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Name=base.ParmJObj.GetStringValue("Name"),
            };
            query.SchoolIdList = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(base.ParmJObj.GetStringValue("School_Ids"));
            var list = dutyModule.GetDutyFrequencyPageModule(pageModel.PageIndex, pageModel.PageSize, out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                item.SchoolName = item.SchoolName.Replace(',', '|');
            }
            pageModel.PageData = list;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 获取班次列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyFrequencyList()
        {
            var query = new RB_Duty_Frequency_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Name = base.ParmJObj.GetStringValue("Name"), 
            };
            query.SchoolIdList = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(base.ParmJObj.GetStringValue("School_Ids"));
            var list = dutyModule.GetDutyFrequencyListModule(query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                item.SchoolName = item.SchoolName.Replace(',', '|');
            }
            return ApiResult.Success(data: list);
        }

        /// <summary>
        /// 获取班次列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyFrequencyModel()
        {
            var query = new RB_Duty_Frequency_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Id = base.ParmJObj.GetInt("Id"),
            };
            if (query.Id == 0)
            {
                return ApiResult.Failed("请传入班次Id");
            }
            var model = dutyModule.GetDutyFrequencyListModule(query).FirstOrDefault();
            if (model == null || model.Id <= 0)
            {
                return ApiResult.Failed("数据不存在");
            }
            if (model.CreateBy > 0)
            {
                model.CreateByName = UserReidsCache.GetUserLoginInfo(model.CreateBy)?.AccountName ?? "";
            }
            model.SchoolName = model.SchoolName.Replace(',', '|');
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 新增修改班次
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSetFrequency()
        {
            var query = new RB_Duty_Frequency_ViewModel()
            {
                Name = base.ParmJObj.GetStringValue("Name"),
                StartTime = base.ParmJObj.GetStringValue("StartTime"),
                EndTime = base.ParmJObj.GetStringValue("EndTime"),
                School_Ids = base.ParmJObj.GetStringValue("School_Ids"),
                Group_Id = base.UserInfo.Group_Id,
                Id = base.ParmJObj.GetInt("Id"),
            };
            if (string.IsNullOrWhiteSpace(query.Name))
            {
                return ApiResult.Failed("请输入班次名称");
            }
            if (string.IsNullOrWhiteSpace(query.StartTime))
            {
                return ApiResult.Failed("请选择班次开始时间");
            }
            if (string.IsNullOrWhiteSpace(query.EndTime))
            {
                return ApiResult.Failed("请选择班次结束时间");
            }
            if (string.IsNullOrWhiteSpace(query.School_Ids))
            {
                return ApiResult.Failed("请选择班次对应的学校");
            }
            if (query.Id == 0)
            {
                query.CreateBy = base.UserInfo.Id;
                query.CreateTime = System.DateTime.Now;
            }
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            bool retult = dutyModule.SetFrequencyModule(query);
            return retult ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除班次
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveFrequency()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var flag = dutyModule.RemoveFrequencyModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        #endregion

        #region 值班事项
        /// <summary>
        /// 获取班次列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyItemPage()
        {
            var pageModel = Common.Plugin.JsonHelper.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            var query = new RB_Duty_Item_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                ItemName=base.ParmJObj.GetStringValue("ItemName"),
                DutyCategory=base.ParmJObj.GetInt("DutyCategory"),
            };
            query.ItemSchoolList = Common.Plugin.JsonHelper.DeserializeObject<List<int>>(base.ParmJObj.GetStringValue("ItemSchools"));
            var list = dutyModule.GetDutyItemPageModule(pageModel.PageIndex,pageModel.PageSize,out long rowsCount, query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                item.SchoolName = item.SchoolName.Replace(',', '|');
            }
            pageModel.PageData = list;
            pageModel.Count = rowsCount;
            return ApiResult.Success(data: pageModel);
        }


        /// <summary>
        /// 获取值班事项详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyItemModel()
        {
            var query = new RB_Duty_Item_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Id = base.ParmJObj.GetInt("Id"),
            };
            if (query.Id == 0)
            {
                return ApiResult.Failed("请传入值班事项Id");
            }
            var model = dutyModule.GetDutyItemListExtModule(query).FirstOrDefault();
            if (model == null || model.Id <= 0)
            {
                return ApiResult.Failed("数据不存在");
            }
            if (model.CreateBy > 0)
            {
                model.CreateByName = UserReidsCache.GetUserLoginInfo(model.CreateBy)?.AccountName ?? "";
            }
            model.SchoolName = model.SchoolName.Replace(',', '|');
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 新增修改值班事项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDutyItem()
        {
            var query = new RB_Duty_Item_ViewModel()
            {
                ItemName = base.ParmJObj.GetStringValue("ItemName"),
                ItemSchools = base.ParmJObj.GetStringValue("ItemSchools"),
                ItemType = (Common.Enum.Duty.ItemTypeEnum)base.ParmJObj.GetInt("ItemType"),
                Shifts = base.ParmJObj.GetStringValue("Shifts"),
                Group_Id = base.UserInfo.Group_Id,
                Id = base.ParmJObj.GetInt("Id"),
                DutyCategory = base.ParmJObj.GetInt("DutyCategory"),
                DutyType = base.ParmJObj.GetInt("DutyType"),
            };
            query.ItemImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(base.ParmJObj.GetStringValue("ItemImgList"));
            if (query.ItemImgList != null && query.ItemImgList.Count > 0)
            {
                query.ItemImg = Common.Plugin.JsonHelper.Serialize(query.ItemImgList);
            }
            else
            {
                query.ItemImg = "";
            }
            if (string.IsNullOrWhiteSpace(query.Shifts))
            {
                return ApiResult.Failed("请选择班次");
            }
            if (string.IsNullOrWhiteSpace(query.ItemSchools))
            {
                return ApiResult.Failed("请选择值班事项对应的学校");
            }
            if (query.DutyCategory == 0)
            {
                return ApiResult.Failed("请选择分类!");
            }
            if (query.DutyType == 0)
            {
                return ApiResult.Failed("请选择类型!");
            }
            if (string.IsNullOrWhiteSpace(query.ItemName))
            {
                return ApiResult.Failed("请输入值班事项名称");
            }
            if (query.DutyCategory == 1 && query.DutyType == 2 && base.ParmJObj.GetInt("ItemType") == 0)
            {
                return ApiResult.Failed("请选择事项类型填写方式!");
            }
            query.CreateBy = base.UserInfo.Id;
            query.CreateTime = System.DateTime.Now;
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            bool retult = dutyModule.SetDutyItemModule(query);
            return retult ? ApiResult.Success("") : ApiResult.Failed("");
        }


        /// <summary>
        /// 根据编号获取值班事项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyItem()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var model = dutyModule.GetDutyItemModule(Id);
            var obj = new object();
            if (model != null && model.Id > 0)
            {
                List<string> SchoolList = new List<string>();
                List<string> ShiftList = new List<string>();
                List<string> ImgList = new List<string>();
                if (!string.IsNullOrEmpty(model?.ItemSchools))
                {
                    SchoolList = Common.ConvertHelper.StringToFileList(model?.ItemSchools);
                }
                if (!string.IsNullOrEmpty(model?.Shifts))
                {
                    ShiftList = Common.ConvertHelper.StringToFileList(model?.Shifts);
                }
                if (!string.IsNullOrEmpty(model?.ItemImg))
                {
                    ImgList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(model.ItemImg);
                }
                obj = new
                {
                    model.Id,
                    model?.ItemName,
                    ItemType = (model?.ItemType ?? 0),
                    model?.ItemSchools,
                    SchoolList,
                    model?.Shifts,
                    ShiftList,
                    ItemImgList= ImgList,
                    model?.DutyType,
                    model?.DutyCategory,
                };
            }
            return ApiResult.Success(data: obj);
        }


        /// <summary>
        /// 删除值班事项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveDutyItem()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var flag = dutyModule.RemoveItemModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 根据班次获取学校信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSchoolListByFrequencyIds()
        {
            var Shifts = base.ParmJObj.GetStringValue("Shifts");
            var list = schoolModule.GetSchoolListByFrequencyIds(base.UserInfo.Group_Id, Shifts);
            var result = list.Select(x => new
            {
                x.SId,
                x.SName
            });
            return ApiResult.Success(data: result);
        }
        /// <summary>
        /// 根据学校获取班次信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyFrequencyBySchoolIds()
        {
            var SchoolIds = base.ParmJObj.GetStringValue("SchoolIds");
            var list = dutyModule.GetDutyFrequencyBySchoolIdsModule(base.UserInfo.Group_Id, SchoolIds);
            var result = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.StartTime,
                x.EndTime,
            });
            return ApiResult.Success(data: result);
        }


        /// <summary>
        /// 获取值班事项类型列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetItemTypeEnumList()
        {
            var list = Common.Plugin.EnumHelper.EnumToList(typeof(Common.Enum.Duty.ItemTypeEnum));

            return ApiResult.Success(data: list);
        }

        #endregion

        #region 值班设置管理
        /// <summary>
        /// 获取设置列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyConfigList()
        {
            var query = new RB_Duty_Config_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                School_Id = base.ParmJObj.GetInt("School_Id"),
            };
            var list = dutyModule.GetDutyConfigModule(query);
            foreach (var item in list)
            {
                if (item.CreateBy > 0)
                {
                    item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                }
                item.ShiftsName = item.ShiftsName.Replace(',', '|');
            }
            return ApiResult.Success(data: list);
        }


        /// <summary>
        /// 获取值班设置详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDutyConfigModel()
        {
            var query = new RB_Duty_Config_ViewModel()
            {
                Group_Id = base.UserInfo.Group_Id,
                Id = base.ParmJObj.GetInt("Id"),
            };
            if (query.Id == 0)
            {
                return ApiResult.Failed("请传入值班设置Id");
            }
            var model = dutyModule.GetDutyConfigModule(query).FirstOrDefault();
            if (model == null || model.Id <= 0)
            {
                return ApiResult.Failed("数据不存在");
            }
            if (model.CreateBy > 0)
            {
                model.CreateByName = UserReidsCache.GetUserLoginInfo(model.CreateBy)?.AccountName ?? "";
            }
            model.ShiftsName = model.ShiftsName.Replace(',', '|');
            return ApiResult.Success(data: model);
        }

        /// <summary>
        /// 获取设置列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDutyConfig()
        {
            var query = new RB_Duty_Config_ViewModel()
            {
                EmployeeIds = base.ParmJObj.GetStringValue("EmployeeIds"),
                School_Id = base.ParmJObj.GetInt("School_Id"),
                MachineCode = base.ParmJObj.GetStringValue("MachineCode"),
                Shifts = base.ParmJObj.GetStringValue("Shifts"),
                Group_Id = base.UserInfo.Group_Id,
                Id = base.ParmJObj.GetInt("Id"),
                SendEmployeeIds=base.ParmJObj.GetStringValue("SendEmployeeIds"),
            };
            if (string.IsNullOrWhiteSpace(query.EmployeeIds))
            {
                return ApiResult.Failed("请选择员工");
            }
            if (string.IsNullOrWhiteSpace(query.Shifts))
            {
                return ApiResult.Failed("请选择班次");
            }
            if (string.IsNullOrWhiteSpace(query.MachineCode))
            {
                return ApiResult.Failed("请输入值班机器码");
            }
            var oldList = dutyModule.GetDutyConfigListModule(new RB_Duty_Config_ViewModel { Group_Id = base.UserInfo.Group_Id, MachineCode = query.MachineCode });
            if (oldList != null && oldList.Any(x => x.Id != query.Id))
            {
                return ApiResult.Failed("机器码已存在");
            }
            if (query.Id == 0)
            {
                query.CreateBy = base.UserInfo.Id;
                query.CreateTime = System.DateTime.Now;
            }
            query.UpdateBy = base.UserInfo.Id;
            query.UpdateTime = System.DateTime.Now;
            if (dutyModule.CheckDutyConfigModule(query))
            {
                return ApiResult.Failed("已经存在该校区的配置数据!");
            }
            bool retult = dutyModule.SetDutyConfigModule(query);
            return retult ? ApiResult.Success("值班设置成功") : ApiResult.Failed("值班设置失败");
        }

        /// <summary>
        /// 删除值班设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult RemoveDutyConfig()
        {
            var Id = base.ParmJObj.GetInt("Id", 0);
            var flag = dutyModule.RemoveConfigModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion
    }
}