using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Groups;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OASystem.Infrastructure.Repositories.Groups
{
    public class GrpScheduleRepository : BaseRepository<Grp_ScheduleInfo, Grp_ScheduleInfo>
    {
        public GrpScheduleRepository(SqlSugarClient sqlSugar) : base(sqlSugar)
        {
        }

        public string SetSqlWhere_GrpScheduleDto(Grp_ScheduleDto _dto)
        {
            string sqlWhere = string.Empty;

            if (_dto.SysUserId > 0)
            {
                sqlWhere += string.Format(@" And s.Id in ( Select Id From Grp_SchedulePerson With(Nolock) Where SysUserId = '{0}' ) ", _dto.SysUserId);
            }

            if (_dto.ScheduleId > 0)
            {
                sqlWhere += string.Format(@" And s.Id = '{0}' ", _dto.ScheduleId);
            }

            if (!string.IsNullOrEmpty(sqlWhere.Trim()))
            {
                Regex r = new Regex("And");
                sqlWhere = r.Replace(sqlWhere, "Where", 1);
            }

            return sqlWhere;
        }

        /// <summary>
        /// 获取团组流程数据单个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="_dto"></param>
        /// <returns></returns>
        public async Task<Grp_ScheduleView> GetView_GrpSchedule(Grp_ScheduleDto _dto)
        {
            Grp_ScheduleView _view = null;

            string sqlWhere = this.SetSqlWhere_GrpScheduleDto(_dto);
            string sql = string.Format(@" Select s.Id,s.DiId,di.TeamName as DeleName,s.PrimaryStep,s.ExpectBeginDt,s.ExpectEndDt,s.Leader,s.Exception,u.CnName as LeaderName
            From Grp_Schedule as s With(Nolock) Inner Join Grp_DelegationInfo as di With(Nolock) On s.DiId=di.Id
            Inner Join Sys_Users as u With(Nolock) On s.Leader=u.Id
            {0} ", sqlWhere);

            _view = await _sqlSugar.SqlQueryable<Grp_ScheduleView>(sql).FirstAsync();

            return _view;
        }


    }
}