
using Tiobon.Core.IServices;
using Tiobon.Core.Model.Models;
using Tiobon.Core.Services.BASE;
using Tiobon.Core.IRepository.Base;
using Tiobon.Core.Common.Caches;
using Tiobon.Core.Common.DB.Dapper.Extensions;
using Microsoft.EntityFrameworkCore.SqlServer.Query.Internal;

namespace Tiobon.Core.Services
{
	/// <summary>
	/// 考核期间 (服务)
	/// </summary>
    public class Ghrp_PerformancePeriodServices : BaseServices<Ghrp_PerformancePeriod, Ghrp_PerformancePeriodDto, InsertGhrp_PerformancePeriodInput, EditGhrp_PerformancePeriodInput>, IGhrp_PerformancePeriodServices
    {
        private readonly IBaseRepository<Ghrp_PerformancePeriod> _dal;
        public Ghrp_PerformancePeriodServices(ICaching caching, IBaseRepository<Ghrp_PerformancePeriod> dal)
        {
            this._dal = dal;
            base.BaseDal = dal;
            base._caching = caching;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="filter"></param>
        /// <param name="condition"></param>
        /// <param name="IsEnable"></param>
        /// <returns></returns>
        public override async Task<ServicePageResult<Ghrp_PerformancePeriodDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
        {

            var result = await base.QueryFilterPage(filter, condition, IsEnable);

            result.result.DT_TableDataT1.ForEach(async x =>
            {
                x.BeginDate = string.IsNullOrEmpty(x.BeginDate)?"":Convert.ToDateTime(x.BeginDate).ToString("yyyy-MM-dd");
                x.EndDate = string.IsNullOrEmpty(x.EndDate) ? "" : Convert.ToDateTime(x.EndDate).ToString("yyyy-MM-dd");
                x.StaffBeginDate = string.IsNullOrEmpty(x.StaffBeginDate) ? "" : Convert.ToDateTime(x.StaffBeginDate).ToString("yyyy-MM-dd");
                x.StaffEndDate = string.IsNullOrEmpty(x.StaffEndDate) ? "" : Convert.ToDateTime(x.StaffEndDate).ToString("yyyy-MM-dd");
                x.MGBeginDate = string.IsNullOrEmpty(x.MGBeginDate) ? "" : Convert.ToDateTime(x.MGBeginDate).ToString("yyyy-MM-dd");
                x.MGEndDate = string.IsNullOrEmpty(x.MGEndDate) ? "" : Convert.ToDateTime(x.MGEndDate).ToString("yyyy-MM-dd");
                x.OnJobBaseDate = string.IsNullOrEmpty(x.OnJobBaseDate) ? "" : Convert.ToDateTime(x.OnJobBaseDate).ToString("yyyy-MM-dd");

                x.Stage = await GetParaLabel("PerformanceStage", x.Stage);
                x.StageItem = await GetParaLabel("PerformanceStageItem", x.StageItem);
                x.PerformancePeriodTypeName = await Db.Queryable<Ghrp_PerformancePeriodType>().Where(a => a.Id==x.PerformancePeriodTypeID).Select(x=> x.PeriodTypeName).FirstAsync();
                x.PrePerformancePeriodName = await Db.Queryable<Ghrp_PerformancePeriod>().Where(a => a.Id == x.PrePerformancePeriodID).Select(x => x.PeriodName).FirstAsync();
            });

            return result;
        }

        public override async Task<long> Add(InsertGhrp_PerformancePeriodInput entity)
        {
            if (entity.PerformancePeriodTypeID != null)
                entity.PeriodType = await Db.Queryable<Ghrp_PerformancePeriodType>().Where(a => a.Id == entity.PerformancePeriodTypeID).Select(x => x.PeriodTypeNo).FirstAsync(); 
            var result = await base.Add(entity);

            return result;
        }

        public override async Task<bool> Update(long Id, EditGhrp_PerformancePeriodInput editModel)
        {
            if (editModel.PerformancePeriodTypeID != null)
                editModel.PeriodType = await Db.Queryable<Ghrp_PerformancePeriodType>().Where(a => a.Id == editModel.PerformancePeriodTypeID).Select(x => x.PeriodTypeNo).FirstAsync();

            var result = await base.Update(Id, editModel, null, ["Status"]);
            return result;
        }

        /// <summary>
        /// 批量生成期间
        /// </summary>
        /// <param name="Stage"></param>
        /// <returns></returns>
        public async Task<ServiceResult> BatchCreatePeriod(JObject jsonParam)
        { 
            string PerformancePeriodTypeID = jsonParam["PerformancePeriodTypeID"]?.Value<string>() ?? ""; // 考核周期类别
            if (string.IsNullOrEmpty(PerformancePeriodTypeID)) return ServiceResult.OprateSuccess("考核周期类别不能为空！");
            string YYYY = jsonParam["YYYY"]?.Value<string>() ?? "";                    // 展开年度
            if (string.IsNullOrEmpty(YYYY)) return ServiceResult.OprateSuccess("展开年度不能为空！"); 
            string BeginDate = jsonParam["BeginDate"]?.Value<string>() ?? "";          // 期间开始日
            if (string.IsNullOrEmpty(BeginDate)) return ServiceResult.OprateSuccess("期间开始日不能为空！");
            string StaffBeginDate = jsonParam["StaffBeginDate"]?.Value<string>() ?? "";// 员工填写开始日
            string StaffDays = jsonParam["StaffDays"]?.Value<string>() ?? "";          // 填写天数 
            string MGBeginDate = jsonParam["MGBeginDate"]?.Value<string>() ?? "";      // 主管填写开始日
            string MGDays = jsonParam["MGDays"]?.Value<string>() ?? "";                // 主管填写天数
            string OnJobBaseType = jsonParam["OnJobBaseType"]?.Value<string>() ?? "";  // 人员状态基准日
            if (string.IsNullOrEmpty(OnJobBaseType)) return ServiceResult.OprateSuccess("人员状态基准日不能为空！");
            string sql = @$" 
                            Declare @PerformancePeriodTypeID nvarchar(100) = '{PerformancePeriodTypeID}';
                            Declare @YYYY nvarchar(100) = '{YYYY}'
                            Declare @BeginDate nvarchar(100) = '{BeginDate}'
                            Declare @StaffBeginDate nvarchar(100) = '{StaffBeginDate}'
                            if @StaffBeginDate = '' set @StaffBeginDate = null
                            Declare @StaffDays int = '{StaffDays}'
                            if @StaffDays = 0 set @StaffDays = null
                            Declare @MGBeginDate nvarchar(100)='{MGBeginDate}'
                            if @MGBeginDate = '' set @MGBeginDate = null
                            Declare @MGDays int = '{MGDays}'
                            if @MGDays = 0 set @MGDays = null
                            Declare @OnJobBaseType nvarchar(100) ='{OnJobBaseType}'
                            
                            Declare @GUID nvarchar(100) = NEWID();
                            ;with PerformancePeriod as(
                            select top 999 ROW_NUMBER() over(order by PeriodTypeNo,b.Nums,c.SortNo) SortNo,
	                               @YYYY YYYY,
	                               PeriodTypeNo+@YYYY+'-'+CONVERT(nvarchar(10),Nums)+c.ParaDetailNo PeriodNo,
	                               PeriodTypeNo+@YYYY+'-'+CONVERT(nvarchar(10),Nums)+c.ParaDetailNo PeriodName,
	                               Id PerformancePeriodTypeID,
	                               PeriodTypeNo,
	                               Stage,
	                               ParaDetailNo StageItem,
	                               b.Nums ,
	                               1 IsUsing,
	                               DATEADD(MONTH,(Nums-1)*case when a.PeriodTypeNo = 'Year' then 12 
								                               when a.PeriodTypeNo = 'HalfYear' then 6 
								                               when a.PeriodTypeNo = 'Month' then 1
								                               when a.PeriodTypeNo = 'Quarter' then 3 
								                               else 12 end
								                             ,@BeginDate) BeginDate,
	                               DATEADD(MONTH,Nums*case when a.PeriodTypeNo = 'Year' then 12 
								                               when a.PeriodTypeNo = 'HalfYear' then 6 
								                               when a.PeriodTypeNo = 'Month' then 1
								                               when a.PeriodTypeNo = 'Quarter' then 3 
								                               else 12 end ,@BeginDate)-1 EndDate,
	                               DATEADD(MONTH,(Nums-1)*case when a.PeriodTypeNo = 'Year' then 12 
								                               when a.PeriodTypeNo = 'HalfYear' then 6 
								                               when a.PeriodTypeNo = 'Month' then 1
								                               when a.PeriodTypeNo = 'Quarter' then 3 
								                               else 12 end
								                             ,@StaffBeginDate) StaffBeginDate,
	                               DATEADD(MONTH,(Nums-1)*case when a.PeriodTypeNo = 'Year' then 12 
								                               when a.PeriodTypeNo = 'HalfYear' then 6 
								                               when a.PeriodTypeNo = 'Month' then 1
								                               when a.PeriodTypeNo = 'Quarter' then 3 
								                               else 12 end
								                             ,@StaffBeginDate)+@StaffDays StaffEndDate,
	                               DATEADD(MONTH,(Nums-1)*case when a.PeriodTypeNo = 'Year' then 12 
								                               when a.PeriodTypeNo = 'HalfYear' then 6 
								                               when a.PeriodTypeNo = 'Month' then 1
								                               when a.PeriodTypeNo = 'Quarter' then 3 
								                               else 12 end
								                             ,@MGBeginDate) MGBeginDate,
	                               DATEADD(MONTH,(Nums-1)*case when a.PeriodTypeNo = 'Year' then 12 
								                               when a.PeriodTypeNo = 'HalfYear' then 6 
								                               when a.PeriodTypeNo = 'Month' then 1
								                               when a.PeriodTypeNo = 'Quarter' then 3 
								                               else 12 end
								                             ,@MGBeginDate)+@MGDays MGEndDate
                            from Ghrp_PerformancePeriodType a,(select CONVERT(int,value) Nums from dbo.Fs1_GHR30_SplitString('1,2,3,4,5,6,7,8,9,10,11,12',',')) b 
								                             ,Ghrs_ParaDetail c   									     
                            where a.IsEnable = 1   
                              and c.ParaMasterNo = 'PerformanceStageItem' and c.ParaTypeNo = 'Performance'
                              and c.ParaDetailNo In (select value from openjson(a.StageItems)) 
                              and a.Id = @PerformancePeriodTypeID 
                              and b.Nums <= case when a.PeriodTypeNo = 'Year' then 1 
					                             when a.PeriodTypeNo = 'HalfYear' then 2 
					                             when a.PeriodTypeNo = 'Month' then 12 
					                             when a.PeriodTypeNo = 'Quarter' then 4 
					                             else 1
				                             end 
                            order by b.Nums,c.SortNo
                            )
                            insert into Ghrp_PerformancePeriod
                            (SortNo,ID,YYYY,PeriodNo,PeriodName,PerformancePeriodTypeID,PeriodType,Stage,StageItem,PeriodNum,IsUsing,
                            BeginDate,EndDate,StaffBeginDate,StaffEndDate,MGBeginDate,MGEndDate,OnJobBaseDate,PrePerformancePeriodID,RemarkSz,
                            IsEnable,CreateBy,CreateTime,CreateProg,Reverse1)  
                            select SortNo,
	                              ISNULL((select MAX(Id) from Ghrp_PerformancePeriod),  1000000000000000000 )
	                              +SortNo,
	                              YYYY,PeriodNo,PeriodName,PerformancePeriodTypeID,PeriodTypeNo,Stage,StageItem,Nums,IsUsing,
	                              BeginDate,EndDate,
	                              dbo.FS_MinDate(dbo.FS_MaxDate(ISNULL(StaffBeginDate,BeginDate),BeginDate),EndDate) StaffBeginDate,
	                              dbo.FS_MinDate(ISNULL(StaffEndDate,EndDate),EndDate) StaffEndDate,
	                              dbo.FS_MinDate(dbo.FS_MaxDate(ISNULL(MGBeginDate,BeginDate),BeginDate),EndDate) MGBeginDate,
	                              dbo.FS_MinDate(ISNULL(MGEndDate,EndDate),EndDate) MGEndDate,
	                              case when ISNULL(@OnJobBaseType,'') = 'Begin' then BeginDate else EndDate end OnJobBaseDate,
	                              NULL PrePerformancePeriodID,'' RemarkSz,
	                              1 IsEnable,1 CreateBy,GETDATE() CreateTime,'/api/Ghrp_PerformancePeriod/BatchCreatePeriod' CreateProg,@GUID 
                            from PerformancePeriod  a
                            where Not Exists(select 1 from Ghrp_PerformancePeriod where IsEnable=1 and YYYY= a.YYYY and PerformancePeriodTypeID=a.PerformancePeriodTypeID and PeriodNo=a.PeriodNo)
                            order by SortNo 

                             update a
                               set PrePerformancePeriodID = (select Id from Ghrp_PerformancePeriod 
									                            where IsEnable=1 and YYYY=a.YYYY 
									                              and PerformancePeriodTypeID=a.PerformancePeriodTypeID
									                              and SortNo = a.SortNo-1
									                              and Reverse1=@GUID
								                              )
                             from Ghrp_PerformancePeriod a
                             where Reverse1=@GUID
            ";
            await Db.Ado.ExecuteCommandAsync(sql);
            return ServiceResult.OprateSuccess("批量展开成功！");
        }

    }
}