using AutoMapper;
using OASystem.Domain;
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 CarTouristGuideGroundRepository:BaseRepository<Grp_CarTouristGuideGroundReservations, Grp_CarTouristGuideGroundReservationsContent>
    {
        private readonly IMapper _mapper;

        public CarTouristGuideGroundRepository(SqlSugarClient sqlSugar, IMapper mapper)
            : base(sqlSugar)
        {
            _mapper = mapper;
        }

        public Task<Result> OpCarTouristGuideGround(OpCarTouristGuideGroundDto dto)
        {
            throw new NotImplementedException();
        }

        public async Task<Result> QueryCarTouristGuideGroundByDiId(CarTouristGuideGroundDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            if (dto.PortType == 0 || string.IsNullOrWhiteSpace(dto.PortType.ToString()))
            {
                return result = new Result() { Code = -1, Msg = "请传入PortType参数，请求端口分类 1 Web 2 Android 3 IOS" };
            }
            try
            {
                #region SQL条件拼接

                string sqlWhere = string.Empty;
                sqlWhere += string.Format(@"And t.DIId={0} and t.isdel={1}", dto.DiId, 0);
                string UserId = "";
                List<Grp_GroupsTaskAssignment> gtaUIdList = _sqlSugar.Queryable<Grp_GroupsTaskAssignment>().Where(a => a.DIId == dto.DiId && a.IsDel == 0 && a.CTId == 79).ToList();
                foreach (Grp_GroupsTaskAssignment gta in gtaUIdList)
                    UserId += gta.UId + ",";

                if (!string.IsNullOrWhiteSpace(UserId))
                {
                    UserId = UserId.Substring(0, UserId.Length - 1);
                }
                else
                {
                    UserId = "0";
                }
                
                sqlWhere += string.Format(@" And t.CreateUserId in ({0})", UserId);
                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }

                #endregion
                int startIndex = (dto.PageIndex - 1) * dto.PageSize + 1;
                int endIndex = startIndex + dto.PageSize - 1;
                if (dto.PortType == 1)
                {
                    string sql = string.Format(@"select t.*,s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage,c.PayMoney from 
                                                Grp_CarTouristGuideGroundReservations t
                                                left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id
                                                left Join Sys_SetData s on s.Id=t.CId {0}
                                                order by CreateTime desc", sqlWhere);
                    List<Grp_CarTouristGuideGroundView> infoViews = _sqlSugar.SqlQueryable<Grp_CarTouristGuideGroundView>(sql).ToList();
                    foreach (var item in infoViews)
                    {
                        item.PayThenMoney = Math.Round(item.PayPercentage/100 * item.ServiceQuotedPrice, 2);
                        item.RemainingBalance = Math.Round(item.ServiceQuotedPrice- item.PayPercentage / 100 * item.ServiceQuotedPrice);
                    }
                    return result = new Result() { Code = 0, Msg = "查询成功！", Data = infoViews };
                }
                else if (dto.PortType == 2 || dto.PortType == 3)
                {
                    string sql = string.Format(@"Select * From (	
                                            Select row_number() over (order by t.Id Desc) as RowNumber,t.*,s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage
                                            from 
                                            Grp_CarTouristGuideGroundReservations t
                                            left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id
                                            left Join Sys_SetData s on s.Id=t.CId {0}
                                            ) temp Where RowNumber Between {1} and {2}", sqlWhere, startIndex, endIndex);

                    List<Grp_CarTouristGuideGroundView> grp_CarTourists = _sqlSugar.SqlQueryable<Grp_CarTouristGuideGroundView>(sql).ToList();
                    foreach (var item in grp_CarTourists)
                    {
                        item.PayThenMoney = Math.Round(item.PayPercentage / 100 * item.ServiceQuotedPrice, 2);
                        item.RemainingBalance = Math.Round(item.ServiceQuotedPrice - item.PayPercentage / 100 * item.ServiceQuotedPrice);
                    }
                    string CountSql = string.Format(@"Select COUNT(1) as Count From (	
                                                        select t.*,s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage from 
                                                        Grp_CarTouristGuideGroundReservations t
                                                        left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id
                                                        left Join Sys_SetData s on s.Id=t.CId {0}
                                                        ) temp ", sqlWhere);
                    DataCount dataCount = _sqlSugar.SqlQueryable<DataCount>(CountSql).First();
                    if (dataCount != null)
                    {
                        int count = dataCount.Count;
                        float totalPage = (float)count / dto.PageSize;//总页数
                        if (totalPage == 0) totalPage = 1;
                        else totalPage = (int)Math.Ceiling((double)totalPage);


                        ListViewBase<Grp_CarTouristGuideGroundView> rst = new ListViewBase<Grp_CarTouristGuideGroundView>();
                        rst.DataList = grp_CarTourists;
                        rst.DataCount = count;
                        rst.CurrPageIndex = dto.PageIndex;
                        rst.CurrPageSize = dto.PageSize;
                        return result = new Result() { Code = 0, Msg = "查询成功！", Data = rst };
                    }
                }
            }
            catch (Exception)
            {
                return result = new Result() { Code = -2, Msg = "未知错误" };
                throw;
            }
            return result;
        }
    }
}
