| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556 | using Aspose.Words.Tables;using AutoMapper;using NPOI.SS.Formula.Functions;using NPOI.SS.UserModel;using NPOI.Util;using OASystem.Domain;using OASystem.Domain.AesEncryption;using OASystem.Domain.Dtos.Financial;using OASystem.Domain.Dtos.Groups;using OASystem.Domain.Dtos.QiYeWeChat;using OASystem.Domain.Entities.Financial;using OASystem.Domain.Entities.Groups;using OASystem.Domain.Entities.Resource;using OASystem.Domain.ViewModels.Groups;using OASystem.Infrastructure.Repositories.Financial;using OASystem.Infrastructure.Repositories.System;using OASystem.Infrastructure.Tools;using SqlSugar.Extensions;using System.Collections.Generic;using System.Linq;using System.Reflection;using static NPOI.HSSF.Util.HSSFColor;namespace OASystem.Infrastructure.Repositories.Groups{    public class CarTouristGuideGroundRepository : BaseRepository<Grp_CarTouristGuideGroundReservations, Grp_CarTouristGuideGroundReservationsContent>    {        private readonly IMapper _mapper;        private readonly CheckBoxsRepository _checkRep;        private readonly SetDataRepository _setDataRep;        private readonly DailyFeePaymentRepository _daiRep;    //日付申请仓库        private readonly GroupCostParameterRepository _groupCostParameterRepository;        private readonly ForeignReceivablesRepository _foreignReceivablesRepository;        public CarTouristGuideGroundRepository(SqlSugarClient sqlSugar, IMapper mapper, CheckBoxsRepository checkRep, SetDataRepository setDataRep,            DailyFeePaymentRepository daiRep, GroupCostParameterRepository groupCostParameterRepository, ForeignReceivablesRepository foreignReceivablesRepository)            : base(sqlSugar)        {            _mapper = mapper;            _checkRep = checkRep;            _setDataRep = setDataRep;            _daiRep = daiRep;            _groupCostParameterRepository = groupCostParameterRepository;            _foreignReceivablesRepository = foreignReceivablesRepository;        }        public async Task<Result> OpCarTouristGuideGround(OpCarTouristGuideGroundDto dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            BeginTran();            try            {                int id = 0;                var grp_CarTouristGuide = _mapper.Map<Grp_CarTouristGuideGroundReservations>(dto);                if (dto.Status == 1)//添加                {                    var grp_CarTouristGuideGround = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>()                                                             .First(a => a.IsDel == 0 &&                                                                         a.Area == dto.Area &&                                                                         a.BusName == dto.BusName &&                                                                         a.ServiceGuide == dto.ServiceGuide &&                                                                         a.DiId == dto.DiId &&                                                                         a.BusTel == dto.BusTel &&                                                                         a.ServiceTel == dto.ServiceTel &&                                                                         a.PriceName == dto.PriceName                                                             );                    if (grp_CarTouristGuideGround != null)                    {                        return result = new Result() { Code = -1, Msg = "该笔费用已存在,请勿重复添加!" };                    }                    else                    {                        id = await AddAsyncReturnId(grp_CarTouristGuide);                        if (id == 0)                        {                            RollbackTran();                            result = new Result() { Code = -1, Msg = "添加失败,请稍后重试!" };                        }                        else                        {                            result = new Result() { Code = 0, Msg = "添加成功!" };                        }                    }                }                else if (dto.Status == 2)//修改                {                    bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Grp_CarTouristGuideGroundReservations                    {                        Area = grp_CarTouristGuide.Area,                        ServiceCompany = grp_CarTouristGuide.ServiceCompany,                        ServiceGuide = grp_CarTouristGuide.ServiceGuide,                        ServiceTel = grp_CarTouristGuide.ServiceTel,                        BusName = grp_CarTouristGuide.BusName,                        BusDescription = grp_CarTouristGuide.BusDescription,                        BusTel = grp_CarTouristGuide.BusTel,                        ServiceStartTime = grp_CarTouristGuide.ServiceStartTime,                        ServiceEndTime = grp_CarTouristGuide.ServiceEndTime,                        ServiceDescription = grp_CarTouristGuide.ServiceDescription,                        QuotedPriceExplanation = grp_CarTouristGuide.QuotedPriceExplanation,                        OrbitalPrivateTransfer = grp_CarTouristGuide.OrbitalPrivateTransfer,                        Remark = grp_CarTouristGuide.Remark,                        PriceType = grp_CarTouristGuide.PriceType,                        PriceName = grp_CarTouristGuide.PriceName,                    });                    if (res)                    {                        id = dto.Id;                        result = new Result() { Code = 0, Msg = "修改成功!" };                    }                    else                    {                        RollbackTran();                        result = new Result() { Code = -1, Msg = "修改失败,请稍后重试!" };                    }                }                if (id != 0)                {                    var _LocalGuideDataCar = _sqlSugar.Queryable<Res_LocalGuideData>()                        .First(a =>                            a.UnitName == AesEncryptionHelper.Encrypt(dto.BusName) &&                            a.ContactTel == AesEncryptionHelper.Encrypt(dto.BusTel) &&                            a.IsDel == 0                            );                    if (_LocalGuideDataCar == null)                    {                        var res_LocalGuideCar = new Res_LocalGuideData();                        res_LocalGuideCar.UnitName = dto.BusName;                        res_LocalGuideCar.ContactTel = dto.BusTel;                        res_LocalGuideCar.CreateUserId = dto.CreateUserId;                        EncryptionProcessor.EncryptProperties(res_LocalGuideCar);                        int cId = await _sqlSugar.Insertable(res_LocalGuideCar).ExecuteReturnIdentityAsync();                    }                    var _LocalGuideDataService = _sqlSugar.Queryable<Res_LocalGuideData>()                        .First(a =>                         a.UnitName == AesEncryptionHelper.Encrypt(dto.ServiceCompany) &&                         a.ContactTel == AesEncryptionHelper.Encrypt(dto.ServiceTel) &&                         a.IsDel == 0                        );                    if (_LocalGuideDataService == null)                    {                        Res_LocalGuideData res_LocalGuideService = new Res_LocalGuideData();                        res_LocalGuideService.UnitName = dto.ServiceCompany;                        res_LocalGuideService.ContactTel = dto.ServiceTel;                        res_LocalGuideService.Contact = dto.ServiceTel;                        res_LocalGuideService.CreateUserId = dto.CreateUserId;                        EncryptionProcessor.EncryptProperties(res_LocalGuideService);                        int cId = await _sqlSugar.Insertable(res_LocalGuideService).ExecuteReturnIdentityAsync();                    }                }                CommitTran();            }            catch (Exception ex)            {                result = new Result() { Code = -2, Msg = "未知错误" + ex.Message };            }            return result;        }        public Result CarTouristGuideGroundContent(CarTouristGuideGroundContentDto dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            try            {                Grp_CarTouristGuideGroundReservations grpCarOp = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().First(x => x.Id == dto.Id);                if (!DateTime.TryParse(grpCarOp?.ServiceStartTime, out DateTime start))                {                    result.Msg = "服务开始时间不存在!";                    result.Code = -1;                    return result;                }                if (!DateTime.TryParse(grpCarOp?.ServiceEndTime, out DateTime end))                {                    result.Msg = "服务结束时间不存在!";                    result.Code = -1;                    return result;                }                if (DateTime.Compare(end, start) < 0)                {                    result.Msg = "服务时间区间有误!结束时间不应该小于开始时间!";                    result.Code = -1;                    return result;                }                TimeSpan ts = end - start;  //计算时间差                int day = ts.Days;                var diid = Query<Grp_GroupsTaskAssignment>(a => a.IsDel == 0 && a.UId == dto.UserId && a.CTId == 79)                    .Select(x => x.DIId)                    .Distinct()                    .ToList();                //团组下拉框                List<Grp_DelegationInfo> _Delegations = diid.Any()                    ? _sqlSugar.Queryable<Grp_DelegationInfo>()                        .Where(x => x.IsDel == 0 && diid.Contains(x.Id)).ToList()                    : new List<Grp_DelegationInfo>();                List<ShareGroupInfoIIView> grp_Delegations = _mapper.Map<List<ShareGroupInfoIIView>>(_Delegations);                //支付方式                List<Sys_SetData> Payment = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 14 && a.IsDel == 0).ToList();                List<SetDataInfoView> _Payment = _mapper.Map<List<SetDataInfoView>>(Payment);                //列表初始化                List<Sys_SetData> TableInitialization = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 17 && a.IsDel == 0).ToList();                List<SetDataInfoView> _TableInitialization = _mapper.Map<List<SetDataInfoView>>(TableInitialization);                _TableInitialization = _TableInitialization.OrderBy(x => x.RemarkSort).ToList();                List<Sys_SetData> ssd = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 78).ToList();                List<SetDataInfoView> ssdv = _mapper.Map<List<Sys_SetData>, List<SetDataInfoView>>(ssd);                var carTouristGuides = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>()                                             .LeftJoin<Sys_SetData>((a, b) => b.IsDel == 0 && a.SId == b.Id)                                             .Where(a => a.IsDel == 0 && a.CTGGRId == dto.Id)                                             .Select((a, b) => new CarTouristGuideGroundReservationsContentView                                             {                                                 SId = a.SId,                                                 Id = a.Id,                                                 Count = a.Count,                                                 DatePrice = a.DatePrice,                                                 Price = a.Price,                                                 PriceContent = a.PriceContent,                                                 Units = a.Units,                                                 SidName = b.Name                                             })                                             .ToList();                var weikuanSign = new int[] { 1070, 1071, };                TableInitialization.RemoveAll(x => weikuanSign.Contains(x.Id));                var weiKuanArr = _TableInitialization.Where(x => weikuanSign.Contains(x.Id)).ToList();                var weiKuanResultArr = carTouristGuides.Where(x => weikuanSign.Contains(x.SId)).ToList();                carTouristGuides.RemoveAll(x => weikuanSign.Contains(x.SId));                var existingSIdArr = new HashSet<int>(carTouristGuides.Select(x => x.SId));                foreach (var itemSt in TableInitialization)                {                    if (!existingSIdArr.Contains(itemSt.Id))                    {                        carTouristGuides.Add(new CarTouristGuideGroundReservationsContentView                        {                            SId = itemSt.Id,                            Count = 1,                            SidName = itemSt.Name,                        });                        existingSIdArr.Add(itemSt.Id);                    }                }                var groupResult = carTouristGuides.GroupBy(x => x.SId).ToDictionary(x => x.Key, x => x.ToList());                foreach (var item in groupResult.Keys)                {                    var startForTime = start;                    var dayResult = new List<CarTouristGuideGroundReservationsContentView>();                    for (var i = 0; i <= day; i++)                    {                        dayResult.Add(new CarTouristGuideGroundReservationsContentView                        {                            Count = 1,                            DatePrice = startForTime,                            SId = item,                            SidName = groupResult[item][0].SidName                        });                        startForTime = startForTime.AddDays(1);                    }                    if (groupResult[item].Count != day)                    {                        for (var m = 0; m < groupResult[item].Count; m++)                        {                            for (var m1 = 0; m1 < dayResult.Count; m1++)                            {                                if (groupResult[item][m].DatePrice == dayResult[m1].DatePrice)                                {                                    dayResult[m1] = groupResult[item][m];                                }                            }                        }                    }                    else                    {                        groupResult[item] = groupResult[item].OrderBy(x => x.DatePrice).ToList();                        if (groupResult[item][0].DatePrice == dayResult[0].DatePrice && groupResult[item][day - 1].DatePrice == dayResult[day - 1].DatePrice)                        {                            dayResult = groupResult[item];                        }                        else                        {                            for (var m = 0; m < groupResult[item].Count; m++)                            {                                for (var m1 = 0; m1 < dayResult.Count; m1++)                                {                                    if (groupResult[item][m].DatePrice == dayResult[m1].DatePrice)                                    {                                        dayResult[m1] = groupResult[item][m];                                    }                                }                            }                        }                    }                    groupResult[item] = dayResult;                }                carTouristGuides = groupResult.Values.SelectMany(sublist => sublist).OrderBy(x => x.SId).ThenBy(x => x.DatePrice).ToList();                var _CreditCardPayment = _sqlSugar.Queryable<Grp_CreditCardPayment, Sys_SetData, Sys_SetData>(                    (g, s1, s2) => new JoinQueryInfos(                        JoinType.Left, g.PayDId == s1.Id,                        JoinType.Left, g.PaymentCurrency == s2.Id                    ))                .Where((g, s1, s2) => g.CId == dto.Id && g.IsDel == 0 && g.CTable == 79)                .Select((g, s1, s2) => new CarTouristCreditCardPaymentView                {                    IsAuditGM = g.IsAuditGM,                    PayDId = g.PayDId,                    PaymentCurrency = g.PaymentCurrency,                    Payee = g.Payee,                    PayMoney = g.PayMoney,                    PayPercentage = g.PayPercentage,                    PayName = s1.Name,                    PaymentCurrencyName = s2.Name,                    OrbitalPrivateTransfer = g.OrbitalPrivateTransfer,                    OrbitalPrivateTransferStr = g.OrbitalPrivateTransfer == 0 ? "公转" : "私转",                    BankNo = g.BankNo,                    CardholderName = g.CardholderName,                    CompanyBankNo = g.CompanyBankNo,                    ConsumptionDate = g.ConsumptionDate,                    ConsumptionPatterns = g.ConsumptionPatterns,                    Ctdid = g.CTDId,                    OtherBankName = g.OtherBankName,                    OtherSideName = g.OtherSideName,                    OtherSideNo = g.OtherSideNo,                })                .First();                Dictionary<string, string> soureDic = new Dictionary<string, string>()                {                    {"车费", "VF"},                    {"导游费", "T/G S"},                    {"客户午餐费用" , "L"},                    {"导游景点费" , "T/G EF"},                    {"导游小费" , "T/G T"},                      // --                     {"司机小费", "DRV T"},                     {"司机餐补", "C/F M"},                     {"车超时费", "C/F OF"},                     {"导游餐补", "T/G M"},                     {"导游房补", "T/G A"},                     {"导游交通", "T/G TF"},                     {"客户早餐费用", "B"},                     {"客户晚餐费用", "D"},                     {"景点门票费", "EF"},                     {"饮料/零食/水果", "B/R/F"},                     {"翻译费", "I/F"},                };                var checkedItem = new List<string>();                var checkedItemId = new List<int>();                var isSaveCheck = false;                if (string.IsNullOrWhiteSpace(grpCarOp.SelectCheck))                {                    //获取成本选中                    var checkTopArr = _checkRep.GetCheckBoxsByDiid(grpCarOp.DiId);                    if (true)                    {                        var FindTop = checkTopArr.Find(x => x.CbType == "Top");                        if (FindTop != null)                        {                            var selectName = FindTop.CbValues.Split(',').ToList<string>();                            foreach (var soureKey in soureDic.Keys)                            {                                var find = selectName.Find(x => x == soureDic[soureKey]);                                if (find == null)                                {                                    var Lindex = carTouristGuides.FindIndex(x => x.SidName == soureKey);                                    //carTouristGuides.RemoveRange(Lindex, day + 1);                                }                                else                                {                                    checkedItem.Add(soureKey);                                    checkedItemId.Add(_TableInitialization.Find(x => x.Name == soureKey)!.Id);                                }                            }                        }                        else                        {                            checkedItem = _TableInitialization.Select(x => x.Name).ToList();                            checkedItemId.AddRange(_TableInitialization.Select(x => x.Id).ToList());                        }                    }                }                else                {                    isSaveCheck = true;                    var checkedItemThis = grpCarOp.SelectCheck.Split(",").ToList<string>();                    int number = 0;                    foreach (var item in checkedItemThis)                    {                        if (!int.TryParse(item, out number))                        {                            checkedItemId.Add(_TableInitialization.Find(x => x.Name == item)!.Id);                            checkedItem.Add(item);                        }                        else                        {                            checkedItemId.Add(number);                            checkedItem.Add(_TableInitialization.Find(x => x.Id == int.Parse(item))!.Name);                        }                    }                }                if (grpCarOp.PriceType == 1062) //尾款id                {                    if (isSaveCheck)                    {                        checkedItemId.AddRange(weiKuanArr.Select(x => x.Id).ToList());                        checkedItem.AddRange(weiKuanArr.Select(x => x.Name).ToList());                        checkedItemId = checkedItemId.Distinct().ToList();                        checkedItem = checkedItem.Distinct().ToList();                    }                    else                    {                        checkedItemId = weiKuanArr.Select(x => x.Id).ToList();                        checkedItem = weiKuanArr.Select(x => x.Name).ToList();                    }                    var weiPrice = weiKuanResultArr.Find(x => x.SId == 1070);                    if (weiPrice != null)                    {                        weiPrice.SidName = "尾款金额";                    }                    var weiOther = weiKuanResultArr.Find(x => x.SId == 1071);                    if (weiOther != null)                    {                        weiOther.SidName = "其他额外费用";                    }                    carTouristGuides.Add(weiPrice ??= new CarTouristGuideGroundReservationsContentView                    {                        Count = 1,                        DatePrice = DateTime.Now,                        Price = 0,                        PriceContent = "",                        SId = 1070,                        SidName = "尾款金额",                        Units = 0,                    });                    carTouristGuides.Add(weiOther ??= new CarTouristGuideGroundReservationsContentView                    {                        Count = 1,                        DatePrice = DateTime.Now,                        Price = 0,                        PriceContent = "",                        SId = 1071,                        SidName = "其他额外费用",                        Units = 0,                    });                }                else                {                    _TableInitialization.RemoveAll(x => weikuanSign.Contains(x.Id));                    checkedItem.RemoveAll(x => x == "尾款金额" || x == "其他额外费用");                    checkedItemId.RemoveAll(x => weikuanSign.Contains(x));                }                //三公费用金额以及币种                var boolParse = int.TryParse(grpCarOp.Area, out int natiId);                var NationalTravelFee = _sqlSugar.Queryable<Grp_NationalTravelFee>()                    .LeftJoin<Sys_SetData>((a, b) => a.Currency == b.Id)                    .Where((a, b) => a.IsDel == 0 && b.IsDel == 0)                    .Select((a, b) => new                    {                        a.Id,                        a.Currency,                        CurrencyStr = b.Name,                        a.FoodCost,                        a.RoomCost,                        a.PublicCost,                    })                    .First((a) => boolParse == true && a.Id == natiId);                var rate = new                {                    grpCarOp.Rate,                    grpCarOp.toCurr                };                var bankCard = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.IsDel == 0 && x.STid == 15)                    .Select(x => new                    {                        x.Id,                        x.Name                    })                    .OrderByDescending(x => x.Id)                    .ToList();                if (dto.PortType == 1)                {                    var data = new                    {                        Payment = _Payment,                        Delegations = grp_Delegations,                        carTouristGuides = carTouristGuides,                        CreditCardPayment = _CreditCardPayment,                        start,                        end,                        ssdv,                        checkedItem,                        existItem = _TableInitialization.Select(x => x.Name).ToList(),                        NationalTravelFee,                        rate,                        bankCard                    };                    return result = new Result() { Code = 0, Msg = "查询成功", Data = data };                }                else if (dto.PortType == 2)                {                    var data = new                    {                        Payment = _Payment,                        TableInitialization = _TableInitialization,                        carTouristGuides = carTouristGuides,                        CreditCardPayment = _CreditCardPayment ??= new CarTouristCreditCardPaymentView(),                        ssdv,                        checkedItemId,                        NationalTravelFee,                        rate,                        bankCard                    };                    return result = new Result() { Code = 0, Msg = "查询成功", Data = data };                }                return result = new Result() { Code = -1, Msg = "请传入有效portType" };            }            catch (Exception ex)            {                return result = new Result() { Code = -2, Msg = "未知错误" };            }        }        /// <summary>        /// web弃用        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public Result OpCarTouristGuideGroundContentById(CarTouristGuideGroundIdDto dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            try            {                List<Grp_CarTouristGuideGroundReservationsContent> grp_CarTouristsContent = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(a => a.IsDel == 0 && a.CTGGRId == dto.Id).ToList();                List<CarTouristGuideGroundReservationsContentView> carTouristGuides = _mapper.Map<List<CarTouristGuideGroundReservationsContentView>>(grp_CarTouristsContent);                foreach (var item in carTouristGuides)                {                    item.SidName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == item.SId).Name;                }                Grp_CreditCardPayment CreditCardPayment = _sqlSugar.Queryable<Grp_CreditCardPayment>().First(a => a.CId == dto.Id && a.IsDel == 0 && a.CTable == 79);                CarTouristCreditCardPaymentView _CreditCardPayment = _mapper.Map<CarTouristCreditCardPaymentView>(CreditCardPayment);                if (_CreditCardPayment != null)                {                    _CreditCardPayment.PayName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == _CreditCardPayment.PayDId).Name;                    _CreditCardPayment.PaymentCurrencyName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == _CreditCardPayment.PaymentCurrency).Name;                    if (_CreditCardPayment.OrbitalPrivateTransfer == 0) _CreditCardPayment.OrbitalPrivateTransferStr = "公转";                    else _CreditCardPayment.OrbitalPrivateTransferStr = "私转";                }                var data = new                {                    CarTouristsContent = carTouristGuides,                    CreditCardPayment = _CreditCardPayment,                };                return result = new Result() { Code = 0, Msg = "查询成功", Data = data };            }            catch (Exception ex)            {                return result = new Result() { Code = -2, Msg = "未知错误(" + ex.Message + ")" };            }        }        /// <summary>        /// 根据diid查询op费用列表        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        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 (dto.IsPaySign != -1)                {                    sqlWhere += string.Format(@" And c.IsPay = {0} ", dto.IsPaySign);                }                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;                Regex regex = new Regex("^[\u4e00-\u9fa5]*$");                //城市列表                var data = _sqlSugar.Queryable<Grp_NationalTravelFee>()                                    .Where(x => x.IsDel == 0)                                    .Select(x => new                                    {                                        x.Id,                                        x.Country,                                        x.City,                                    })                                    .ToList();                if (dto.PortType == 1)                {                    string sql = string.Format(@"select t.*,(select Name from Sys_SetData where isdel = 0 and id = t.priceType) as 'priceTypeStr',s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage,c.PayMoney,c.PayDid,c.IsPay from                                                 Grp_CarTouristGuideGroundReservations t                                                left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id  and c.isdel=0                                                left Join Sys_SetData s on s.Id=c.PaymentCurrency {0}                                                order by c.IsAuditGM,c.PayPercentage desc", sqlWhere);                    List<Grp_CarTouristGuideGroundView> infoViews = _sqlSugar.SqlQueryable<Grp_CarTouristGuideGroundView>(sql).ToList();                    foreach (var item in infoViews)                    {                        if (!regex.IsMatch(item.Area))                        {                            for (int i = 0; i < data.Count; i++)                            {                                if (item.Area.Equals(data[i].Id.ToString()))                                {                                    item.Area = string.Format("{0} {1}", data[i].Country, data[i].City);                                }                            }                        }                        if (string.IsNullOrWhiteSpace(item.priceTypeStr))                        {                            item.priceTypeStr = "未选择!";                        }                        if (item.OrbitalPrivateTransfer == 0) item.OrbitalPrivateTransferStr = "公转";                        else if (item.OrbitalPrivateTransfer == 1) item.OrbitalPrivateTransferStr = "私转";                        item.ServiceStartTime = Convert.ToDateTime(item.ServiceStartTime).ToString("yyyy-MM-dd");                        item.ServiceEndTime = Convert.ToDateTime(item.ServiceEndTime).ToString("yyyy-MM-dd");                        item.ServiceQuotedPrice = item.PayMoney;                        item.PayThenMoney = Math.Round(item.PayPercentage / 100 * item.ServiceQuotedPrice, 2);                        item.RemainingBalance = Math.Round(item.ServiceQuotedPrice - item.PayPercentage / 100 * item.ServiceQuotedPrice, 2);                        if (item.IsAuditGM == 0) item.IsAuditGMStr = "未审核";                        else if (item.IsAuditGM == 1) item.IsAuditGMStr = "已通过";                        else if (item.IsAuditGM == 2) item.IsAuditGMStr = "未通过";                        else if (item.IsAuditGM == 3) item.IsAuditGMStr = "自动审核";                        Sys_SetData s = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == item.PayDid);                        if (s != null)                        {                            item.PayStrd = s.Name;                        }                        else item.PayStrd = "未选择";                    }                    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 c.IsAuditGM,c.PayPercentage desc) as RowNumber,t.*,(select Name from Sys_SetData where isdel = 0 and id = t.priceType) as 'priceTypeStr',s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage,c.PayDid,c.PayMoney                                            from                                             Grp_CarTouristGuideGroundReservations t                                            left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id  and c.isdel=0                                            left Join Sys_SetData s on s.Id=c.PaymentCurrency {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)                    {                        if (!regex.IsMatch(item.Area))                        {                            for (int i = 0; i < data.Count; i++)                            {                                if (item.Area.Equals(data[i].Id.ToString()))                                {                                    item.Area = string.Format("{0} {1}", data[i].Country, data[i].City);                                }                            }                        }                        if (string.IsNullOrWhiteSpace(item.priceTypeStr))                        {                            item.priceTypeStr = "未选择!";                        }                        if (item.OrbitalPrivateTransfer == 0) item.OrbitalPrivateTransferStr = "公转";                        else if (item.OrbitalPrivateTransfer == 1) item.OrbitalPrivateTransferStr = "私转";                        item.ServiceStartTime = Convert.ToDateTime(item.ServiceStartTime).ToString("yyyy-MM-dd");                        item.ServiceEndTime = Convert.ToDateTime(item.ServiceEndTime).ToString("yyyy-MM-dd");                        if (item.IsAuditGM == 0) item.IsAuditGMStr = "未审核";                        else if (item.IsAuditGM == 1) item.IsAuditGMStr = "已通过";                        else if (item.IsAuditGM == 2) item.IsAuditGMStr = "未通过";                        else if (item.IsAuditGM == 3) item.IsAuditGMStr = "自动审核";                        item.ServiceQuotedPrice = item.PayMoney;                        item.PayThenMoney = Math.Round(item.PayPercentage / 100 * item.ServiceQuotedPrice, 2);                        item.RemainingBalance = Math.Round(item.ServiceQuotedPrice - item.PayPercentage / 100 * item.ServiceQuotedPrice, 2);                        Sys_SetData s = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == item.PayDid);                        if (s != null)                        {                            item.PayStrd = s.Name;                        }                        else item.PayStrd = "未选择";                    }                    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  and c.isdel=0                                                        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 = "未知错误" };            }            return result;        }        /// <summary>        /// OP费用录入填写详情        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        public async Task<Result> OpCarTouristGuideGroundContent(OpCarTouristGuideGroundContentDto dto)        {            Result result = new Result() { Code = -2, Msg = "未知错误" };            var di = _sqlSugar.Queryable<Grp_DelegationInfo>().First(x => x.Id == dto.DiId && x.IsDel == 0);            if (di == null)            {                result.Code = -1;                result.Msg = "无该团组信息!";                return result;            }            try            {                BeginTran();                List<Grp_CarTouristGuideGroundReservationsContent> carTouristList = dto.OPContentList.Select(item => new Grp_CarTouristGuideGroundReservationsContent                {                    Id = item.Id,                    DiId = dto.DiId,                    CTGGRId = dto.CTGGRId,                    SId = item.SId,                    Price = item.Price,                    PriceContent = item.priceContent,                    Currency = dto.Currency,                    CreateUserId = dto.CreateUserId,                    Units = item.Units,                    DatePrice = item.DatePrice,                    Count = item.Count,                }).ToList();                #region 旧数据处理                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm ss");                var ids = carTouristList.Select(x1 => x1.Id);                _ = _sqlSugar.Updateable<Grp_CarTouristGuideGroundReservationsContent>().Where(x => x.DiId == dto.DiId && x.CTGGRId == dto.CTGGRId && !ids.Contains(x.Id) && x.IsDel == 0).SetColumns(x => new Grp_CarTouristGuideGroundReservationsContent                {                    IsDel = 1,                    DeleteTime = time,                    DeleteUserId = dto.CreateUserId,                }).ExecuteCommand();                #endregion                if (carTouristList.Count > 0)                {                    #region 超支处理                    Dictionary<int, int> mealsDic = new Dictionary<int, int>()                    {                        {988,1074},                        {93,1075},                        {989,1076},                    };                    //限制只能选择地区                    var opSingle = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().First(x => x.Id == dto.CTGGRId && x.IsDel == 0);                    var opSingleCityId = 0;                    Grp_NationalTravelFee cityPrice = null;                    string priceCity = string.Empty;                    //三公费用                    if (int.TryParse(opSingle.Area, out opSingleCityId))                    {                        cityPrice = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x =>                         x.Id == opSingleCityId                        ).First();                        priceCity = cityPrice == null ? string.Empty : cityPrice.Country + cityPrice?.City;                    }                    else                    {                        cityPrice = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x =>                            !string.IsNullOrEmpty(x.City) && x.City.Contains(opSingle.Area)                        ).First();                        priceCity = opSingle.Area;                    }                    cityPrice ??= new Grp_NationalTravelFee                    {                        FoodCost = "0",                        Id = 0,                    };                    List<Tuple<int, string, int, decimal>> arr = new List<Tuple<int, string, int, decimal>>();                    arr.Add(new Tuple<int, string, int, decimal>(1074, "早餐超支费用", 1077, 1M));  // sid name setdataid 系数                    arr.Add(new Tuple<int, string, int, decimal>(1075, "午餐超支费用", 1078, 1M));                    arr.Add(new Tuple<int, string, int, decimal>(1076, "晚餐超支费用", 1079, 1M));                    arr.Add(new Tuple<int, string, int, decimal>(982, "车超时费用", 1050, 2.4M));                    arr.Add(new Tuple<int, string, int, decimal>(1059, "导游超时费用", 1072, 1M));                    arr.Add(new Tuple<int, string, int, decimal>(1085, "景点门票超支费用", 1086, 1.2M));                    arr.Add(new Tuple<int, string, int, decimal>(1073, "翻译超时费用", 1087, 1.5M));                    //超支费用表(数据添加)  Fin_GroupExtraCost                    List<Fin_GroupExtraCost> groupExtraCostsArr = new List<Fin_GroupExtraCost>();                    List<List<Fin_GroupExtraCost>> enterOverspendArr = new List<List<Fin_GroupExtraCost>>();                    var aMeal = cityPrice.FoodCost.ObjToDecimal() / 2; //一顿三公费用                    var findSetDataCurr = _sqlSugar.Queryable<Sys_SetData>().First(q => q.Id == dto.toCurr && q.IsDel == 0);                    var carCurr = _sqlSugar.Queryable<Sys_SetData>().First(q => q.Id == carTouristList.First().Currency && q.IsDel == 0);                    foreach (var item in arr)                    {                        var a = carTouristList.Where(x => x.SId == item.Item1 && x.Price != 0).Select(x => new Fin_GroupExtraCost                        {                            Coefficient = item.Item4,                            CreateTime = DateTime.Now,                            CreateUserId = dto.CreateUserId,                            DiId = dto.DiId,                            FilePath = string.Empty,                            IsDel = 0,                            PriceCount = x.Count,                            Price = x.Price,                            PriceDt = x.DatePrice.ObjToDate(),                            PriceCurrency = x.Currency,                            PriceSum = x.Count * x.Price,                            PriceName = di.TeamName + "-" + priceCity + "-" + $"{item.Item2}(地接导入)",                            PriceType = 1028,                            PriceDetailType = item.Item3,                            Remark = x.PriceContent,                            Area = opSingleCityId                        }).ToList();                        if (a.Count > 0)                        {                            enterOverspendArr.Add(a);                        }                    }                    //数组中的费用                    if (enterOverspendArr.Count > 0)                    {                        groupExtraCostsArr.AddRange(enterOverspendArr.SelectMany(x => x).ToList());                    }                    var start = opSingle.ServiceStartTime.ObjToDate();                    var end = opSingle.ServiceEndTime.ObjToDate();                    string remake = string.Empty;                    var exitMealCount = 0;                    var price = 0M;                    //var day = 0;                    var consumerMealStr = string.Empty;                    var consumerMealNumber = 0;                    var consumerMealAllPrice = 0.00M;                    while (start <= end)                    {                        //查看每日每顿是否存在超支                        //不存在则加入退费 (三公一顿 - 消费金额)                        //93 , 989                        bool isExistsWu = carTouristList.Where(x => x.SId == mealsDic[93] && x.IsDel == 0 && DateTime.Compare(start, x.DatePrice.ObjToDate()) == 0 && x.Price > 0).Count() == 0;                        bool isExistsWan = carTouristList.Where(x => x.SId == mealsDic[989] && x.IsDel == 0 && DateTime.Compare(start, x.DatePrice.ObjToDate()) == 0 && x.Price > 0).Count() == 0;                        var mealPriceWu = carTouristList.Where(x => x.SId == 93 && x.IsDel == 0 && DateTime.Compare(start, x.DatePrice.ObjToDate()) == 0).Sum(x => x.Price * x.Count);                        var mealPriceWan = carTouristList.Where(x => x.SId == 989 && x.IsDel == 0 && DateTime.Compare(start, x.DatePrice.ObjToDate()) == 0).Sum(x => x.Price * x.Count);                        var mealPriceWuChao = carTouristList.Where(x => x.SId == mealsDic[93] && x.IsDel == 0 && DateTime.Compare(start, x.DatePrice.ObjToDate()) == 0).Sum(x => x.Price * x.Count);                        var mealPriceWanChao = carTouristList.Where(x => x.SId == mealsDic[989] && x.IsDel == 0 && DateTime.Compare(start, x.DatePrice.ObjToDate()) == 0).Sum(x => x.Price * x.Count);                        if (mealPriceWu > 0)                        {                            consumerMealStr += $"{start.ToString("M/d")}午餐消费{mealPriceWu + mealPriceWuChao}{carCurr?.Name},";                            consumerMealNumber++;                            consumerMealAllPrice += mealPriceWu + mealPriceWuChao;                        }                        if (mealPriceWan > 0)                        {                            consumerMealStr += $"{start.ToString("M/d")}晚餐消费{mealPriceWan + mealPriceWanChao}{carCurr?.Name},";                            consumerMealNumber++;                            consumerMealAllPrice += mealPriceWan + mealPriceWanChao;                        }                        if (isExistsWu && isExistsWan)                        {                            remake += $"{start.ToString("M/d")}午餐和晚餐,";                            exitMealCount += 2;                            price += (aMeal * 2 * di.VisitPNumber) - (mealPriceWu * dto.Rate) - (mealPriceWan * dto.Rate);                        }                        else if (isExistsWu)                        {                            remake += $"{start.ToString("M/d")}午餐,";                            exitMealCount += 1;                            price += (aMeal * di.VisitPNumber) - (mealPriceWu * dto.Rate);                        }                        else if (isExistsWan)                        {                            remake += $"{start.ToString("M/d")}晚餐,";                            exitMealCount += 1;                            price += (aMeal * di.VisitPNumber) - (mealPriceWan * dto.Rate);                        }                        start = start.AddDays(1);                        //day++;                    }                    var priceTypeArr = new int[] { 1061, 1069 };                    if (exitMealCount > 0 && priceTypeArr.Contains(opSingle.PriceType))                    {                        remake = remake.TrimEnd(',');                        remake += $"财政 {findSetDataCurr?.Name} {aMeal} * {di.VisitPNumber} * {exitMealCount}餐";                        remake += $",[TuT]{consumerMealStr} 共{consumerMealNumber}顿 {consumerMealAllPrice} {carCurr?.Name}";                        decimal priceInt = price / di.VisitPNumber / exitMealCount;                        groupExtraCostsArr.Add(new Fin_GroupExtraCost                        {                            Coefficient = 1,                            CreateTime = DateTime.Now,                            CreateUserId = dto.CreateUserId,                            DiId = dto.DiId,                            FilePath = string.Empty,                            IsDel = 0,                            PriceCount = di.VisitPNumber * exitMealCount * -1,                            Price = priceInt,                            PriceDt = opSingle.ServiceStartTime.ObjToDate(),                            PriceCurrency = findSetDataCurr == null ? dto.toCurr : findSetDataCurr.Id,                            PriceSum = (di.VisitPNumber * exitMealCount * -1) * priceInt,                            PriceName = di.TeamName + "-" + priceCity + "-" + $"退餐费(地接导入)",                            PriceType = 1028,                            PriceDetailType = 1088,                            Remark = remake,                            Area = opSingleCityId                        });                    }                    var needToConfirm = new int[] { 1088, 1050 };                    if (groupExtraCostsArr.Count > 0)                    {                        foreach (var item in groupExtraCostsArr)                        {                            var ManagerConfirm = needToConfirm.Contains(item.PriceDetailType) ? 0 : 1;                            var SupervisorConfirm = needToConfirm.Contains(item.PriceDetailType) ? 0 : 1;                            var SYsupervisorConfirm = needToConfirm.Contains(item.PriceDetailType) ? 0 : 1;                            var QuerySgin = _sqlSugar.Queryable<Fin_GroupExtraCost>()                                .Where(x => x.PriceName == item.PriceName && x.DiId == item.DiId && x.IsDel == 0 && x.PriceDt.ToString("yyyy-MM-dd") == item.PriceDt.ToString("yyyy-MM-dd"))                                .First();                            if (QuerySgin == null)                            {                                var resultId = await PostGroupExtraCost_Operator(new Fin_GroupExtraCostDto_OP                                {                                    coefficient = item.Coefficient,                                    createUser = dto.CreateUserId,                                    currency = item.PriceCurrency,                                    diId = item.DiId,                                    editType = 1,                                    filePath = string.Empty,                                    payee = dto.Payee,                                    PortType = 1,                                    PriceCount = item.PriceCount,                                    priceName = item.PriceName,                                    remark = item.Remark,                                    price = item.Price,                                    priceDetailType = item.PriceDetailType,                                    priceType = item.PriceType,                                    PriceDt = item.PriceDt.ToString("yyyy-MM-dd"),                                    payType = dto.PayDId,                                    costSign = dto.OrbitalPrivateTransfer,                                    Area = item.Area,                                    ManagerConfirm = ManagerConfirm,                                    SupervisorConfirm = SupervisorConfirm,                                    SYsupervisorConfirm = SYsupervisorConfirm                                });                                _sqlSugar.Insertable<Fin_LocalGuideRelevancyOverspend>(new Fin_LocalGuideRelevancyOverspend                                {                                    CreateTime = DateTime.Now,                                    CreateUserId = dto.CreateUserId,                                    IsDel = 0,                                    LocalGuideId = opSingle.Id,                                    OverspendId = resultId.Data,                                }).ExecuteCommand();                            }                            else                            {                                item.Id = QuerySgin.Id;                                _ = await PostGroupExtraCost_Operator(new Fin_GroupExtraCostDto_OP                                {                                    coefficient = item.Coefficient,                                    createUser = dto.CreateUserId,                                    currency = item.PriceCurrency,                                    diId = item.DiId,                                    editType = 2,                                    filePath = string.Empty,                                    payee = dto.Payee,                                    PortType = 1,                                    PriceCount = item.PriceCount,                                    priceName = item.PriceName,                                    remark = item.Remark,                                    price = item.Price,                                    priceDetailType = item.PriceDetailType,                                    priceType = item.PriceType,                                    PriceDt = item.PriceDt.ToString("yyyy-MM-dd"),                                    payType = dto.PayDId,                                    costSign = dto.OrbitalPrivateTransfer,                                    Id = item.Id,                                    Area = item.Area,                                });                            }                        }                        _foreignReceivablesRepository.OverSpSeteceivables(new OverSpSeteceivablesDto                        {                            CreateUserId = dto.CreateUserId,                            DiId = dto.DiId,                        });                    }                    #endregion                    var existingRecords = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>()                                                         .Where(a => carTouristList.Select(item => item.Id).Contains(a.Id) &&                                                                     a.CTGGRId == dto.CTGGRId &&                                                                     a.IsDel == 0                                                                     )                                                         .ToListAsync();                    var existingRecordsDict = existingRecords.ToDictionary(a => (a.Id));                    var insertList = new List<Grp_CarTouristGuideGroundReservationsContent>();                    var updateList = new List<Grp_CarTouristGuideGroundReservationsContent>();                    foreach (var item in carTouristList)                    {                        if (!existingRecordsDict.TryGetValue((item.Id), out var existingRecord))                        {                            insertList.Add(item);                        }                        else                        {                            existingRecord.Price = item.Price;                            existingRecord.PriceContent = item.PriceContent;                            existingRecord.Currency = dto.Currency;                            existingRecord.Remark = item.Remark;                            existingRecord.DatePrice = item.DatePrice;                            existingRecord.Count = item.Count;                            existingRecord.Units = item.Units;                            updateList.Add(existingRecord);                        }                    }                    // 执行批量插入                    if (insertList.Any())                    {                        var insertIds = await _sqlSugar.Insertable(insertList).ExecuteReturnIdentityAsync();                        if (insertIds == 0)                        {                            throw new Exception("添加失败,请稍后重试!");                        }                    }                    // 执行批量更新                    if (updateList.Any())                    {                        var updateCount = await _sqlSugar.Updateable(updateList).ExecuteCommandAsync();                        if (updateCount == 0)                        {                            throw new Exception("修改失败,请稍后重试!");                        }                    }                }                Regex regex = new Regex("^[\u4e00-\u9fa5]{0,}$");                #region 修改C表数据                Grp_CreditCardPayment c = new Grp_CreditCardPayment();                c.PaymentCurrency = dto.Currency;                for (int i = 0; i < dto.SelectCheck.Count; i++)                {                    if (!regex.IsMatch(dto.SelectCheck[i]))                    {                        for (int j = 0; j < carTouristList.Count; j++)                        {                            if (int.Parse(dto.SelectCheck[i]) == carTouristList[j].SId)                            {                                c.PayMoney += carTouristList[j].Price * carTouristList[j].Count;                            }                        }                    }                    else                    {                        c.PayMoney = carTouristList.Sum(x => x.Price * x.Count);                        break;                    }                }                c.PayPercentage = dto.PayPercentage;                c.ConsumptionDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");                c.CTable = 79;                c.CId = dto.CTGGRId;                c.IsAuditGM = 0;                c.PayDId = dto.PayDId;                c.DIId = dto.DiId;                c.OrbitalPrivateTransfer = dto.OrbitalPrivateTransfer;                c.Payee = dto.Payee;                c.CreateUserId = dto.CreateUserId;                //--------------------添加C表字段---------------                c.ConsumptionPatterns = dto.ConsumptionPatterns;                c.CTDId = dto.Ctdid;                c.BankNo = dto.BankNo;                c.CardholderName = dto.CardholderName;                c.ConsumptionDate = dto.ConsumptionDate;                c.CompanyBankNo = dto.CompanyBankNo;                c.OtherBankName = dto.OtherBankName;                c.OtherSideNo = dto.OtherSideNo;                c.OtherSideName = dto.OtherSideName;                if (c.PayDId == 72) c.IsPay = 1;                else c.IsPay = 0;                c.RMBPrice = c.PayMoney;                c.DayRate = 1;                #region 老汇率获取                //Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == dto.DiId && a.IsDel == 0 && a.CTable == 79);                //List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();                //if (_TeamRate != null)                //{                //    Sys_SetData _SetData = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == c.PaymentCurrency);                //    if (_SetData != null)                //    {                //        currencyInfos = CommonFun.GetCurrencyChinaToList(_TeamRate.Remark);                //        CurrencyInfo CurrencyRate = currencyInfos.FirstOrDefault(a => a.CurrencyCode == _SetData.Name);                //        if (CurrencyRate != null)                //        {                //            c.RMBPrice = c.PayMoney * Convert.ToDecimal(CurrencyRate.Rate);                //            c.DayRate = CurrencyRate.Rate;                //        }                //    }                //}                #endregion                var rate = await _setDataRep.PostCurrencyByDiid(dto.DiId, 79, dto.Currency);                if (rate.Code == 0)                {                    var rateData = rate.Data as CurrencyInfo;                    if (rateData != null)                    {                        c.RMBPrice = c.PayMoney * rateData.Rate;                        c.DayRate = rateData.Rate;                    }                }                int noticeSign = 1; //企业微信通知标识                int noticeCcpId = 0;                Grp_CreditCardPayment grp_CreditCard = _sqlSugar.Queryable<Grp_CreditCardPayment>().First(a => a.CId == dto.CTGGRId && a.IsDel == 0 && a.CTable == 79 && a.DIId == dto.DiId);                if (grp_CreditCard != null)//修改                {                    int CTable = await _sqlSugar.Updateable<Grp_CreditCardPayment>().Where(a => a.CId == dto.CTGGRId && a.CTable == 79 && a.DIId == dto.DiId).SetColumns(a => new Grp_CreditCardPayment                    {                        PaymentCurrency = c.PaymentCurrency,                        PayMoney = c.PayMoney,                        PayPercentage = c.PayPercentage,                        CTable = c.CTable,                        PayDId = c.PayDId,                        OrbitalPrivateTransfer = c.OrbitalPrivateTransfer,                        Payee = c.Payee,                        IsPay = c.IsPay,                        RMBPrice = c.RMBPrice,                        DayRate = c.DayRate,                        //添加属性                        ConsumptionPatterns = c.ConsumptionPatterns,                        CTDId = c.CTDId,                        BankNo = c.BankNo,                        CardholderName = c.CardholderName,                        ConsumptionDate = c.ConsumptionDate,                        CompanyBankNo = c.CompanyBankNo,                        OtherBankName = c.OtherBankName,                        OtherSideNo = c.OtherSideNo,                        OtherSideName = c.OtherSideName                    }).ExecuteCommandAsync();                    noticeSign = 2;                    noticeCcpId = grp_CreditCard.Id;                    if (CTable == 0)                    {                        RollbackTran();                        return result = new Result() { Code = -2, Msg = "修改失败" };                    }                }                else//添加                {                    int id = await _sqlSugar.Insertable(c).ExecuteReturnIdentityAsync();                    noticeCcpId = id;                    if (id == 0)                    {                        RollbackTran();                        return result = new Result() { Code = -2, Msg = "添加失败" };                    }                }                #endregion                _ = await _sqlSugar.Updateable<Grp_CarTouristGuideGroundReservations>()                                   .Where(a => a.Id == dto.CTGGRId && a.DiId == dto.DiId && a.IsDel == 0)                                   .SetColumns(a => new Grp_CarTouristGuideGroundReservations                                   {                                       CId = dto.Currency,                                       ServiceQuotedPrice = c.PayMoney,                                       OrbitalPrivateTransfer = dto.OrbitalPrivateTransfer,                                       SelectCheck = string.Join(',', dto.SelectCheck),                                       Rate = dto.Rate,                                       toCurr = dto.toCurr                                   })                                   .ExecuteCommandAsync();                var data = new { ccpId = noticeCcpId, sign = noticeSign };                result = new Result() { Code = 0, Msg = "保存成功", Data = data };                CommitTran();            }            catch (Exception ex)            {                RollbackTran();                result = new Result() { Code = -2, Msg = $"接口异常!({ex.Message})" };            }            return result;        }        /// <summary>        /// 超支费用        /// 1增、2改、3删        /// </summary>        /// <param name="dto"></param>        /// <returns></returns>        private async Task<Result> PostGroupExtraCost_Operator(Fin_GroupExtraCostDto_OP dto)        {            Result rt = new Result();            #region 验证            #endregion            Fin_GroupExtraCost _entity = new Fin_GroupExtraCost();            _entity.DiId = dto.diId;            _entity.PriceName = dto.priceName;            _entity.Price = dto.price;            _entity.PriceCurrency = dto.currency;            _entity.PriceType = dto.priceType;            _entity.Coefficient = dto.coefficient;            _entity.PriceDetailType = dto.priceDetailType;            _entity.FilePath = dto.filePath;            _entity.Remark = dto.remark;            _entity.PriceCount = dto.PriceCount;            _entity.PriceDt = DateTime.Parse(dto.PriceDt);            _entity.PriceSum = dto.price * dto.PriceCount;            _entity.Area = dto.Area;            _entity.SupervisorConfirm = dto.SupervisorConfirm;            _entity.ManagerConfirm = dto.ManagerConfirm;            _entity.SYsupervisorConfirm = dto.SYsupervisorConfirm;            _daiRep.BeginTran();            if (dto.editType == 1)            {                _entity.CreateUserId = dto.createUser;                _entity.CreateTime = DateTime.Now;                _entity.IsDel = 0;                int returnId = await _daiRep.AddAsyncReturnId<Fin_GroupExtraCost>(_entity);                if (returnId > 0)                {                    dto.Id = returnId;                }            }            else if (dto.editType == 2)            {                bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost                {                    PriceName = dto.priceName,                    Price = dto.price,                    PriceCurrency = dto.currency,                    PriceType = dto.priceType,                    PriceDetailType = dto.priceDetailType,                    Coefficient = dto.coefficient,                    FilePath = dto.filePath,                    Remark = dto.remark,                    PriceCount = dto.PriceCount,                    PriceDt = _entity.PriceDt,                    PriceSum = _entity.PriceSum,                    Area = _entity.Area,                });                if (!res)                {                    _daiRep.RollbackTran();                    //Ok(JsonView(false, "2操作失败!"))                    rt.Msg = "2操作失败!";                    return rt;                }            }            else if (dto.editType == 3)            {                string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");                bool res = await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.Id == dto.Id, s => new Fin_GroupExtraCost                {                    IsDel = 1,                    DeleteTime = delTime,                    DeleteUserId = dto.createUser                });                if (!res)                {                    _daiRep.RollbackTran();                    rt.Msg = "3操作失败!";                    return rt;                }            }            else            {                _daiRep.RollbackTran();                rt.Msg = "未知的editType";                return rt;            }            if (!(await extraCost_editCreditCardPayment(dto)))            {                rt.Msg = "ccp操作失败";                return rt;            }            _daiRep.CommitTran();            rt.Code = 0;            rt.Msg = "操作成功";            rt.Data = dto.Id;            return rt;        }        private async Task<bool> extraCost_editCreditCardPayment(Fin_GroupExtraCostDto_OP costDto)        {            //设置团组汇率            decimal dcm_dayrate = 1M;            decimal dcm_rmbPrice = costDto.price;            int ispay = costDto.payType == 72 ? 1 : 0;            if (costDto.costSign != 3)            {                //获取新汇率  int diId,int CId, int currencyId                Result rate = await _setDataRep.PostCurrencyByDiid(costDto.diId, 1015, costDto.currency);                if (rate.Code == 0)                {                    var rateInfo = (rate.Data as CurrencyInfo);                    if (rateInfo is not null)                    {                        dcm_dayrate = rateInfo.Rate;                        dcm_rmbPrice = rateInfo.Rate * dcm_rmbPrice;                    }                    else                    {                        dcm_dayrate = 1;                    }                }            }            Grp_CreditCardPayment ccp = _daiRep.Query<Grp_CreditCardPayment>(s => s.CId == costDto.Id && s.CTable == 1015).First();            if (ccp == null)            {                ccp = new Grp_CreditCardPayment();                ccp.PayDId = costDto.payType;// dto                ccp.ConsumptionPatterns = "";                ccp.ConsumptionDate = "";                ccp.CTDId = costDto.payCardId;// dto                ccp.BankNo = "";                ccp.CardholderName = "";                ccp.PayMoney = costDto.price;// dto                ccp.PaymentCurrency = costDto.currency;// dto                ccp.CompanyBankNo = "";                ccp.OtherBankName = "";                ccp.OtherSideNo = "";                ccp.OtherSideName = "";                ccp.Remark = "";                ccp.CreateUserId = costDto.createUser;                ccp.CreateTime = DateTime.Now;                ccp.MFOperator = 0;                ccp.MFOperatorDate = "";                ccp.IsAuditDM = 0;                ccp.AuditDMOperate = 0;                ccp.AuditDMDate = "";                ccp.IsAuditMF = 0;                ccp.AuditMFOperate = 0;                ccp.AuditMFDate = "";                ccp.IsAuditGM = 0;                ccp.AuditGMOperate = 0;                ccp.AuditGMDate = "";                ccp.IsPay = ispay; // upd                ccp.DIId = costDto.diId;// dto                ccp.CId = costDto.Id;// dto                ccp.CTable = 1015; //超支费用指向id                ccp.IsDel = 0;                ccp.PayPercentage = 100M;                ccp.PayThenMoney = 0M;                ccp.PayPercentageOld = 100M;                ccp.PayThenMoneyOld = 0M;                ccp.UpdateDate = "";                ccp.Payee = costDto.payee;// dto                ccp.OrbitalPrivateTransfer = costDto.costSign;// dto                ccp.ExceedBudget = 0;                ccp.DayRate = dcm_dayrate; //upd                ccp.RMBPrice = dcm_rmbPrice; //upd                int ccpInsertId = _daiRep.AddReturnId<Grp_CreditCardPayment>(ccp);                if (ccpInsertId > 0)                {                    return true;                }            }            else            {                if (costDto.editType == 2)                {                    bool res = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment                    {                        PayDId = costDto.payType,                        CTDId = costDto.payCardId,                        PayMoney = costDto.price,                        PaymentCurrency = costDto.currency,                        IsPay = ispay,                        Payee = costDto.payee,                        OrbitalPrivateTransfer = costDto.costSign,                        DayRate = dcm_dayrate,                        RMBPrice = dcm_rmbPrice                    });                    return res;                }                else if (costDto.editType == 3)                {                    string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");                    bool res2 = _daiRep.Update<Grp_CreditCardPayment>(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment                    {                        IsDel = 1,                        DeleteTime = delTime,                        DeleteUserId = costDto.createUser                    });                    return res2;                }            }            return false;        }        public async Task<Result> GroupExtraCost_OperatorList(List<Fin_GroupExtraCostDto_OP> dto)        {            Result rt = new Result();            foreach (var item in dto)            {                await _daiRep.UpdateAsync<Fin_GroupExtraCost>(s => s.PriceName == item.priceName && s.DiId == item.diId,                    s => new Fin_GroupExtraCost                    {                        IsDel = 1,                        DeleteTime = DateTime.Now.ToString("yyyy-MM-dd"),                        DeleteUserId = item.createUser                    });                rt = await PostGroupExtraCost_Operator(item);            }            return rt;        }    }}
 |