using AutoMapper;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Resource;

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

        public async Task<Res_CountryFeeCost> InfoByCountryName(string countryName)
        {
            if (string.IsNullOrEmpty(countryName)) return null;
            return await _sqlSugar.Queryable<Res_CountryFeeCost>()
                .FirstAsync(it => it.VisaCountry == countryName);
        }


        public async Task<JsonView> OperationCountryFeeCost(OperationCountryFeeCostDto dto)
        {
            var result = new JsonView() { Code = StatusCodes.Status400BadRequest, Msg = "未知错误" };

            var countryFeeCost = _mapper.Map<Res_CountryFeeCost>(dto);

            countryFeeCost.LastUpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            if (dto.Status == 1)//添加
            {
                var exists = await _sqlSugar.Queryable<Res_CountryFeeCost>()
                    .AnyAsync(x => x.IsDel == 0 &&
                                   x.VisaFeeType == dto.VisaFeeType &&
                                   x.VisaContinent == dto.VisaContinent &&
                                   x.VisaCountry == dto.VisaCountry);

                if (exists)
                {
                    result.Msg = "该国家已存在,请勿重复添加!";
                    return result;
                }
                else//不存在,可添加
                {

                    int id = await AddAsyncReturnId(countryFeeCost);
                    if (id == 0)
                    {
                        result.Msg = "添加失败!";
                        return result;
                    }
                    result.Code = StatusCodes.Status200OK;
                    result.Msg = "添加成功!";
                }
            }
            else if (dto.Status == 2)//修改
            {
                var update = await _sqlSugar
                    .Updateable(countryFeeCost)
                    .IgnoreColumns(it => new { it.Id, it.DeleteUserId, it.DeleteTime, it.CreateUserId, it.CreateTime, it.IsDel })
                    .Where(it => it.Id == countryFeeCost.Id)
                    .ExecuteCommandAsync();
                //bool res = await UpdateAsync(a => a.Id == dto.Id, a => _CountryFeeCost);
                if (update < 1)
                {
                    result.Msg = "修改失败!";
                    return result;
                }
                result.Code = StatusCodes.Status200OK;
                result.Msg = "修改成功!";
            }
            else
            {
                result.Msg = "请传入Status参数,1添加 2修改!";
            }

            return result;
        }
    }
}