using APT.Infrastructure.Core;
using APT.BaseData.Domain.Entities.FM;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using APT.BaseData.Domain.IServices.FM;

using APT.Utility;
using APT.BaseData.Domain.Entities.BD;
using System.Linq;
using APT.BaseData.Domain.Enums;
using System;
using System.Linq.Expressions;

namespace APT.FM.WebApi.Controllers.Api.FM
{
    /// <summary>
    ///  部门排班表
    /// </summary>
    [Route("api/FM/DepartmentScheduling")]
    public partial class DepartmentSchedulingController : AuthorizeApiController<T_FM_DEPARTMENT_SCHEDULING>
    {

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_DEPARTMENT_SCHEDULING entity)
        {
            return SafeExecute<bool>(() =>
            {

                if (entity == null || !entity.Nav_DepartmentSchedulingDetail.Any(i => !i.IS_DELETED))
                {
                    this.ThrowError("040004");
                }
                var detail = entity.Nav_DepartmentSchedulingDetail;
                var repeatPersonIds = detail.Where(t => t.IS_DELETED == false).GroupBy(x => x.PERSON_ID).Where(x => x.Count() > 1).Select(t => t.Key);
                if (repeatPersonIds.Any())
                {
                    BaseFilter baseFilter = new BaseFilter(entity.ORG_ID);
                    baseFilter.SelectField = new string[] { "NAME" };
                    var repeatPersonNames = GetEntities<T_FM_PERSON>(t => repeatPersonIds.Contains(t.ID), baseFilter);
                    string repeatNames = string.Join(",", repeatPersonNames.Select(i => i.NAME));
                    throw new Exception(repeatNames + "重复,不允许重复添加人员!");
                }
                entity.Nav_DepartmentSchedulingDetail = null;
                UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                    this.BantchSaveEntityNoCommit(detail);
                });
                return true;
            });
        }
        /// <summary>
        /// 保存配置信息
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        [HttpPost, Route("ClearRun")]
        public JsonActionResult<bool> ClearRun([FromBody] KeywordFilter filter)
        {
            return SafeExecute<bool>(() =>
            {
                var baseConfig = this.GetEntityByRedis<T_FM_BASE_CONFIG>(filter.GetOrgId().ToString(), filter.GetOrgId());
                if (baseConfig == null)
                    this.ThrowError("010002");
                //清除数据后重新生成
                if (!string.IsNullOrWhiteSpace(filter.Keyword))
                {
                    var configIds = filter.Parameter1?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(i => Guid.Parse(i));
                    Expression<Func<T_FM_DEPARTMENT_CALENDAR_CONFIG, bool>> express = i => i.DEPARTMENT_ID == new Guid(filter.Keyword)
               && i.ENABLE_STATUS == (int)FMEnableStatusEnum.启用 && i.END_TIME > DateTime.Now;
                    if (configIds.Any())
                    {
                        express = express.And(i => configIds.Contains(i.ID));
                    }
                    var departmentConfig = this.GetEntities<T_FM_DEPARTMENT_CALENDAR_CONFIG>(express, new BaseFilter(filter.GetOrgId()));
                    if (departmentConfig != null && departmentConfig.Any())
                    {
                        departmentConfig.ForEach(x => x.CURR_TIME = DateTime.Now.Date.AddDays(1));
                    }
                    this.UnifiedCommit(() =>
                    {
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING_DETAIL>(i => i.Nav_DepartmentScheduling.DEPARTMENT_ID == new Guid(filter.Keyword)
                   && configIds.Contains(i.Nav_DepartmentScheduling.DEPARTMENT_CALENDAR_CONFIG_ID.Value) && i.Nav_DepartmentScheduling.DATE_TIME > DateTime.Now);
                        this.DeleteEntityNoCommit<T_FM_DEPARTMENT_SCHEDULING>(i => i.DEPARTMENT_ID == new Guid(filter.Keyword)
                        && configIds.Contains(i.DEPARTMENT_CALENDAR_CONFIG_ID.Value) && i.DATE_TIME > DateTime.Now);
                        if (departmentConfig != null && departmentConfig.Any())
                        {
                            this.BantchUpdateEntityNoCommit(departmentConfig);
                        }
                    });
                }

                return true;
            });
        }

    }
}
