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 APT.BaseData.Domain.Entities;
using APT.Infrastructure.Api.Redis;
using APT.BaseData.Domain.ApiModel.Platform;

namespace APT.FM.WebApi.Controllers.Api.FM
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/FM/FMNotificationTaskTimeSet")]
    public class FMNotificationTaskTimeSetController : AuthorizeApiController<T_FM_NOTIFICATION_TASK_TIME_SET>
    {
        /// <summary>
        /// 批量设置
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdateList")]
        public JsonActionResult<bool> FullUpdateList([FromBody] T_FM_NOTIFICATION_TASK_TIME_SET entity)
        {
            return SafeExecute<bool>(() =>
            {
                if (string.IsNullOrEmpty(entity.STRTASK_TYPE))
                {
                    throw new Exception("请选择待办类型！");
                }

                #region     格式 数据 判断

                if (entity.TIME_TYPE == FMTIMETYPE.Frequency)
                {
                    //嵌套业务自己的信息 此处无需处理
                }
                else if (entity.TIME_TYPE == FMTIMETYPE.DateLimit)
                {
                    if (string.IsNullOrEmpty(entity.LIMITDATE))
                    {
                        throw new Exception("请填写限制日期！");
                    }
                    else
                    {
                        try
                        {
                            Convert.ToDateTime(DateTime.Now.Year + "-" + entity.LIMITDATE);
                        }
                        catch
                        {
                            throw new Exception("限制日期格式错误【MM-dd】！");
                        }
                    }
                }
                else if (entity.TIME_TYPE == FMTIMETYPE.DayLimit)
                {
                    if (!entity.DAYDELAY.HasValue)
                    {
                        throw new Exception("请填写【限制天数】！");
                    }
                    else if (entity.DAYDELAY.Value <= 0)
                    {
                        throw new Exception("限制天数必须大于0！");
                    }
                }
                else if (entity.TIME_TYPE == FMTIMETYPE.DayDateLimit)
                {
                    if (!entity.DAYDELAY.HasValue)
                    {
                        throw new Exception("请填写【限制天数】！");
                    }
                    else if (entity.DAYDELAY.Value <= 0)
                    {
                        throw new Exception("限制天数必须大于0！");
                    }
                }

                #endregion

                // STRTASK_TYPE _1_3_5_7_
                string[] TASK_TYPE = entity.STRTASK_TYPE.Split('_', StringSplitOptions.RemoveEmptyEntries);
                List<FMTASKTYPE> listTaskType = new List<FMTASKTYPE>();
                foreach (var item in TASK_TYPE)
                {
                    try
                    {
                        listTaskType.Add((FMTASKTYPE)int.Parse(item));
                    }
                    catch
                    {
                        throw new Exception("待办类型转换出错【" + item + "】！");
                    }
                }
                var listTaskSet = GetEntities<T_FM_NOTIFICATION_TASK_TIME_SET>(e => !e.IS_DELETED && listTaskType.Contains(e.TASK_TYPE), null, null);

                if (listTaskSet != null && listTaskSet.Any())
                {
                    string TASK_TYPESet = string.Empty;
                    listTaskSet.ForEach(e =>
                    {
                        TASK_TYPESet = "，" + e.TASK_TYPE.GetDescription();
                    });
                    throw new Exception("待办类型【" + TASK_TYPESet.Substring(1) + "】不能重复配置！");
                }
                List<T_FM_NOTIFICATION_TASK_TIME_SET> listAdd = new List<T_FM_NOTIFICATION_TASK_TIME_SET>();
                foreach (var item in listTaskType)
                {
                    listAdd.Add(new T_FM_NOTIFICATION_TASK_TIME_SET()
                    {
                        ID = Guid.NewGuid(),
                        ORG_ID = entity.ORG_ID,
                        CREATER_ID = entity.CREATER_ID,
                        CREATE_TIME = entity.CREATE_TIME,

                        CODE = item.GetString(),
                        NAME = item.GetDescription(),
                        TASK_TYPE = item,
                        TIME_TYPE = entity.TIME_TYPE,
                        DAYDELAY = entity.DAYDELAY,
                        TABLENAME = entity.TABLENAME,
                        TABLEKEY = entity.TABLEKEY,
                        TABLETIME = entity.TABLETIME,
                        ROW_NO = entity.ROW_NO == 0 ? item.GetInt() : entity.ROW_NO,
                        LIMITDATE = entity.LIMITDATE,
                        ENABLE_STATUS = 0,
                    });
                }
                this.UnifiedCommit(() =>
                {
                    if (listAdd != null && listAdd.Any())
                        this.BantchSaveEntityNoCommit(listAdd);
                });

                if (entity.ORG_ID.HasValue)
                {
                    RedisSave(entity.ORG_ID.Value);
                }
                return true;
            });
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost, Route("FullUpdate")]
        public JsonActionResult<bool> FullUpdate([FromBody] T_FM_NOTIFICATION_TASK_TIME_SET entity)
        {
            return SafeExecute<bool>(() =>
            {
                #region     格式 数据 判断

                if (entity.TIME_TYPE == FMTIMETYPE.Frequency)
                {
                    //嵌套业务自己的信息 此处无需处理
                }
                else if (entity.TIME_TYPE == FMTIMETYPE.DateLimit)
                {
                    if (string.IsNullOrEmpty(entity.LIMITDATE))
                    {
                        throw new Exception("请填写限制日期！");
                    }
                    else
                    {
                        try
                        {
                            Convert.ToDateTime(DateTime.Now.Year + "-" + entity.LIMITDATE);
                        }
                        catch
                        {
                            throw new Exception("限制日期格式错误【MM-dd】！");
                        }
                    }
                }
                else if (entity.TIME_TYPE == FMTIMETYPE.DayLimit)
                {
                    if (!entity.DAYDELAY.HasValue)
                    {
                        throw new Exception("请填写【限制天数】！");
                    }
                    else if (entity.DAYDELAY.Value <= 0)
                    {
                        throw new Exception("限制天数必须大于0！");
                    }
                }
                else if (entity.TIME_TYPE == FMTIMETYPE.DayDateLimit)
                {
                    if (!entity.DAYDELAY.HasValue)
                    {
                        throw new Exception("请填写【限制天数】！");
                    }
                    else if (entity.DAYDELAY.Value <= 0)
                    {
                        throw new Exception("限制天数必须大于0！");
                    }
                }

                #endregion

                var check = GetEntity<T_FM_NOTIFICATION_TASK_TIME_SET>(e => !e.IS_DELETED && e.TASK_TYPE == entity.TASK_TYPE && e.ID != entity.ID, "");

                if (check != null && check.ID != Guid.Empty)
                {
                    throw new Exception("此待办类型不能重复配置！");
                }

                this.UnifiedCommit(() =>
                {
                    this.UpdateEntityNoCommit(entity);
                });
                if (entity.ORG_ID.HasValue)
                {
                    RedisSave(entity.ORG_ID.Value);
                }
                return true;
            });
        }

        /// <summary>
        /// 更新Redis
        /// </summary>
        /// <param name="OrgId"></param>
        private void RedisSave(Guid OrgId)
        {
            bool isRedisConfig = true;
            var redisConfig = APT.Infrastructure.Api.ConfigurationManager.AppSettings["RedisFormConfig"];
            if (!string.IsNullOrEmpty(redisConfig))
                isRedisConfig = bool.Parse(redisConfig);
            if (isRedisConfig)
            {
                var redisCode = string.Format(RedisCacheKey.TaskTimeSet, OrgId);
                var listSet = GetEntities<T_FM_NOTIFICATION_TASK_TIME_SET>(e => 1 == 1, null, null).ToList();
                CsRedisManager.StringSet<List<T_FM_NOTIFICATION_TASK_TIME_SET>>(redisCode, listSet);
            }
        }
    }
}
