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

namespace OASystem.Infrastructure.Repositories.Resource
{
    public class TicketBlackCodeRepository : BaseRepository<Air_TicketBlackCode, TicketBlackCodeView>
    {
        private readonly IMapper _mapper;
        public TicketBlackCodeRepository(SqlSugarClient sqlSugar, IMapper mapper) : base(sqlSugar)
        {
            _mapper = mapper;
        }

        /// <summary>
        /// 黑屏代码操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> OpTicketBlackCode(OpTicketBlackCodeDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                if (dto.Status == 1)//添加
                {
                   
                    Air_TicketBlackCode _TicketBlackCode = await _sqlSugar.Queryable<Air_TicketBlackCode>().FirstAsync(a=>a.IsDel==0 && a.BlackCode==dto.BlackCode);//查询是否存在
                    if (_TicketBlackCode != null)
                    {
                        return result = new Result() { Code = -1, Msg = "该信息已存在，请勿重复添加！" };

                    }
                    else//不存在，可添加
                    {

                        Air_TicketBlackCode air_TicketBlack = _mapper.Map<Air_TicketBlackCode>(dto);
                        int id = await _sqlSugar.Insertable(air_TicketBlack).ExecuteReturnIdentityAsync();
                        if (id == 0)
                        {
                            return result = new Result() { Code = -1, Msg = "添加失败！" };

                        }
                        return result = new Result() { Code = 0, Msg = "添加成功！", Data = new { Id = id } };
                    }
                }
                else if (dto.Status == 2)//修改
                {
                    bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Air_TicketBlackCode
                    {
                        DiId=dto.DiId,
                        BlackCode=dto.BlackCode,
                        Price=dto.Price,
                        NowPrice=dto.NowPrice,
                        BCPrice=dto.BCPrice,
                        ECPrice=dto.ECPrice,
                        CreateUserId = dto.CreateUserId,
                        Remark = dto.Remark,
                    });
                    if (!res)
                    {
                        return result = new Result() { Code = -1, Msg = "修改失败！" };
                    }
                    return result = new Result() { Code = 0, Msg = "修改成功！", Data = new { Id = dto.Id } };
                }
                else
                {
                    return result = new Result() { Code = -1, Msg = "请传入Status参数，1添加 2修改！" };
                }
            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "程序错误！" };
            }
        }

        public async Task<Result> QueryTicketBlackCodeByDiId(QueryTicketBlackCodeByDiIdDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                string sqlWhere = string.Empty;

                sqlWhere += string.Format(@" And a.IsDel={0} And a.DiId={1}", 0, dto.DiId);
                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }

                string sql = string.Format(@"select *,(select CnName from Sys_Users where id=a.CreateUserId) as CreateName from Air_TicketBlackCode a  {0}", sqlWhere);
                List<TicketBlackCodeView> _TicketBlackCodes = await _sqlSugar.SqlQueryable<TicketBlackCodeView>(sql).ToListAsync();
                Grp_DelegationInfo _DelegationInfo=await _sqlSugar.Queryable<Grp_DelegationInfo>().FirstAsync(a=>a.IsDel==0 && a.Id==dto.DiId);
                if (_TicketBlackCodes.Count!=0)
                {
                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功",
                        Data = new
                        {
                            TicketBlackCodes= _TicketBlackCodes,
                            DelegationInfo= _DelegationInfo
                        },
                    };
                }
                else
                {
                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "暂无数据",
                        Data = new
                        {
                            TicketBlackCodes = _TicketBlackCodes,
                            DelegationInfo = _DelegationInfo
                        },
                    };
                }
            }
            catch (Exception)
            {
                return result;
                throw;
            }
        }

        public async Task<Result> QueryTicketBlackCodeById(QueryTicketBlackCodeByIdDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                //查询成本和团组信息
                Grp_GroupCostParameter _GroupCostParameter = _sqlSugar.Queryable<Grp_GroupCostParameter>().First(a => a.DiId == dto.DiId && a.IsDel==0);//团组成本
                AirGroupCostParameterView _AirgroupCostParameter = _mapper.Map<AirGroupCostParameterView>(_GroupCostParameter);
                Grp_DelegationInfo _DelegationInfo=_sqlSugar.Queryable<Grp_DelegationInfo>().First(a=>a.Id == dto.DiId && a.IsDel==0);//团组信息
                Air_TicketBlackCode _TicketBlackCode=new Air_TicketBlackCode();
                if (dto.Id!=0 && !string.IsNullOrWhiteSpace(dto.Id.ToString()))
                {
                    _TicketBlackCode = _sqlSugar.Queryable<Air_TicketBlackCode>().First(a => a.IsDel==0 && a.Id==dto.Id);
                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功！",
                        Data = new
                        {
                            GroupCostParameter = _AirgroupCostParameter,
                            DelegationInfo = _DelegationInfo,
                            TicketBlackCode = _TicketBlackCode
                        },
                    };
                }
                else
                {
                    return result = new Result()
                    {
                        Code = 0,
                        Msg = "查询成功！",
                        Data = new
                        {
                            GroupCostParameter = _AirgroupCostParameter,
                            DelegationInfo = _DelegationInfo,
                        },
                    };
                }
                
            }
            catch (Exception)
            {
                return result;
                throw;
            }
        }
    }
}
