| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953 | using Microsoft.AspNetCore.Mvc;using NPOI.POIFS.Properties;using NPOI.SS.Formula.Functions;using OASystem.API.OAMethodLib;using OASystem.Domain.Dtos.Groups;using OASystem.Domain.Dtos.Statistics;using OASystem.Domain.Entities.Financial;using OASystem.Domain.ViewModels.Financial;using OASystem.Domain.ViewModels.Groups;using OASystem.Domain.ViewModels.Statistics;using OASystem.Infrastructure.Repositories.Groups;using static OpenAI.GPT3.ObjectModels.SharedModels.IOpenAiModels;using System;using OASystem.Domain.Entities.Customer;using System.Collections.Generic;using Microsoft.AspNetCore.Mvc.RazorPages;using Microsoft.VisualBasic;using OASystem.Domain.Entities.Groups;using Microsoft.Extensions.DependencyInjection;using Aspose.Words.Lists;using static OASystem.API.OAMethodLib.GeneralMethod;using TypeInfo = OASystem.Domain.ViewModels.Statistics.TypeInfo;using System.Net.NetworkInformation;using System.ComponentModel.Design;using NetTaste;using OASystem.Domain.ViewModels.QiYeWeChat;using NPOI.POIFS.Crypt.Dsig;using EyeSoft.SequentialIdentity;using Microsoft.Extensions.Configuration;namespace OASystem.API.Controllers{    /// <summary>    /// 统计模块    /// </summary>    [Route("api/[controller]")]    [ApiController]    public class StatisticsController : ControllerBase    {        private readonly int _decimalPlaces;        private readonly IConfiguration _config;        private readonly IMapper _mapper;        private readonly SqlSugarClient _sqlSugar;        private readonly DelegationInfoRepository _groupRep;        private readonly SetDataRepository _setDataRep;        private readonly TeamRateRepository _teamRateRep;        private readonly VisitingClientsRepository _visitingClientsRep;        /// <summary>        /// Init        /// </summary>        /// <param name="mapper"></param>        /// <param name="sqlSugar"></param>        /// <param name="groupRep"></param>        /// <param name="setDataRep"></param>        public StatisticsController(IMapper mapper, IConfiguration config, SqlSugarClient sqlSugar, DelegationInfoRepository groupRep, SetDataRepository setDataRep, TeamRateRepository teamRate, VisitingClientsRepository visitingClientsRep)        {            _mapper = mapper;            _config = config;            _groupRep = groupRep;            _setDataRep = setDataRep;            _sqlSugar = sqlSugar;            _teamRateRep = teamRate;            _visitingClientsRep = visitingClientsRep;        }        #region 团组报表        /// <summary>        ///  团组报表        ///  Items         /// </summary>        /// <param name="_dto">团组列表请求dto</param>        /// <returns></returns>        [HttpPost("PostGroupStatementItems")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostGroupStatementItems(GroupStatementItemsDto _dto)        {            #region  参数验证            if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));            if (_dto.PageId < 1) return Ok(JsonView(false, "页面Id为空"));            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));            #endregion            #endregion            if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS            {                string sqlWhere = string.Empty;                if (_dto.IsSure == 0) //未完成                {                    sqlWhere += string.Format(@" And IsSure = 0");                }                else if (_dto.IsSure == 1) //已完成                {                    sqlWhere += string.Format(@" And IsSure = 1");                }                if (!string.IsNullOrEmpty(_dto.SearchCriteria))                {                    string tj = _dto.SearchCriteria;                    sqlWhere += string.Format(@"And (ssd.Name Like '%{0}%' Or TeamName Like '%{1}%' Or ClientName Like '%{2}%' Or  ClientName Like '%{3}%' Or su.CnName  Like '%{4}%')",                       tj, tj, tj, tj, tj);                }                string sql = string.Format(@"Select row_number() over(order by gdi.VisitDate Desc) as Row_Number, 											    gdi.Id,TourCode,ssd1.Id TeamLevId,ssd1.Name TeamLev,TeamName,											    ClientName,ClientUnit,VisitDate,ssd.Id TeamTypeId, ssd.Name TeamType,											    VisitDays,VisitPNumber,su.CnName JietuanOperator,IsSure,gdi.CreateTime,											    pr.LastCollectionTime											    From  Grp_DelegationInfo gdi											    Left Join Sys_SetData ssd On gdi.TeamDid = ssd.Id 											    Left Join Sys_SetData ssd1 On gdi.TeamLevSId = ssd1.Id											    Left Join Sys_Users su On gdi.JietuanOperator = su.Id											    Left Join (												    SELECT Diid, MAX(CreateTime) LastCollectionTime												    FROM Fin_ProceedsReceived												    Where IsDel = 0												    GROUP BY Diid											    ) pr On gdi.Id = pr.Diid										    Where gdi.IsDel = 0 {0} ", sqlWhere);                RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解                var _DelegationList = await _sqlSugar.SqlQueryable<GroupStatementItemView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync                var _view = new                {                    PageFuncAuth = pageFunAuthView,                    Data = _DelegationList                };                return Ok(JsonView(true, "查询成功!", _view, total));            }            else            {                return Ok(JsonView(false, "查询失败"));            }        }        /// <summary>        ///  团组报表        ///  Details         /// </summary>        /// <param name="_dto">团组列表请求dto</param>        /// <returns></returns>        [HttpPost("PostGroupStatementDetails")]        //[JsonConverter(typeof(DecimalConverter), 2)]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostGroupStatementDetails(GroupStatementDetailsDto _dto)        {            /*              * 团组报表计算方式             * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()             * 应收金额 = 应收表.Sum()             * 已收金额 = 已收表.Sum()             * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出             * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出             *              */            #region  参数验证            if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));            if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id            if (_dto.DiId < 1) return Ok(JsonView(false, "团组Id为空"));            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));            #endregion            #endregion            if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS            {                GroupStatementDetailsView _view = new GroupStatementDetailsView();                #region 费用类型 币种,转账,客户信息                List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();                var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();                #endregion                #region 团组收入                GroupIncomeView _giView = new GroupIncomeView();                /*                 * 应收报表                 */                decimal frTotalAmount = 0.00M;//应收总金额                string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,										        sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime										        From Fin_ForeignReceivables fr										        Left Join Sys_SetData sd On fr.Currency = sd.Id										        Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _dto.DiId);                List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();                frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);                _giView.Receivables = _frViews;                _giView.ReceivableStr = string.Format(@"应收款合计:{0} CNY(人民币)", frTotalAmount.ConvertToDecimal1().ToString("#0.00"));                /*                 * 已收报表                 */                decimal prTotalAmount = 0.00M;//已收总金额                string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,										        sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,										        pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime										        From Fin_ProceedsReceived  pr										        Left Join Sys_SetData sd1 On pr.Currency = sd1.Id										        Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id										        Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _dto.DiId);                List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();                prTotalAmount = _prViews.Sum(it => it.Price);                _giView.ProceedsReceivedViews = _prViews;                _giView.ProceedsReceivedStr = string.Format(@$"应收合计:{frTotalAmount.ToString("#0.00")} CNY  已收款合计:{prTotalAmount.ConvertToDecimal1().ToString("#0.00")} CNY");                /*                 * 超支费用                  */                decimal exTotalAmount = 0.00M;                string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,(gec.PriceSum * gec.Coefficient) As PayMoney,sd1.Name As PaymentCurrency,													   (gec.PriceSum * gec.Coefficient * ccp.DayRate) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,													   sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime												From OA2023DB.dbo.Fin_GroupExtraCost gec												Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId                                                Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                 Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                Left Join Sys_Users u On ccp.CreateUserId = u.Id												Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _dto.DiId);                List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();                #region 超支费用 - 模拟数据                //if (_ExtraCostsViews.Count < 1)                //{                //    _ExtraCostsViews.Add(new Gsd_ExtraCostsView()                //    {                //        GECId = 0,                //        GECDiId = 2334,                //        PriceName = "模拟数据-超支费用名称",                //        PayMoney = 1000.00M,                //        PaymentCurrency = "CNY",                //        DayRate = 1.0000M,                //        CNYPrice = 1000.00M,                //        Payee = "模拟数据-超支费用收款方",                //        OrbitalPrivateTransfer = 1,                //        PayWay = "刷卡",                //        CardType = "招行卡",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //    _ExtraCostsViews.Add(new Gsd_ExtraCostsView()                //    {                //        GECId = 0,                //        GECDiId = 2334,                //        PriceName = "模拟数据-超支费用名称",                //        PayMoney = 1000.00M,                //        PaymentCurrency = "CNY",                //        DayRate = 1.0000M,                //        CNYPrice = 1000.00M,                //        Payee = "模拟数据-超支费用收款方",                //        OrbitalPrivateTransfer = 1,                //        PayWay = "刷卡",                //        CardType = "招行卡",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //}                #endregion                exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);                _giView.ExtraCostsViews = _ExtraCostsViews;                _giView.ExtraCostsStr = string.Format(@"人民币总费用:{0} CNY", exTotalAmount.ConvertToDecimal1().ToString("#0.00"));                /*                 * 收款退还                 */                decimal promTotalAmount = 0.00M;// 收款退还总金额                List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();                //删除了  And prom.PriceType = 1                string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,										         prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,										         prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime										         From Fin_PaymentRefundAndOtherMoney prom										         Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId										         Left Join Sys_Users u On ccp.CreateUserId = u.Id										         Where prom.IsDel = 0  And prom.PayType = 1 And ccp.CTable = 285										         And ccp.IsAuditGM = 1 And ccp.IsPay = 1										         And prom.DiId = {0} Order By PrCreateTime", _dto.DiId);                var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();                foreach (var ropItem in _promDatas)                {                    string thisCueencyCode = "Unknown";                    string thisCueencyName = "Unknown";                    var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();                    if (currency != null)                    {                        thisCueencyCode = currency.Name;                        thisCueencyName = currency.Remark;                    }                    string orbitalPrivateTransferStr = "Unknown";                    var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();                    if (orbitalPrivateTransfer != null)                    {                        orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;                    }                    string payStr = "Unknown";                    var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();                    if (pay != null)                    {                        payStr = pay.Name;                    }                    Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()                    {                        Id = ropItem.Id,                        DiId = ropItem.DIId,                        PriceName = ropItem.PrPriceName,                        PayCurrencyCode = thisCueencyCode,                        PayCurrencyName = thisCueencyName,                        Price = ropItem.PrPrice,                        CNYPrice = ropItem.RMBPrice,                        ThisRate = ropItem.DayRate,                        Payee = ropItem.Payee,                        PayTime = ropItem.AuditGMDate,                        OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,                        PayType = payStr,                        IsPay = ropItem.IsPay,                        Applicant = ropItem.Appliction                    };                    _promView.Add(gsd_PaymentRefund);                }                #region 收款退还 - 模拟数据                //if (_promView.Count < 1)                //{                //    _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()                //    {                //        Id = 0,                //        DiId = 2334,                //        PriceName = "模拟数据-费用名称",                //        PayCurrencyCode = "CNY",                //        PayCurrencyName = "人民币",                //        Price = 1000.00M,                //        CNYPrice = 1000.00M,                //        ThisRate = 1.00M,                //        Payee = "模拟数据-收款方",                //        PayTime = "2023-01-01 15:20:01",                //        OrbitalPrivateTransfer = 1,                //        PayType = "刷卡",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //    _promView.Add(new Gsd_PaymentRefundAndOtherMoneyView()                //    {                //        Id = 0,                //        DiId = 2334,                //        PriceName = "模拟数据-费用名称",                //        PayCurrencyCode = "CNY",                //        PayCurrencyName = "人民币",                //        Price = 1000.00M,                //        CNYPrice = 1000.00M,                //        ThisRate = 1.00M,                //        Payee = "模拟数据-收款方",                //        PayTime = "2023-01-01 15:20:01",                //        OrbitalPrivateTransfer = 1,                //        PayType = "刷卡",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //}                #endregion                promTotalAmount = _promView.Sum(it => it.CNYPrice);                _giView.PaymentRefundAndOtherMoneyViews = _promView;                _giView.PaymentRefundAndOtherMoneyStr = string.Format(@"人民币总费用:{0} CNY", promTotalAmount.ConvertToDecimal1().ToString("#0.00"));                decimal BalancePayment = frTotalAmount - prTotalAmount + promTotalAmount;                _view.GroupIncome = _giView;                _view.GroupIncomeStr = string.Format(@"<span style='color:red;'>剩余尾款:{0} CNY(包含了收款退还费用数据)</span>", BalancePayment.ConvertToDecimal1().ToString("#0.00"));                #endregion                #region 团组支出                GroupExpenditureView _geView = new GroupExpenditureView();                #region 酒店预定费用                List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();                //ccp.RMBPrice As CNYPrice                //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice                string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,                                                     sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,                                                     hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,                                                     hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,                                                     sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,                                                     ccp.PayMoney,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,                                                     sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant                                                     From Grp_HotelReservations  hr                                                     Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId                                                     Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                     Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                     Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                     Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                     Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id                                                     Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id                                                     Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id                                                     Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.PayMoney<> 0 And hr.DiId = {0}                                                      Order By CheckInDate Asc", _dto.DiId);                groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();                List<int> hotelSubIds = groupHotelFeeViews.Select(it => it.HrId).ToList();                List<Grp_HotelReservationsContent> groupHotelContentFeeViews = new List<Grp_HotelReservationsContent>();                groupHotelContentFeeViews = await _sqlSugar.Queryable<Grp_HotelReservationsContent>().Where(it => hotelSubIds.Contains(it.HrId)).ToListAsync();                decimal HotelCNYTotalPrice = 0.00M;                var teamRateData = await _teamRateRep.PostGroupRateInfoByDiId(_dto.DiId);                foreach (var item in groupHotelFeeViews)                {                    var roomData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 1); //房费                     item.RoomPrice = roomData?.Price ?? 0.00M;                    item.RoomPriceCurrency = _setDatas.Find(it => it.Id == roomData?.Currency)?.Name;                    string feeMark1 = roomData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";                    string isFeeMark1 = roomData?.IsOppay == 1 ? "是" : "否";                    item.RoomInfoTips = @$"当时汇率:{roomData?.Rate.ToString("#0.0000")} <br/>                                           收款方:{roomData?.Payee}<br/>                                           费用标识:{feeMark1} <br/>                                           支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>                                           卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name}                                           是否由地接支付:{isFeeMark1} <br/>";                    var breakfastData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 2); //早餐                     item.BreakfastPrice = breakfastData?.Price ?? 0.00M;                    item.BreakfastCurrency = _setDatas.Find(it => it.Id == breakfastData?.Currency)?.Name;                    string feeMark2 = breakfastData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";                    string isFeeMark2 = breakfastData?.IsOppay == 1 ? "是" : "否";                    item.BreakfastInfoTips = @$"当时汇率:{breakfastData?.Rate.ToString("#0.0000")} <br/>                                                收款方:{breakfastData?.Payee}<br/>                                                费用标识:{feeMark2} <br/>                                                支付方式:{_setDatas.Find(it => it.Id == roomData?.PayDId)?.Name} <br/>                                                卡类型:{_setDatas.Find(it => it.Id == roomData?.CTDId)?.Name} <br/>                                                是否由地接支付:{isFeeMark2} <br/>";                    var landTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 3); //地税                     item.GovernmentRent = landTaxData?.Price ?? 0.00M;                    item.GovernmentRentCurrency = _setDatas.Find(it => it.Id == landTaxData?.Currency)?.Name;                    string feeMark3 = landTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";                    string isFeeMark3 = landTaxData?.IsOppay == 1 ? "是" : "否";                    item.GovernmentRentTips = @$"当时汇率:{landTaxData?.Rate.ToString("#0.0000")} <br/>                                                 收款方:{landTaxData?.Payee}<br/>                                                 费用标识:{feeMark3} <br/>                                                 支付方式:{_setDatas.Find(it => it.Id == landTaxData?.PayDId)?.Name} <br/>                                                 卡类型:{_setDatas.Find(it => it.Id == landTaxData?.CTDId)?.Name} <br/>                                                 是否由地接支付:{isFeeMark3} <br/>";                    var cityTaxData = groupHotelContentFeeViews.Find(it => it.HrId == item.HrId && it.PriceType == 4); //城市税                     item.CityTax = cityTaxData?.Price ?? 0.00M;                    item.CityTaxCurrency = _setDatas.Find(it => it.Id == cityTaxData?.Currency)?.Name;                    string feeMark4 = cityTaxData?.OrbitalPrivateTransfer == 0 ? "公转" : "私转";                    string isFeeMark4 = landTaxData?.IsOppay == 1 ? "是" : "否";                    item.CityTaxTips = @$"当时汇率:{cityTaxData?.Rate.ToString("#0.0000")} <br/>                                          收款方:{cityTaxData?.Payee}<br/>                                          费用标识:{feeMark4} <br/>                                          支付方式:{_setDatas.Find(it => it.Id == cityTaxData?.PayDId)?.Name} <br/>                                          卡类型:{_setDatas.Find(it => it.Id == cityTaxData?.CTDId)?.Name} <br/>                                          是否由地接支付:{isFeeMark4} <br/>";                    HotelCNYTotalPrice += item.CNYPrice;                    item.PayMoney = item.PayMoney.ConvertToDecimal1();                    item.CNYPrice = item.CNYPrice.ConvertToDecimal1();                }                _geView.GroupHotelFeeViews = groupHotelFeeViews;                _geView.GroupHotelFeeStr = string.Format(@"人民币总费用:{0} CNY", HotelCNYTotalPrice.ToString("#0.00"));                #endregion                #region 地接费用                List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();                string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.PriceName As Area,ctggrc.*,ctggrc.Price As PayMoney,                                                     sd2.name As PaymentCurrency,ccp.PayPercentage,                                                     (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,                                                     (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,                                                     ccp.DayRate,(ctggrc.Price * ccp.DayRate)  As CNYPrice,ccp.Payee,ccp.AuditGMDate,                                                     ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime                                                     From Grp_CarTouristGuideGroundReservations ctggr                                                     Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,                                                                     cggrc.PriceContent                                                             From Grp_CarTouristGuideGroundReservationsContent cggrc                                                             Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id                                                             Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id                                                             Where cggrc.ISdel = 0 And cggrc.Price != 0.00                                                              ) ctggrc On ctggr.Id = ctggrc.CTGGRId                                                      Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0  And ccp.CTable = 79 And ctggr.Id = ccp.CId                                                     Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id                                                     Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id                                                     Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                     Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ctggr.DiId = {0}                                                     Order By CreateTime", _dto.DiId);                groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();                string CTGGRFeeStr = "";                decimal CTGGRCNYTotalPrice = 0.00M;                //按1 地区,2 币种,3 汇率 分组计算                var groupCTGGRFeeDatas = groupCTGGRFeeViews.GroupBy(it => it.Area);                foreach (var ctggfr in groupCTGGRFeeDatas)                {                    var ctggfr_curr = ctggfr.GroupBy(it => it.PaymentCurrency);                    if (ctggfr_curr.Count() > 0)                    {                        foreach (var curr in ctggfr_curr)                        {                            var ctggfr_rate = curr.GroupBy(it => it.DayRate);                            if (ctggfr_rate.Count() > 0)                            {                                foreach (var rate in ctggfr_rate)                                {                                    CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{rate.Sum(it => it.AmountPaid).ToString("#0.00")}                                                         {rate.FirstOrDefault()?.PaymentCurrency}(人民币:                                                        {rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:                                                        {rate.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");                                    CTGGRCNYTotalPrice += rate.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));                                }                            }                            else                            {                                CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{curr.Sum(it => it.AmountPaid).ToString("#0.00")}                                                         {curr.FirstOrDefault()?.PaymentCurrency}(人民币:                                                        {curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:                                                        {curr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");                                CTGGRCNYTotalPrice += curr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));                            }                        }                    }                    else                    {                        CTGGRFeeStr += string.Format(@$"{ctggfr.Key} 总费用:{ctggfr.Sum(it => it.AmountPaid).ToString("#0.00")}                                                         {ctggfr.FirstOrDefault()?.PaymentCurrency}(人民币:                                                        {ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00"))).ToString("#0.00")} CNY 当时支付汇率:                                                        {ctggfr.FirstOrDefault()?.DayRate.ToString("#0.0000")})\r\n");                        CTGGRCNYTotalPrice += ctggfr.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));                    }                }                foreach (var item in groupCTGGRFeeViews)                {                    if (!string.IsNullOrEmpty(item.AuditGMDate))                    {                        item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");                    }                    //CTGGRFeeStr += string.Format(@"{0} 总费用:{1} {2}(人民币:{3} CNY 当时支付汇率:{4})\r\n",                     //    item.Area, item.AmountPaid.ConvertToDecimal1().ToString("#0.00"), item.PaymentCurrency, item.CNYPrice.ToString("#0.0000"), item.DayRate.ToString("#0.0000"));                    //CTGGRCNYTotalPrice += item.CNYPrice;                }                _geView.GroupCTGGRFeeViews = groupCTGGRFeeViews;                _geView.GroupCTGGRFeeStr = string.Format(@"{0}人民币总费用:{1} CNY", CTGGRFeeStr, CTGGRCNYTotalPrice.ToString("#0.00"));                #endregion                #region 机票预订费用                //(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice                //ccp.RMBPrice As CNYPrice                List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();                string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,                                                        atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,                                                        sd1.Name As PayMoneyCurrency,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,                                                        ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime,                                                        atr.CType                                                        From Grp_AirTicketReservations atr                                                        Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId                                                        Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                        Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                        Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                        Left Join Sys_SetData sd4 On atr.CType = sd4.Id                                                        Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                        Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And atr.DiId = {0} Order By CreateTime", _dto.DiId);                groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();                string str = "";                List<dynamic> airClientPris = new List<dynamic>();                decimal AirCNYTotalPrice = 0.00M;                decimal JJCCNYTotalPrice = 0.00M, JJCPeopleNum = 0.00M, JJCAveragePrice = 0.00M;                decimal GWCCNYTotalPrice = 0.00M, GWCPeopleNum = 0.00M, GWCAveragePrice = 0.00M;                //if (groupAirFeeViews.Count > 0)                //{                //    JJCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.CNYPrice);                //    JJCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("经济舱")).Sum(it => it.ClientNum);                //    JJCAveragePrice = (JJCCNYTotalPrice / JJCPeopleNum).ConvertToDecimal1();                //    GWCCNYTotalPrice = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.CNYPrice);                //    GWCPeopleNum = groupAirFeeViews.Where(it => it.AirTypeName.Equals("公务舱")).Sum(it => it.ClientNum);                //    GWCAveragePrice = (GWCCNYTotalPrice / GWCPeopleNum).ConvertToDecimal1();                //}                int Index = 0;                foreach (var item in groupAirFeeViews)                {                    if (item.AirId > 2924)                    {                        string itemClientName = "";                        if (!string.IsNullOrEmpty(item.ClientName))                        {                            System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");                            System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");                            if (m_EnName.Success || m_ZHName.Success)                            {                                itemClientName = item.ClientName;                                decimal unitCost = 0.00M;                                AirCNYTotalPrice += item.CNYPrice;                                continue;                            }                            string[] clientIds = new string[] { };                            if (item.ClientName.Contains(','))                            {                                clientIds = item.ClientName.Split(',');                            }                            else                            {                                clientIds = new string[] { item.ClientName };                            }                            if (clientIds.Length > 0)                            {                                int[] output = Array.ConvertAll<string, int>(clientIds, delegate (string s) { return int.Parse(s); });                                if (output.Contains(-1))                                {                                    itemClientName += $@"行程单";                                    output = output.Where(val => val != -1).ToArray();                                }                                var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();                                decimal unitCost = 0.00M;                                unitCost = (item.PayMoney / item.ClientNum).ConvertToDecimal1();                                int clienIndex = 1;                                foreach (var client in clients)                                {                                    airClientPris.Add(new                                    {                                        CnName = client.LastName + client.FirstName,                                        EnName = client.Pinyin,                                        Price = unitCost,                                        AirType = item.AirTypeName                                    });                                    string six = "";                                    if (client.Sex == 0) six = "Mr";                                    else if (client.Sex == 1) six = "Ms";                                    itemClientName += string.Format(@"{0}.{1} {2};", clienIndex, client.LastName + client.FirstName, six);                                    clienIndex++;                                }                            }                        }                        item.ClientName = itemClientName;                    }                    else                    {                        string clientPinYinName = "";                        decimal unitCost = 0.00M;                        int cNum = item.ClientNum == 0 ? 1 : item.ClientNum;                        unitCost = (item.PayMoney / cNum).ConvertToDecimal1();                        Regex r = new Regex("[0-9]");                        string name1 = item.ClientName;                        name1 = r.Replace(name1, "");                        string[] clientNames = name1.Split('.');                        for (int i = 0; i < item.ClientNum; i++)                        {                            string name = "";                            if (clientNames.Length > 0)                            {                                int index = i + 1;                                if (index < clientNames.Length)                                {                                    name = clientNames[index].Replace("MR", "").Replace("MS", "").Trim();                                    if (!string.IsNullOrEmpty(name))                                    {                                        airClientPris.Add(new                                        {                                            CnName = name,                                            EnName = name,                                            Price = unitCost,                                            AirType = item.AirTypeName                                        });                                    }                                    //if (name.Length > 0)                                    //{                                    //    string nameLastStr = name[name.Length - 1].ToString();                                    //    if (nameLastStr.IsNumeric())                                    //    {                                    //        name = name.Substring(0, name.Length - 1).Trim();                                    //    }                                    //}                                }                            }                            clientPinYinName += string.Format(@"{0}.{1}出票价为:{2} CNY;", Index + 1, name, unitCost.ToString("#0.00"));                        }                    }                    if (!string.IsNullOrEmpty(item.AuditGMDate))                    {                        item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");                    }                    AirCNYTotalPrice += item.CNYPrice;                }                _geView.GroupAirFeeViews = groupAirFeeViews;                if (airClientPris.Count > 0)                {                    var peoplePriStr = "";                    var airClientPris1 = airClientPris.GroupBy(item => item.CnName)                                                      .Select(group => group.First())                                                      .ToList();                    int airClientPrisIndex = 1;                    foreach (var item in airClientPris1)                    {                        decimal price = 0.00M;                        var prices = airClientPris.Where(it => it.CnName == item.CnName).ToList();                        foreach (var pri in prices)                        {                            price += pri.Price;                        }                        peoplePriStr += $@"{airClientPrisIndex}.{item.EnName}出票价为: {price.ToString("#0.00")} CNY;";                        airClientPrisIndex++;                    }                    if (!string.IsNullOrEmpty(peoplePriStr))                    {                        str = $@"其中:{peoplePriStr}";                    }                    //经济舱均价                    var airJJCPris = airClientPris.Where(it => it.AirType == "经济舱").ToList();                    if (airJJCPris.Count > 0)                    {                        decimal jjcTotalPrice = 0.00M;                        foreach (var item in airJJCPris)                        {                            jjcTotalPrice += item.Price;                        }                        decimal jjcPeopleNum = airJJCPris.GroupBy(item => item.CnName)                                                      .Select(group => group.First())                                                      .ToList().Count(); ;                        JJCAveragePrice = jjcTotalPrice / jjcPeopleNum;                    }                    //公务舱均价                    var airGWCPris = airClientPris.Where(it => it.AirType == "公务舱").ToList();                    if (airGWCPris.Count > 0)                    {                        decimal gwcTotalPrice = 0.00M;                        foreach (var item in airGWCPris)                        {                            gwcTotalPrice += item.Price;                        }                        decimal gwcPeopleNum = airGWCPris.GroupBy(item => item.CnName)                                                      .Select(group => group.First())                                                      .ToList().Count();                        GWCAveragePrice = gwcTotalPrice / gwcPeopleNum;                    }                }                _geView.GroupAirFeeStr = $@"人民币总费用:{AirCNYTotalPrice.ToString("#0.00")} CNY\r\n{str}\r\n经济舱均价为:{JJCAveragePrice.ToString("#0.00")}CNY/人;公务舱均价为:{GWCAveragePrice.ToString("#0.00")}CNY/人;";                #endregion                #region 签证费用                List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();                string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,                                                         ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,                                                         sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice                                                         From Grp_VisaInfo vi                                                         Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId                                                         Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                         Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                         Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                         Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                         Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And vi.DIId = {0} Order By CreateTime", _dto.DiId);                groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();                decimal VisaCNYTotalPirce = 0.00M;                foreach (var item in groupVisaFeeViews)                {                    string itemClientName = "";                    string visaClients = item.VisaClient;                    if (!string.IsNullOrEmpty(visaClients))                    {                        string[] clientIds = new string[] { };                        if (visaClients.Contains(','))                        {                            clientIds = visaClients.Split(',');                        }                        else                        {                            clientIds = new string[] { visaClients };                        }                        if (clientIds.Length > 0)                        {                            List<int> clientIds1 = new List<int>() { };                            foreach (var clientIdStr in clientIds)                            {                                if (clientIdStr.IsNumeric())                                {                                    clientIds1.Add(int.Parse(clientIdStr));                                }                            }                            if (clientIds1.Count > 0)                            {                                var clients = _clientDatas.Where(it => clientIds1.Contains(it.Id)).ToList();                                foreach (var client in clients)                                {                                    itemClientName += $"{client.LastName + client.FirstName},";                                }                            }                            else                            {                                itemClientName = visaClients;                            }                        }                    }                    if (itemClientName.Length > 0)                    {                        itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);                    }                    item.VisaClient = itemClientName;                    VisaCNYTotalPirce += item.CNYPrice;                    if (!string.IsNullOrEmpty(item.AuditGMDate))                    {                        item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");                    }                }                _geView.GroupVisaFeeViews = groupVisaFeeViews;                _geView.GroupVisaFeeStr = string.Format(@"人民币总费用:{0} CNY", VisaCNYTotalPirce.ConvertToDecimal1().ToString("#.00"));                #endregion                #region 邀请/公务活动  CTable = 81                List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();                string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,                                                                 ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,                                                                 sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,                                                                 sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,(((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice2,ccp.Payee,ccp.AuditGMDate,                                                                 ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime                                                                 From  Grp_InvitationOfficialActivities ioa                                                                 Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId                                                                 Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                                 Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                                 Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id                                                                 Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id                                                                 Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id                                                                 Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id                                                                 Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id                                                                 Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                                 Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And  ioa.Diid = {0} Order By CreateTime", _dto.DiId);                groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();                #region 邀请/公务活动 - 模拟数据                //if (groupInvitationalFeeViews.Count < 1)                //{                //    groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()                //    {                //        IOAId = 0,                //        IOADiId = 2334,                //        InviterArea = "模拟数据-邀请方地区",                //        Inviter = "模拟数据-邀请方",                //        InviteTime = "2023-10-10",                //        InviteCost = 100.00M,                //        InviteCurrency = "EUR",                //        SendCost = 100.00M,                //        SendCurrency = "EUR",                //        EventsCost = 10000.00M,                //        EventsCurrency = "EUR",                //        TranslateCost = 300.00M,                //        TranslateCurrency = "EUR",                //        PayMoney = 10500.00M,                //        PaymentCurrency = "EUR",                //        CNYPrice = 76765.50M,                //        Payee = "模拟数据-收款方",                //        AuditGMDate = "2023-12-05",                //        OrbitalPrivateTransfer = 1,                //        PayWay = "刷卡",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //    groupInvitationalFeeViews.Add(new GroupInvitationalFeeView()                //    {                //        IOAId = 0,                //        IOADiId = 2334,                //        InviterArea = "模拟数据-邀请方地区",                //        Inviter = "模拟数据-邀请方",                //        InviteTime = "2023-10-10",                //        InviteCost = 100.00M,                //        InviteCurrency = "EUR",                //        SendCost = 100.00M,                //        SendCurrency = "EUR",                //        EventsCost = 10000.00M,                //        EventsCurrency = "EUR",                //        TranslateCost = 300.00M,                //        TranslateCurrency = "EUR",                //        PayMoney = 10500.00M,                //        PaymentCurrency = "EUR",                //        CNYPrice = 76765.50M,                //        Payee = "模拟数据-收款方",                //        AuditGMDate = "2023-12-05",                //        OrbitalPrivateTransfer = 1,                //        PayWay = "刷卡",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //}                #endregion                decimal InvitationalCNYTotalPrice = 0.00M;                foreach (var item in groupInvitationalFeeViews)                {                    InvitationalCNYTotalPrice += item.CNYPrice2;                    if (!string.IsNullOrEmpty(item.AuditGMDate))                    {                        item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");                    }                    string currencyRateStr = "";                    List<string> currencys = new List<string>();                    if (!string.IsNullOrEmpty(item.InviteCurrency)) currencys.Add(item.InviteCurrency);                    if (!string.IsNullOrEmpty(item.SendCurrency)) currencys.Add(item.SendCurrency);                    if (!string.IsNullOrEmpty(item.EventsCurrency)) currencys.Add(item.EventsCurrency);                    if (!string.IsNullOrEmpty(item.TranslateCurrency)) currencys.Add(item.TranslateCurrency);                    if (!string.IsNullOrEmpty(item.PaymentCurrency)) currencys.Add(item.PaymentCurrency);                    currencyRateStr = await GeneralMethod.PostGroupRateByCTableAndCurrency(teamRateData, 81, currencys);                    item.CurrencyRateStr = currencyRateStr;                }                _geView.GroupInvitationalFeeViews = groupInvitationalFeeViews;                _geView.GroupInvitationalFeeStr = string.Format(@"人民币总费用:{0} CNY", InvitationalCNYTotalPrice.ToString("#.00"));                #endregion                #region 保险费用                List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();                string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,                                                              sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,                                                              sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime                                                              From Grp_Customers ic                                                              Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId                                                              Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                              Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                              Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                              Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ic.DiId = {0} Order By CreateTime", _dto.DiId);                groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();                decimal InsuranceCNYTotalPrice = 0.00M;                foreach (var item in groupInsuranceFeeViews)                {                    InsuranceCNYTotalPrice += item.CNYPrice;                    string itemClientName = "";                    string insClients = item.ClientName;                    if (!string.IsNullOrEmpty(insClients))                    {                        //System.Text.RegularExpressions.Match m_EnName = Regex.Match(item.ClientName, @"[A-Za-z]+");                        //System.Text.RegularExpressions.Match m_ZHName = Regex.Match(item.ClientName, @"[\u4e00-\u9fa5]");                        //if (m_EnName.Success || m_ZHName.Success)                        //{                        //    itemClientName = insClients;                        //    continue;                        //}                        string[] clientIds = new string[] { };                        if (insClients.Contains(','))                        {                            clientIds = insClients.Split(',');                        }                        else                        {                            clientIds = new string[] { insClients };                        }                        if (clientIds.Length > 0)                        {                            List<int> output = new List<int>();                            foreach (var clientId in clientIds)                            {                                if (clientId.IsNumeric())                                {                                    output.Add(int.Parse(clientId));                                }                            }                            if (output.Count > 0)                            {                                var clients = _clientDatas.Where(it => output.Contains(it.Id)).ToList();                                foreach (var client in clients)                                {                                    itemClientName += $"{client.LastName + client.FirstName},";                                }                                if (itemClientName.Length > 0)                                {                                    itemClientName = itemClientName.Substring(0, itemClientName.Length - 1);                                }                            }                            else                            {                                itemClientName = insClients;                            }                        }                    }                    item.ClientName = itemClientName;                    if (!string.IsNullOrEmpty(item.AuditGMDate))                    {                        item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");                    }                }                _geView.GroupInsuranceFeeViews = groupInsuranceFeeViews;                _geView.GroupInsuranceFeeStr = string.Format(@"人民币总费用:{0} CNY", InsuranceCNYTotalPrice.ToString("#0.00"));                #endregion                #region 其他款项费用  98                List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();                string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,                                                              (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,                                                                ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,                                                             sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime                                                             From Grp_DecreasePayments dp                                                             Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId                                                             Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                             Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                             Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                             Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And dp.Diid = {0}                                                              Order By CreateTime", _dto.DiId);                groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();                #region 保险费用 - 模拟数据                //if (groupDecreaseFeeViews.Count < 1)                //{                //    groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()                //    {                //        DPId = 0,                //        DPDiId = 2334,                //        PriceName = "模拟数据-费用名称",                //        PayMoney = 1000.00M,                //        PayMoneyCurrency = "CNY",                //        DayRate = 1.0000M,                //        CNYPrice = 1.0000M,                //        AuditGMDate = "2023-12-10 12:13:00",                //        Payee = "模拟数据-付款方",                //        OrbitalPrivateTransfer = 1,                //        PayWay = "现金",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //    groupDecreaseFeeViews.Add(new GroupDecreaseFeeView()                //    {                //        DPId = 0,                //        DPDiId = 2334,                //        PriceName = "模拟数据-费用名称",                //        PayMoney = 1000.00M,                //        PayMoneyCurrency = "CNY",                //        DayRate = 1.0000M,                //        CNYPrice = 1.0000M,                //        AuditGMDate = "2023-12-10 12:13:00",                //        Payee = "模拟数据-付款方",                //        OrbitalPrivateTransfer = 1,                //        PayWay = "现金",                //        IsPay = 1,                //        Applicant = "刘华举"                //    });                //}                #endregion                decimal DecreaseCNYTotalPrice = 0.00M;                foreach (var item in groupDecreaseFeeViews)                {                    item.CNYPrice = Convert.ToDecimal(item.CNYPrice.ToString("#0.00"));                    DecreaseCNYTotalPrice += item.CNYPrice;                    if (!string.IsNullOrEmpty(item.AuditGMDate))                    {                        item.AuditGMDate = Convert.ToDateTime(item.AuditGMDate).ToString("yyyy-MM-dd HH:mm:ss");                    }                }                _geView.GroupDecreaseFeeViews = groupDecreaseFeeViews;                _geView.GroupDecreaseFeeStr = string.Format(@"人民币总费用:{0} CNY", DecreaseCNYTotalPrice.ToString("#0.00"));                #endregion                _view.GroupExpenditure = _geView;                #endregion                /*                  * 团组报表计算方式                 * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()                 * 应收金额 = 应收表.Sum()                 * 已收金额 = 已收表.Sum()                 * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出                 * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出                 *                  */                decimal _totalExpenditure = 0.00M; //总支出                decimal _amountReceivable = 0.00M; //应收金额                decimal _amountReceived = 0.00M;   //已收金额                decimal _receivableProfit = 0.00M; //应收利润                decimal _receivedProfit = 0.00M;   //已收利润                _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +                                    InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;                _amountReceivable = frTotalAmount;                _amountReceived = prTotalAmount;                _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;                _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;                _view.FeeTotalStr = string.Format(@$"<span>                                                    <span>当前总支出:{_totalExpenditure.ToString("#0.00")} CNY</span>                                                     <span style='padding-left:10px;color: Green;'>应收金额:{_amountReceivable.ToString("#0.00")} CNY</span>                                                     <span style='padding-left:10px;color: Green;'>已收金额:{_amountReceived.ToString("#0.00")} CNY</span>                                                    <span style='padding-left:10px;color: Green;'>应收利润(应收-支出):{_receivableProfit.ToString("#0.00")} CNY</span>                                                    <span style='padding-left:10px;color: Green;'>已收利润(已收-支出):{_receivedProfit.ToString("#0.00")} CNY</span>                                                    </span>");                return Ok(JsonView(true, "查询成功!", _view));            }            else            {                return Ok(JsonView(false, "查询成功"));            }        }        #endregion        #region 报表/折线图统计        //企业利润-团组利润        //企业利润-会务利润        /// <summary>        ///  企业利润        ///  Details         ///  待添加权限验证        /// </summary>        /// <param name="_dto">团组列表请求dto</param>        /// <returns></returns>        [HttpPost("PostCorporateProfit")]        //[JsonConverter(typeof(DecimalConverter), 2)]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostCorporateProfit(PostCorporateProfitDto _dto)        {            #region  参数验证            if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));            if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id            if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));            if (_dto.StatisticsType > 2 && _dto.StatisticsType < 1) return Ok(JsonView(false, "请输入有效的StatisticsType参数,1 月份 2 季度"));            if (_dto.BusinessType > 3 && _dto.BusinessType < 1) return Ok(JsonView(false, "请输入有效的BusinessType参数,1 所有 2 团组 3 会务"));            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));            #endregion            string sqlWhere = string.Empty;            //起止时间            DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");            DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");            sqlWhere = string.Format(@$" Where Isdel = 0 ");            //业务类型            List<int> groupTypeId = new List<int>();            if (_dto.BusinessType == 2) //团组            {                groupTypeId.AddRange(new List<int>() {                    38,   //  政府团                    39,   //  企业团                    40,   //  散客团                    1048  // 高校团                });            }            else if (_dto.BusinessType == 3) //会务            {                groupTypeId.AddRange(new List<int>() {                   102,   // 未知                   248,   // 非团组                   302,   // 成都-会务活动                   691,   // 四川-会务活动                   762,   // 四川-赛事项目收入                   1047   // 成都-赛事项目收入                });            }            if (groupTypeId.Count > 0)            {                sqlWhere += string.Format(@$" And TeamDid In ({string.Join(',', groupTypeId)})");            }            string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");            var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();            if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));            List<int> diIds = groupInfos.Select(it => it.Id).ToList();            List<CorporateProfit> corporateProfits = await CorporateProfit(diIds);            List<MonthInfo> months = new List<MonthInfo>();            if (_dto.StatisticsType == 1) //月份            {                months = GeneralMethod.GetMonthInfos(Convert.ToInt32(_dto.Year));            }            else if (_dto.StatisticsType == 1) //季度            {                months = GeneralMethod.GetQuarter(Convert.ToInt32(_dto.Year));            }            List<CorporateProfitMonthView> _view = new List<CorporateProfitMonthView>();            foreach (var item in months)            {                DateTime monthBeginDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.BeginDays} 00:00:00");                DateTime monthEndDt = Convert.ToDateTime($"{_dto.Year}-{item.Month}-{item.Days.EndDays} 23:59:59");                var corporateProfit = corporateProfits.Where(it => it.CreateDt >= monthBeginDt && it.CreateDt <= monthEndDt).ToList();                _view.Add(new CorporateProfitMonthView()                {                    Month = item.Month,                    Profit = corporateProfit.Sum(it => it.ReceivedProfit),                    GroupInfos = corporateProfit.OrderBy(it => it.CreateDt).ToList()                });            }            return Ok(JsonView(true, "操作成功!", _view));            #endregion        }        /// <summary>        /// 计算团组利润        /// </summary>        /// <param name="diIds"></param>        /// <returns></returns>        private async Task<List<CorporateProfit>> CorporateProfit(List<int> diIds)        {            List<CorporateProfit> corporateProfits = new List<CorporateProfit>();            if (diIds.Count < 1)            {                return corporateProfits;            }            #region 计算团组利润            /*             * 团组报表计算方式            * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()            * 应收金额 = 应收表.Sum()            * 已收金额 = 已收表.Sum()            * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出            * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出            *             */            string diIdStr = string.Join(",", diIds);            string sql = string.Format(@$"Select * From Grp_DelegationInfo Where Isdel = 0 And Id In ({diIdStr})");            var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToListAsync();            #region 费用类型 币种,转账,客户信息            List<Sys_SetData> _setDatas = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.IsDel == 0).ToListAsync();            var _clientDatas = await _sqlSugar.Queryable<Crm_DeleClient>().Where(it => it.IsDel == 0).ToListAsync();            #endregion            foreach (var _diId in diIds)            {                List<ExpenditureInfo> expenditureInfos = new List<ExpenditureInfo>();                #region 团组收入                /*                 * 应收报表                 */                decimal frTotalAmount = 0.00M;//应收总金额                string _frSql = string.Format(@"Select fr.Id,fr.Diid,fr.PriceName,fr.Price,fr.Count,fr.Unit,fr.Currency,										        sd.Name As CurrencyCode,sd.Remark As CurrencyName,fr.Rate,fr.ItemSumPrice,fr.CreateTime										        From Fin_ForeignReceivables fr										        Left Join Sys_SetData sd On fr.Currency = sd.Id										        Where fr.IsDel = 0 And fr.Diid = {0} Order By CreateTime", _diId);                List<Gsd_ForeignReceivablesView> _frViews = await _sqlSugar.SqlQueryable<Gsd_ForeignReceivablesView>(_frSql).ToListAsync();                frTotalAmount = _frViews.Sum(it => it.ItemSumPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "应收项", Amount = frTotalAmount });                /*                 * 已收报表                 */                decimal prTotalAmount = 0.00M;//已收总金额                string _prSql = string.Format(@"Select pr.Id,pr.Diid,pr.SectionTime As SectionTimeDt,pr.Price,pr.Currency,										        sd1.Name As CurrencyCode,sd1.Remark As CurrencyName,pr.Client,										        pr.ReceivablesType,sd2.Name As ReceivablesTypeName,pr.Remark,pr.CreateTime										        From Fin_ProceedsReceived  pr										        Left Join Sys_SetData sd1 On pr.Currency = sd1.Id										        Left Join Sys_SetData sd2 On pr.ReceivablesType = sd2.Id										        Where pr.IsDel = 0 and pr.Diid = {0} Order By CreateTime", _diId);                List<Gsd_ProceedsReceivedView> _prViews = await _sqlSugar.SqlQueryable<Gsd_ProceedsReceivedView>(_prSql).ToListAsync();                prTotalAmount = _prViews.Sum(it => it.Price);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "已收项", Amount = prTotalAmount });                /*                 * 超支费用                  */                decimal exTotalAmount = 0.00M;                string _ecSql = string.Format(@"Select gec.Id As GECId,gec.DiId As GECDiId,gec.PriceName,ccp.PayMoney,sd1.Name As PaymentCurrency,													   ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,													   sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,gec.CreateTime												From OA2023DB.dbo.Fin_GroupExtraCost gec												Left Join Grp_CreditCardPayment ccp On gec.Id = ccp.CId                                                Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                 Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                Left Join Sys_Users u On ccp.CreateUserId = u.Id												Where ccp.IsDel = 0 And ccp.CTable = 1015 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ccp.DiId = {0} Order By CreateTime", _diId);                List<Gsd_ExtraCostsView> _ExtraCostsViews = await _sqlSugar.SqlQueryable<Gsd_ExtraCostsView>(_ecSql).ToListAsync();                exTotalAmount = _ExtraCostsViews.Sum(it => it.CNYPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "超支费用", Amount = exTotalAmount });                /*                 * 收款退还                 */                decimal promTotalAmount = 0.00M;// 收款退还总金额                List<Gsd_PaymentRefundAndOtherMoneyView> _promView = new List<Gsd_PaymentRefundAndOtherMoneyView>();                //删除了  And prom.PriceType = 1                string _ropSql = string.Format(@"Select u.CnName As Appliction,prom.Id As PrId,prom.DiId As PrDiId,prom.Price As PrPrice,										         prom.PriceName AS PrPriceName,prom.CurrencyId As PrCurrencyId,										         prom.PayType As PrPayType,prom.PriceType As PrPriceType,ccp.*,prom.CreateTime As PrCreateTime										         From Fin_PaymentRefundAndOtherMoney prom										         Left Join Grp_CreditCardPayment ccp On prom.DiId = ccp.DIId And prom.Id = ccp.CId										         Left Join Sys_Users u On ccp.CreateUserId = u.Id										         Where prom.IsDel = 0  And prom.PayType = 1 And ccp.CTable = 285										         And ccp.IsAuditGM = 1 And ccp.IsPay = 1										         And prom.DiId = {0} Order By PrCreateTime", _diId);                var _promDatas = await _sqlSugar.SqlQueryable<Gsd_PaymentRefundAndOtherMoneyDataSource1View>(_ropSql).ToListAsync();                foreach (var ropItem in _promDatas)                {                    string thisCueencyCode = "Unknown";                    string thisCueencyName = "Unknown";                    var currency = _setDatas.Where(it => it.Id == ropItem.PaymentCurrency).FirstOrDefault();                    if (currency != null)                    {                        thisCueencyCode = currency.Name;                        thisCueencyName = currency.Remark;                    }                    string orbitalPrivateTransferStr = "Unknown";                    var orbitalPrivateTransfer = _setDatas.Where(it => it.Id == ropItem.OrbitalPrivateTransfer).FirstOrDefault();                    if (orbitalPrivateTransfer != null)                    {                        orbitalPrivateTransferStr = orbitalPrivateTransfer.Name;                    }                    string payStr = "Unknown";                    var pay = _setDatas.Where(it => it.Id == ropItem.PayDId).FirstOrDefault();                    if (pay != null)                    {                        payStr = pay.Name;                    }                    Gsd_PaymentRefundAndOtherMoneyView gsd_PaymentRefund = new Gsd_PaymentRefundAndOtherMoneyView()                    {                        Id = ropItem.Id,                        DiId = ropItem.DIId,                        PriceName = ropItem.PrPriceName,                        PayCurrencyCode = thisCueencyCode,                        PayCurrencyName = thisCueencyName,                        Price = ropItem.PrPrice,                        CNYPrice = ropItem.RMBPrice,                        ThisRate = ropItem.DayRate,                        Payee = ropItem.Payee,                        PayTime = ropItem.AuditGMDate,                        OrbitalPrivateTransfer = ropItem.OrbitalPrivateTransfer,                        PayType = payStr,                        IsPay = ropItem.IsPay,                        Applicant = ropItem.Appliction                    };                    _promView.Add(gsd_PaymentRefund);                }                promTotalAmount = _promView.Sum(it => it.CNYPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "收款退还", Amount = promTotalAmount });                #endregion                #region 团组支出                GroupExpenditureView _geView = new GroupExpenditureView();                #region 酒店预定费用                List<GroupHotelFeeView> groupHotelFeeViews = new List<GroupHotelFeeView>();                string hotelFeeSql = string.Format(@"Select hr.Id As HrId,hr.DiId As HrDiId,hr.City,hr.HotelName,hr.CheckInDate,hr.CheckOutDate,                                                     sd1.Name As PaymentCurrency,hr.SingleRoomPrice,hr.SingleRoomCount,hr.DoubleRoomPrice,                                                     hr.DoubleRoomCount,hr.SuiteRoomPrice,hr.SuiteRoomCount,hr.OtherRoomPrice,hr.OtherRoomCount,                                                     hr.BreakfastPrice,sd4.Name As BreakfastCurrency,hr.Isoppay,hr.GovernmentRent,                                                     sd5.Name As GovernmentRentCurrency,hr.CityTax,sd6.Name As CityTaxCurrency,                                                     ccp.PayMoney,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.OrbitalPrivateTransfer,                                                     sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant                                                     From Grp_HotelReservations  hr                                                     Left Join Grp_CreditCardPayment ccp On hr.Id = ccp.CId                                                     Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                     Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                     Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                     Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                     Left Join Sys_SetData sd4 On hr.BreakfastCurrency = sd4.Id                                                     Left Join Sys_SetData sd5 On hr.GovernmentRentCurrency = sd5.Id                                                     Left Join Sys_SetData sd6 On hr.CityTaxCurrency = sd6.Id                                                     Where hr.IsDel = 0 And ccp.IsDel = 0 And ccp.CTable = 76 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And hr.DiId = {0}                                                      Order By CheckInDate Asc", _diId);                groupHotelFeeViews = await _sqlSugar.SqlQueryable<GroupHotelFeeView>(hotelFeeSql).ToListAsync();                decimal HotelCNYTotalPrice = groupHotelFeeViews.Sum(it => it.CNYPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "酒店预定", Amount = HotelCNYTotalPrice });                #endregion                #region 地接费用                List<GroupCTGGRFeeView> groupCTGGRFeeViews = new List<GroupCTGGRFeeView>();                string CTGGRFeeSql = string.Format(@"Select ctggr.Id As CTGGRId,ctggr.DiId As CTGGRDiId,ctggr.Area,ctggrc.*,ctggrc.Price As PayMoney,                                                     sd2.name As PaymentCurrency,ccp.PayPercentage,                                                     (ctggrc.Price / (ccp.PayPercentage / 100)) As AmountPaid,                                                     (ctggrc.Price / (ccp.PayPercentage / 100) - ctggrc.Price) As BalancePayment,                                                     ccp.DayRate,(ctggrc.Price * ccp.DayRate)  As CNYPrice,ccp.Payee,ccp.AuditGMDate,                                                     ccp.OrbitalPrivateTransfer,sd1.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ctggr.CreateTime                                                     From Grp_CarTouristGuideGroundReservations ctggr                                                     Left Join ( Select cggrc.CTGGRId,sd1.Name As PriceName,cggrc.Price,sd2.Name As PriceCurrency,                                                                     cggrc.PriceContent                                                             From Grp_CarTouristGuideGroundReservationsContent cggrc                                                             Left Join Sys_SetData sd1 On cggrc.SId = sd1.Id                                                             Left Join Sys_SetData sd2 On cggrc.Currency = sd2.Id                                                             Where cggrc.ISdel = 0 And cggrc.Price != 0.00                                                              ) ctggrc On ctggr.Id = ctggrc.CTGGRId                                                      Left Join Grp_CreditCardPayment ccp On ccp.IsDel = 0  And ccp.CTable = 79 And ctggr.Id = ccp.CId                                                     Left Join Sys_SetData sd1 On ccp.PayDId = sd1.Id                                                     Left Join Sys_SetData sd2 On ccp.PaymentCurrency = sd2.Id                                                     Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                     Where ctggr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ctggr.DiId = {0}                                                     Order By CreateTime", _diId);                groupCTGGRFeeViews = await _sqlSugar.SqlQueryable<GroupCTGGRFeeView>(CTGGRFeeSql).ToListAsync();                decimal CTGGRCNYTotalPrice = groupCTGGRFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "地接", Amount = CTGGRCNYTotalPrice });                #endregion                #region 机票预订费用                List<GroupAirFeeView> groupAirFeeViews = new List<GroupAirFeeView>();                string groupAirFeeSql = string.Format(@"Select atr.Id As AirId,atr.DIId As AirDiId,atr.FlightsCode,atr.FlightsCity,sd4.Name As AirTypeName,                                                        atr.FlightsDate,atr.FlightsTime,atr.ClientName,atr.ClientNum,ccp.PayMoney,                                                        sd1.Name As PayMoneyCurrency,ccp.RMBPrice As CNYPrice,ccp.DayRate,ccp.Payee,ccp.AuditGMDate,                                                        ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,sd3.Name As CardType,ccp.IsPay,u.CnName As Applicant,atr.CreateTime                                                        From Grp_AirTicketReservations atr                                                        Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 85 And atr.Id = ccp.CId                                                        Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                        Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                        Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                        Left Join Sys_SetData sd4 On atr.CType = sd4.Id                                                        Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                        Where atr.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And atr.DiId = {0} Order By CreateTime", _diId);                groupAirFeeViews = await _sqlSugar.SqlQueryable<GroupAirFeeView>(groupAirFeeSql).ToListAsync();                decimal AirCNYTotalPrice = groupAirFeeViews.Sum(it => it.CNYPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "机票预订", Amount = AirCNYTotalPrice });                #endregion                #region 签证费用                List<GroupVisaFeeView> groupVisaFeeViews = new List<GroupVisaFeeView>();                string groupVisaFeeSql = string.Format(@"Select vi.Id As VisaId,vi.DIId As VisaDiId,vi.VisaClient,ccp.PayMoney,sd1.Name As PayMoneyCurrency,                                                         ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,                                                         sd3.Name As CardTypeName,ccp.IsPay,u.CnName As Applicant,vi.CreateTime                                                         From Grp_VisaInfo vi                                                         Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 80 And vi.Id = ccp.CId                                                         Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                         Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                         Left Join Sys_SetData sd3 On ccp.CTDId = sd3.Id                                                         Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                         Where vi.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And vi.DIId = {0} Order By CreateTime", _diId);                groupVisaFeeViews = await _sqlSugar.SqlQueryable<GroupVisaFeeView>(groupVisaFeeSql).ToListAsync();                decimal VisaCNYTotalPirce = groupVisaFeeViews.Sum(it => it.PayMoney);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "签证", Amount = VisaCNYTotalPirce });                #endregion                #region 邀请/公务活动  CTable = 81                List<GroupInvitationalFeeView> groupInvitationalFeeViews = new List<GroupInvitationalFeeView>();                string groupInvitationalFeeSql = string.Format(@"Select ioa.Id As IOAId,ioa.DiId As IOADiId,ioa.InviterArea,ioa.Inviter,ioa.InviteTime,                                                                 ioa.InviteCost,sd3.Name As InviteCurrency,ioa.SendCost,sd4.Name As SendCurrency,ioa.EventsCost,                                                                 sd5.Name As EventsCurrency,ioa.TranslateCost,sd6.Name As TranslateCurrency,ccp.PayMoney,                                                                 sd7.Name As PaymentCurrency,ccp.RMBPrice As CNYPrice,ccp.Payee,ccp.AuditGMDate,                                                                 ccp.OrbitalPrivateTransfer,sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ioa.CreateTime                                                                 From  Grp_InvitationOfficialActivities ioa                                                                 Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 81 And ioa.Id = ccp.CId                                                                 Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                                 Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                                 Left Join Sys_SetData sd3 On ioa.InviteCurrency = sd3.Id                                                                 Left Join Sys_SetData sd4 On ioa.SendCurrency = sd4.Id                                                                 Left Join Sys_SetData sd5 On ioa.EventsCurrency = sd5.Id                                                                 Left Join Sys_SetData sd6 On ioa.TranslateCurrency = sd6.Id                                                                 Left Join Sys_SetData sd7 On ccp.PaymentCurrency = sd7.Id                                                                 Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                                 Where ioa.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And  ioa.Diid = {0} Order By CreateTime", _diId);                groupInvitationalFeeViews = await _sqlSugar.SqlQueryable<GroupInvitationalFeeView>(groupInvitationalFeeSql).ToListAsync();                decimal InvitationalCNYTotalPrice = groupInvitationalFeeViews.Sum(it => it.CNYPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "邀请/公务活动", Amount = InvitationalCNYTotalPrice });                #endregion                #region 保险费用                List<GroupInsuranceFeeView> groupInsuranceFeeViews = new List<GroupInsuranceFeeView>();                string groupInsuranceFeeSql = string.Format(@"Select ic.Id As InsuranceId,ic.Diid As InsuranceDiId,ClientName,ccp.PayMoney,ccp.RMBPrice As CNYPrice,                                                              sd1.Name As PayMoneyCurrency,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,                                                              sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,ic.CreateTime                                                              From Grp_Customers ic                                                              Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 82 And ic.Id = ccp.CId                                                              Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                              Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                              Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                              Where ic.IsDel = 0 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And ic.DiId = {0} Order By CreateTime", _diId);                groupInsuranceFeeViews = await _sqlSugar.SqlQueryable<GroupInsuranceFeeView>(groupInsuranceFeeSql).ToListAsync();                decimal InsuranceCNYTotalPrice = groupInsuranceFeeViews.Sum(it => it.CNYPrice);                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "保险费用", Amount = InsuranceCNYTotalPrice });                #endregion                #region 其他款项费用  98                List<GroupDecreaseFeeView> groupDecreaseFeeViews = new List<GroupDecreaseFeeView>();                string groupDecreaseFeeSql = string.Format(@"Select dp.Id As DPId,dp.DiId As DPDiId,dp.PriceName,ccp.PayMoney,sd1.Name As PayMoneyCurrency,                                                              (((ccp.PayMoney * ccp.DayRate) / ccp.PayPercentage) * 100) As CNYPrice,                                                                ccp.DayRate,ccp.Payee,ccp.AuditGMDate,ccp.OrbitalPrivateTransfer,                                                             sd2.Name As PayWay,ccp.IsPay,u.CnName As Applicant,dp.CreateTime                                                             From Grp_DecreasePayments dp                                                             Left Join Grp_CreditCardPayment ccp On ccp.isdel = 0 And ccp.CTable = 98 And dp.Id = ccp.CId                                                             Left Join Sys_SetData sd1 On ccp.PaymentCurrency = sd1.Id                                                             Left Join Sys_SetData sd2 On ccp.PayDId = sd2.Id                                                             Left Join Sys_Users u On ccp.CreateUserId = u.Id                                                             Where dp.IsDel = 0 And ccp.Ctable = 98 And ccp.IsAuditGM = 1 And ccp.IsPay = 1 And dp.Diid = {0}                                                              Order By CreateTime", _diId);                groupDecreaseFeeViews = await _sqlSugar.SqlQueryable<GroupDecreaseFeeView>(groupDecreaseFeeSql).ToListAsync();                decimal DecreaseCNYTotalPrice = groupDecreaseFeeViews.Sum(it => Convert.ToDecimal(it.CNYPrice.ToString("#0.00")));                expenditureInfos.Add(new ExpenditureInfo() { ItemName = "其他款项", Amount = DecreaseCNYTotalPrice });                #endregion                #endregion                /*                  * 团组报表计算方式                 * 当前总支出 = 团组支出.Sum() + 超支费用.Sum()                 * 应收金额 = 应收表.Sum()                 * 已收金额 = 已收表.Sum()                 * 应收利润(应收-支出) = 应收金额 - 收款退还 - 当前总支出                 * 已收利润(已收-支出) = 已收金额 - 收款退还 - 当前总支出                 *                  */                decimal _totalExpenditure = 0.00M; //总支出                decimal _amountReceivable = 0.00M; //应收金额                decimal _amountReceived = 0.00M;   //已收金额                decimal _receivableProfit = 0.00M; //应收利润                decimal _receivedProfit = 0.00M;   //已收利润                _totalExpenditure = HotelCNYTotalPrice + CTGGRCNYTotalPrice + AirCNYTotalPrice + VisaCNYTotalPirce + InvitationalCNYTotalPrice +                                    InsuranceCNYTotalPrice + DecreaseCNYTotalPrice + exTotalAmount;                _amountReceivable = frTotalAmount;                _amountReceived = prTotalAmount;                _receivableProfit = _amountReceivable - promTotalAmount - _totalExpenditure;                _receivedProfit = _amountReceived - promTotalAmount - _totalExpenditure;                var groupInfo = groupInfos.Find(it => it.Id == _diId);                corporateProfits.Add(new CorporateProfit()                {                    DiId = _diId,                    TeamName = groupInfo?.TeamName ?? "Unkwnon",                    CreateDt = Convert.ToDateTime(groupInfo?.CreateTime),                    TotalExpenditure = _totalExpenditure,                    ExpenditureItem = expenditureInfos,                    AmountReceivable = _amountReceivable,                    AmountReceived = _amountReceived,                    ReceivableProfit = _receivableProfit,                    ReceivedProfit = _receivedProfit,                });            }            #endregion            return corporateProfits;        }        //未来预测-地区接团/出团量        //未来预测-地区酒店预订量        //未来预测-地区机票预订量        //未来预测-地区车辆预订量        /// <summary>        ///  (国家/城市)地区预订数量(团,酒店,机票,车辆)        ///  Details        ///  待添加权限验证         /// </summary>        /// <param name="_dto">团组列表请求dto</param>        /// <returns></returns>        [HttpPost("PostRegionalBookingsNumber")]        //[JsonConverter(typeof(DecimalConverter), 2)]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostRegionalBookingsNumber(PostRegionalBookingsNumberDto _dto)        {            #region  参数验证            if (_dto.UserId < 1) return Ok(JsonView(false, "员工Id为空"));            //if (_dto.PageId < 1) _dto.PageId = 38; //团组报表页面Id            if (_dto.Type > 1 && _dto.Type > 5) return Ok(JsonView(false, "请输入有效的Type参数,1 团 2 酒店 3 机票 4 车辆"));            if (_dto.Year < 1) return Ok(JsonView(false, "请输入有效的Year参数!"));            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));            #endregion            string sqlWhere = string.Empty;            //起止时间            DateTime beginDt = Convert.ToDateTime($"{_dto.Year}-01-01 00:00:00");            DateTime endDt = Convert.ToDateTime($"{_dto.Year}-12-31 23:59:59");            sqlWhere = string.Format(@$" Where Isdel = 0 ");            string sql = string.Format(@$"Select * From Grp_DelegationInfo {sqlWhere}");            var groupInfos = await _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).Where(it => it.CreateTime >= beginDt && it.CreateTime <= endDt).ToListAsync();            if (groupInfos.Count < 1) return Ok(JsonView(false, "暂无相关团组!"));            List<GroupTypeNumberInfo> datas = new List<GroupTypeNumberInfo>();            foreach (var item in groupInfos)            {                var data = await GroupBookingsNumber(_dto.Type, item);                if (data.TypeItem.Count > 0)                {                    datas.Add(data);                }            }            //类型处理            if (_dto.Type == 1)//接团            {                List<GroupBookingNumberView> views = new List<GroupBookingNumberView>();                dynamic groupData = null;                foreach (var item in datas)                {                    if (item.TypeItem.Count > 0)                    {                        foreach (var item1 in item.TypeItem)                        {                            if (item1.RegionItem.Count > 0)                            {                                GroupInfo groupInfo = new GroupInfo()                                {                                    DiId = item.DiId,                                    TeamName = item.GroupName,                                    CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",                                    ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",                                    Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",                                };                                views.Add(new GroupBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, GroupItem = new List<GroupInfo>() { groupInfo } });                            }                        }                    }                }                var viewsGroup = views.GroupBy(it => it.Name);                List<GroupBookingNumberView> _view = new List<GroupBookingNumberView>();                foreach (var item in viewsGroup)                {                    List<GroupInfo> infos = new List<GroupInfo>();                    foreach (var item1 in item)                    {                        infos.AddRange(item1.GroupItem);                    }                    infos = infos.OrderByDescending(it => it.CreateTime).ToList(); //                    _view.Add(new GroupBookingNumberView() { Name = item.Key, Number = item.Count(), GroupItem = infos });                }                _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();                return Ok(JsonView(true, "操作成功!", _view, _view.Count));            }            else if (_dto.Type == 2)            {                List<HotelBookingNumberView> views = new List<HotelBookingNumberView>();                foreach (var item in datas)                {                    if (item.TypeItem.Count > 0)                    {                        foreach (var item1 in item.TypeItem)                        {                            if (item1.RegionItem.Count > 0)                            {                                foreach (var item2 in item1.RegionItem)                                {                                    GroupInfo groupInfo = new GroupInfo()                                    {                                        DiId = item.DiId,                                        TeamName = item.GroupName,                                        CreateTime = groupInfos.Find(it => it.Id == item.DiId)?.CreateTime.ToString("yyyy-MM-dd HH:mm:ss") ?? "Unknown",                                        ClientUnit = groupInfos.Find(it => it.Id == item.DiId)?.ClientUnit ?? "Unknown",                                        Principal = groupInfos.Find(it => it.Id == item.DiId)?.ClientName ?? "Unknown",                                    };                                    List<HotelInfo> hotels = new List<HotelInfo>();                                    foreach (var item3 in item2.Data)                                    {                                        StatisticsHotelInfo statisticsHotelInfos = JsonConvert.DeserializeObject<StatisticsHotelInfo>(JsonConvert.SerializeObject(item3));                                        HotelInfo hotelInfo = new HotelInfo()                                        {                                            HotelName = statisticsHotelInfos.HotelName,                                            SingleRoomNum = statisticsHotelInfos.SingleRoomNum,                                            DoubleRoomNum = statisticsHotelInfos.DoubleRoomNum,                                            SuiteRoomNum = statisticsHotelInfos.SuiteRoomNum,                                            OtherRoomNum = statisticsHotelInfos.OtherRoomNum,                                            GroupInfo = groupInfo                                        };                                        hotels.Add(hotelInfo);                                    }                                    views.Add(new HotelBookingNumberView() { Name = item1.RegionItem[0].Name, Number = item1.RegionItem[0].Number, HotelItem = hotels });                                }                            }                        }                    }                }                var viewsGroup = views.GroupBy(it => it.Name);                List<HotelBookingNumberView> _view = new List<HotelBookingNumberView>();                foreach (var item in viewsGroup)                {                    List<HotelInfo> infos = new List<HotelInfo>();                    foreach (var item1 in item)                    {                        infos.AddRange(item1.HotelItem);                    }                    _view.Add(new HotelBookingNumberView() { Name = item.Key, Number = item.Count(), HotelItem = infos });                }                _view = _view.OrderByDescending(it => it.Number).Take(10).ToList();                return Ok(JsonView(true, "操作成功!", views, views.Count));            }            return Ok(JsonView(false, "操作失败!"));            #endregion        }        /// <summary>        /// 计算团组ALLType预订数量        /// </summary>        /// <param name="diIds"></param>        /// <returns></returns>        private async Task<GroupTypeNumberInfo> GroupBookingsNumber(int type, Grp_DelegationInfo info)        {            GroupTypeNumberInfo _view = new GroupTypeNumberInfo();            if (info == null)            {                return _view;            }            _view.DiId = info.Id;            _view.GroupName = info.TeamName;            List<TypeInfo> _types = new List<TypeInfo>();            #region 计算团组ALLType预订数量            if (type == 1)            {                //接团 客户集团所在地区                string group_region = string.Empty;                int group_number = 0;                if (!string.IsNullOrEmpty(info.ClientUnit))                {                    var _NewClientData = await _sqlSugar.Queryable<Crm_NewClientData>().Where(it => it.IsDel == 0 && it.Client.Equals(info.ClientUnit)).FirstAsync();                    if (_NewClientData != null)                    {                        var regionInfo = await _sqlSugar.Queryable<Sys_SetData>().Where(it => it.Id == _NewClientData.Lvlid).FirstAsync();                        if (regionInfo != null)                        {                            group_region = regionInfo.Name.Replace("级", "");                            group_number++;                        }                    }                }                if (group_number > 0)                {                    _types.Add(new TypeInfo() { Id = 1, RegionItem = new List<RegionInfo>() { new RegionInfo() { Name = group_region, Number = group_number } } });                }            }            else if (type == 2)            {                //酒店                var hotelInfos = await _sqlSugar.Queryable<Grp_HotelReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();                if (hotelInfos.Count > 0)                {                    List<RegionInfo> hotelRegions = new List<RegionInfo>();                    foreach (var item in hotelInfos)                    {                        var hotelNumberInfo = new StatisticsHotelInfo()                        {                            HotelName = item.HotelName,                            SingleRoomNum = item.SingleRoomCount,                            DoubleRoomNum = item.DoubleRoomCount,                            SuiteRoomNum = item.SuiteRoomCount,                            OtherRoomNum = item.OtherRoomCount,                        };                        int hotelRoomTotal = item.SingleRoomCount + item.DoubleRoomCount + item.SuiteRoomCount + item.OtherRoomCount;                        if (hotelRegions.Select(it => it.Name).ToList().Contains(item.City))                        {                            RegionInfo hotelRegion = hotelRegions.Find(it => it.Name.Equals(item.City));                            if (hotelRegion != null)                            {                                hotelRegions.Remove(hotelRegion);                                if (hotelRegion.Data.Count > 0)                                {                                    hotelRegion.Data.Add(hotelNumberInfo);                                }                                hotelRegion.Number += hotelRoomTotal;                                hotelRegions.Add(hotelRegion);                            }                        }                        else                        {                            hotelRegions.Add(new RegionInfo() { Name = item.City, Number = hotelRoomTotal, Data = new List<dynamic>() { hotelNumberInfo } });                        }                    }                    _types.Add(new TypeInfo() { Id = 2, RegionItem = hotelRegions });                }            }            else if (type == 3)            {                //机票                var airTicketInfos = await _sqlSugar.Queryable<Grp_AirTicketReservations>()                                                    .LeftJoin<Grp_CreditCardPayment>((atr, ccp) => atr.Id == ccp.CId && ccp.IsPay == 1)                                                    .LeftJoin<Sys_SetData>((atr, ccp, sd) => atr.CType == sd.Id)                                                    .Where((atr, ccp, sd) => atr.IsDel == 0 && atr.DIId == info.Id)                                                    .Select((atr, ccp, sd) => new { atr.ClientNum, atr.CType, ccp.Payee, AirType = sd.Name })                                                    .ToListAsync();                if (airTicketInfos.Count > 0)                {                    List<RegionInfo> airTicketRegions = new List<RegionInfo>();                    foreach (var item in airTicketInfos)                    {                        var ticketClass = new                        {                            TiketClass = item.AirType,                            Number = item.ClientNum                        };                        if (airTicketRegions.Select(it => it.Name).ToList().Contains(item.Payee))                        {                            RegionInfo airTicketRegion = airTicketRegions.Find(it => it.Name.Equals(item.Payee));                            if (airTicketRegion != null)                            {                                airTicketRegions.Remove(airTicketRegion);                                if (airTicketRegion.Data.Count > 0)                                {                                    airTicketRegion.Data.Add(ticketClass);                                }                                airTicketRegion.Number += item.ClientNum;                                airTicketRegions.Add(airTicketRegion);                            }                        }                        else                        {                            airTicketRegions.Add(new RegionInfo() { Name = item.Payee, Number = item.ClientNum, Data = new List<dynamic>() { ticketClass } });                        }                    }                    _types.Add(new TypeInfo() { Id = 3, RegionItem = airTicketRegions });                }            }            else if (type == 4)            {                //车辆                var opInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();                var opContentInfos = await _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(it => it.IsDel == 0 && it.DiId == info.Id).ToListAsync();                if (opInfos.Count > 0)                {                    List<RegionInfo> opRegions = new List<RegionInfo>();                    foreach (var item in opInfos)                    {                        int carNum = 0;                        var opContentInfo = opContentInfos.Where(it => it.CTGGRId == item.Id && it.SId == 91).ToList();                        if (opContentInfo.Count > 0)                        {                            foreach (var item1 in opContentInfo)                            {                                if (item1.Price > 0 && item1.Count > 0)                                {                                    carNum += item1.Count;                                }                            }                        }                        if (carNum > 0)                        {                            var opData = new                            {                                ServiceCompany = item.ServiceCompany,                                BusName = item.BusName,                                Numbuer = carNum                            };                            if (opRegions.Select(it => it.Name).ToList().Contains(item.Area))                            {                                RegionInfo opRegion = opRegions.Find(it => it.Name.Equals(item.Area));                                if (opRegion != null)                                {                                    opRegions.Remove(opRegion);                                    if (opRegion.Data.Count > 0)                                    {                                        opRegion.Data.Add(opData);                                    }                                    opRegion.Number += carNum;                                    opRegions.Add(opRegion);                                }                            }                            else                            {                                opRegions.Add(new RegionInfo() { Name = item.Area, Number = carNum, Data = new List<dynamic>() { opData } });                            }                        }                    }                    _types.Add(new TypeInfo() { Id = 4, RegionItem = opRegions });                }            }            #endregion            _view.TypeItem = _types;            return _view;        }        #endregion        #region 市场部销售额        /// <summary>        ///  市场部销售额        /// Init 基础数据(公司/人员/年份/季度/月份)        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesInitData")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesInitData(MarketingSalesInitDataDto _dto)        {            #region  参数验证            MarketingSalesInitDataDtoFoalidator validationRules = new MarketingSalesInitDataDtoFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            var companyData = _sqlSugar.Queryable<Sys_Company>().Where(it => it.IsDel == 0)                                       .Select(it => new { id = it.Id, name = it.CompanyName })                                       .ToList();            List<int> companyIds = companyData.Select(it => it.id).ToList();            List<int> pickGroupUserIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0)                                                  .Select(it => it.JietuanOperator )                                                  .ToList();            //var jobData = _sqlSugar.Queryable<Sys_JobPost>().Where(it => it.IsDel == 0 && companyIds.Contains(it.CompanyId) && (it.JobName.Contains("经理") || it.JobName.Contains("主管")))            //                       .Select(it => new { it.Id, it.CompanyId, it.DepId, it.JobName })            //                       .ToList();            //List<int> jobIds = jobData.Select(it => it.Id).ToList();            //(depIds.Contains(it.DepId) || jobIds.Contains(it.JobPostId)            //userId = 21             var userData = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0 && (pickGroupUserIds.Contains(it.Id) || it.Id == 21))                                   .Select(it => new { id = it.Id, companyId = it.CompanyId, name = it.CnName })                                   .ToList();            companyData.Insert(0, new { id = -1, name = "全部" });            userData.Insert(0, new { id = -1, companyId = -1, name = "全部" });            #region 年份            var dtData = new List<dynamic>();            int dt = DateTime.Now.Year;            for (int y = dt; y >= dt-4; y--)            {                //季度                var quarterDatas = new List<dynamic>();                quarterDatas.Add(new { name = "全部", beginDt = $"{y}-01-01", endDt = $"{y}-12-31" });                for (int q = 0; q < 4; q++)                {                    dynamic quarterData = null;                    if (q == 0)                    {                        var monthDatas = new List<dynamic>();                        monthDatas.Add(new { name = $"全部", beginDt = $"{y}-01-01", endDt = $" {y}-03-31" });                        for (int m = 1; m < 4; m++)                        {                            MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);                            monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });                        }                        //quarterData = new { name = "第一季度", beginDt = $"{y}-01-01", endDt = $" {y}-03-31", monthData = monthDatas };                        quarterData = new { name = "第一季度", monthData = monthDatas };                    }                    else if (q == 1)                    {                        var monthDatas = new List<dynamic>();                        monthDatas.Add(new { name = $"全部", beginDt = $"{y}-04-01", endDt = $"{y}-06-30" });                        for (int m = 4; m < 7; m++)                        {                            MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);                            monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });                        }                        //quarterData = new { name = "第二季度", beginDt = $"{y}-04-01", endDt = $"{y}-06-30", monthData = monthDatas };                        quarterData = new { name = "第二季度",  monthData = monthDatas };                    }                    else if (q == 2)                    {                        var monthDatas = new List<dynamic>();                        monthDatas.Add(new { name = $"全部", beginDt = $"{y}-07-01", endDt = $"{y}-09-30" });                        for (int m = 7; m < 10; m++)                        {                            MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);                            monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });                        }                        //quarterData = new { name = "第三季度", beginDt = $"{y}-07-01", endDt = $"{y}-09-30", monthData = monthDatas };                        quarterData = new { name = "第三季度", monthData = monthDatas };                    }                    else if (q == 3)                    {                        var monthDatas = new List<dynamic>();                        monthDatas.Add(new { name = $"全部", beginDt = $"{y}-10-01", endDt = $"{y}-12-31" });                        for (int m = 10; m < 13; m++)                        {                            MonthlyTimeSegment timeSegment = new MonthlyTimeSegment(y, m);                            monthDatas.Add(new { name = $"{ConvertToChinese(m)}", beginDt = timeSegment.Start.ToString("yyyy-MM-dd"), endDt = timeSegment.End.ToString("yyyy-MM-dd") });                        }                        //quarterData = new { name = "第四季度", beginDt = $"{y}-10-01", endDt = $"{y}-12-31", monthData = monthDatas };                         quarterData = new { name = "第四季度", monthData = monthDatas };                    }                    quarterDatas.Add(quarterData);                 }                dtData.Add(new                {                    year = y,                    //yearData = new { beginDt = $"{y}-01-01", endDt = $"{y}-12-31" },                    quarterData = quarterDatas,                });            }            #endregion            return Ok(JsonView(true, "操作成功!", new { companyData = companyData, userData = userData, dtData = dtData }));            #endregion        }        private static string ConvertToChinese(int month)        {            if (month < 1 || month > 12)                throw new ArgumentOutOfRangeException(nameof(month), "月份必须在1到12之间。");            var cultureInfo = new System.Globalization.CultureInfo("zh-CN");            var dateTimeFormat = cultureInfo.DateTimeFormat;            return dateTimeFormat.GetMonthName(month);        }        /// <summary>        ///  市场部销售额        ///  年度/季度/月度 报表(同比)        ///  (增加团组查询条件 IsSure=1)        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesStatistics")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesStatistics_Year(MarketingSalesStatisticsDto _dto)        {            #region  参数验证            MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            string beginDt = $"{_dto.BeginDt} 00:00:00",endDt = $"{_dto.EndDt} 23:59:59";                        return Ok(JsonView(true, "操作成功!", await GroupSales(_dto.CompanyId, _dto.GroupPickupUserId, beginDt, endDt)));        }        private async Task<List<int>> GetUserIds(int companyId, int groupPickupUserId)        {            //全部人员Id            //查询所有公司的市场部            List<int> pickGroupIds = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).Select(it => it.JietuanOperator).Distinct().ToList();            List<int> userIds = new List<int>();            var userDatas = await _sqlSugar.Queryable<Sys_Users>()                                           .InnerJoin<Sys_Company>((u, c) => u.CompanyId == c.Id)                                           .Where((u, c) => u.IsDel == 0 && pickGroupIds.Contains( u.Id))                                           .Select((u, c) => new { u.Id, u.CompanyId, u.CnName })                                           .ToListAsync();            userIds = userDatas.Select(it => it.Id).ToList();            if (companyId > 0)            {                userIds = userDatas.Where(it => it.CompanyId == companyId).Select(it => it.Id).ToList();            }            if (groupPickupUserId > 0)            {                userIds = userDatas.Where(it => it.Id == groupPickupUserId).Select(it => it.Id).ToList();            }            return userIds;        }        /// <summary>        /// 计算团组销售额        /// </summary>        /// <param name="companyId"></param>        /// <param name="groupPickupUserId"></param>        /// <param name="beginDt"></param>        /// <param name="endDt"></param>        /// <returns></returns>        private async Task<SalesYOYView> GroupSales(int companyId, int groupPickupUserId,string beginDt, string endDt)        {            decimal thisSales = 0.00M, lastSales = 0.00M, yoy = 1.00M;            var _view = new SalesYOYView();            List<int> userIds = new List<int>();            userIds = await GetUserIds(companyId, groupPickupUserId);            string userSqlWhere = "";            if (userIds.Count > 0)            {                userSqlWhere = string.Format($" And Id IN ({string.Join(',', userIds)})");            }            else            {                _view = new SalesYOYView                {                    thisYearSales = "0.00",                    lastYearSales = "0.00",                };                return _view;            }            string lastBeginDt = Convert.ToDateTime(beginDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss"),                   lastEndDt = Convert.ToDateTime(endDt).AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss");            string salesSql = string.Format(@"SELECT	'ThisSales' As [Name],	CAST(SUM(Sales) AS decimal(12,2)) As SalesFROM	(	SELECT di.VisitDate,		(SELECT  CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables		WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid		) AS Sales	FROM		Grp_DelegationInfo di	WHERE di.IsDel = 0 AND di.IsSure = 1		AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0  {0})		AND di.VisitDate BETWEEN '{1}' AND '{2}'	) tempUnion ALLSELECT	'LastSales' As [Name],	CAST(SUM(Sales) AS decimal(12,2)) As SalesFROM	(	SELECT di.VisitDate,		(SELECT  CAST(SUM(ItemSumPrice * Rate) AS decimal(12,2)) FROM Fin_ForeignReceivables		WHERE IsDel = 0 AND AddingWay IN (0, 1, 2)AND di.Id = Diid		) AS Sales	FROM		Grp_DelegationInfo di	WHERE di.IsDel = 0 AND di.IsSure = 1		AND di.JietuanOperator IN (SELECT Id FROM Sys_Users WITH (NoLock) WHERE IsDel = 0 {3})		AND di.VisitDate BETWEEN '{4}' AND '{5}'	) temp", userSqlWhere, beginDt, endDt, userSqlWhere, lastBeginDt, lastEndDt);            var salesData = await _sqlSugar.SqlQueryable<SalesView>(salesSql).ToListAsync();             thisSales = salesData.Where(x => x.Name.Equals("ThisSales")).First()?.Sales ?? 0;             lastSales = salesData.Where(x => x.Name.Equals("LastSales")).First()?.Sales ?? 0;                if (lastSales != 0 && thisSales != 0) yoy = (thisSales - lastSales) / lastSales;            return new SalesYOYView() {                thisYearSales = thisSales.ToString("#0.00"),                lastYearSales = lastSales.ToString("#0.00"),                yoy = yoy.ToString("#0.00")            };        }        private class SalesView        {            public string Name { get; set; }            public decimal Sales { get; set; }        }        private class SalesYOYView        {            public string thisYearSales { get; set; }            public string lastYearSales { get; set; }            public string yoy { get; set; } = "1.00";        }        /// <summary>        ///  市场部销售额        ///  团组列表        ///  (增加团组查询条件 IsSure=1)        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesGroupList")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesGroupList(MarketingSalesGroupListDto _dto)        {            #region  参数验证            MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            string userSql = "";            List<int> userIds = new List<int>();            userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);            if (userIds.Count <= 0)            {                return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));            }            else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";            if (!string.IsNullOrEmpty(_dto.SearchCriteria))            {                userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");            }            string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";            string sql = string.Format(@$"SELECT  ROW_NUMBER() OVER (    ORDER BY      CollectionDays  ) AS RowNumber,  *FROM  (    SELECT      di.Id,      di.TeamName,      di.ClientUnit,      di.ClientName,      di.VisitDate,      di.VisitPNumber,      di.JietuanOperator,      di.VisitEndDate,      (        SELECT          CAST(            COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)          ) AS GroupSales        FROM          Fin_ForeignReceivables        WHERE          IsDel = 0          AND di.Id = Diid          AND AddingWay IN (0, 1, 2)      ) AS GroupSales,      u.CnName AS GroupPickupUser,      DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays    FROM      Grp_DelegationInfo di    WITH      (NoLock)      LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id    WHERE      di.Isdel = 0	  AND di.IsSure = 1 {userSql}       AND VisitDate Between '{beginDt}' And  '{endDt}'  ) Temp ");            RefAsync<int> total = 0;            var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);            return Ok(JsonView(true, "操作成功!", groupData, total));        }        /// <summary>        ///  市场部销售额        ///  客户类型、客户等级 统计        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesGroupStatistics")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesGroupStatistics(MarketingSalesGroupStatisticsDto _dto)        {            #region  参数验证            MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";            List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);            string userSql = "";            if (userIds.Count > 0)            {                userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",",userIds)})");            }            else            {                if (_dto.PortType == 2 || _dto.PortType == 3)                {                    return Ok(JsonView(true, "操作成功!", new List<object> { }));                }                else                {                    return Ok(JsonView(true, "操作成功!", new                    {                        customerTypeData = new List<object> { },                        clientGradeData = new List<object> { }                    }));                }            }            string sql = "";            if (_dto.StatisticsType == 1 )            {                sql = string.Format(@$"Select 	sd.[Name],	Count(*) As [Count]From Grp_DelegationInfo diLeft Join Sys_SetData sd On di.TeamDid = sd.IdWhere di.Isdel = 0 And IsSure = 1 {userSql} And VisitDate Between '{beginDt}' And  '{endDt}'Group By [Name]Order By Count Desc");            }            else if (_dto.StatisticsType == 2)            {                sql = string.Format(@$"Select 	sd.[Name],	Count(*) As [Count]From Grp_DelegationInfo diLeft Join Sys_SetData sd On di.TeamLevSId = sd.IdWhere di.Isdel = 0 And IsSure = 1 {userSql} And VisitDate Between '{beginDt}' And  '{endDt}'Group By [Name]Order By Count Desc");            }            else return Ok(JsonView(false, "StatisticsType不在可取范围!"));            if (_dto.PortType == 1)            {                string sql1 = string.Format(@$"Select 	sd.[Name],	Count(*) As [Count]From Grp_DelegationInfo diLeft Join Sys_SetData sd On di.TeamDid = sd.IdWhere di.Isdel = 0 And IsSure = 1 {userSql} And VisitDate Between '{beginDt}' And  '{endDt}'Group By [Name]Order By Count Desc");                var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();                string sql2 = string.Format(@$"Select 	sd.[Name],	Count(*) As [Count]From Grp_DelegationInfo diLeft Join Sys_SetData sd On di.TeamLevSId = sd.IdWhere di.Isdel = 0 And IsSure = 1 {userSql} And VisitDate Between '{beginDt}' And  '{endDt}'Group By [Name]Order By Count Desc");                var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();                return Ok(JsonView(true, "操作成功!", new {                    customerTypeData= customerTypeData,                    clientGradeData = clientGradeData                }));            }            else if (_dto.PortType == 2 || _dto.PortType == 3)            {                var data = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql).ToListAsync();                return Ok(JsonView(true, "操作成功!", data, data.Count));            }            else return Ok(JsonView(false, MsgTips.Port));        }        /// <summary>        ///  市场部销售额        ///  接单排名        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesOrderRanking")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesOrderRanking(MarketingSalesOrderRankingDto _dto)        {            #region  参数验证            MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";            List<int> userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);            string userSql = "";            if (userIds.Count > 0)            {                userSql = string.Format(@$" AND JietuanOperator IN ({string.Join(",", userIds)})");            }else return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));            string sql = string.Format(@$"Select 	ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,	u.CnName As UserName,	Count(*) As [Count]	From Grp_DelegationInfo di	Left Join Sys_Users u On di.JietuanOperator = u.Id	Where di.Isdel = 0     AND IsSure = 1 {userSql} 	And VisitDate Between '{beginDt}' And  '{endDt}'	Group By CnName");            RefAsync<int> total = 0;            var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);            return Ok(JsonView(true, "操作成功!", rankingData, total));        }        /// <summary>        ///  市场部销售额        ///  团组列表、客户类型、客户等级、接单排名        ///  (增加团组查询条件 IsSure=1)        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesGroupItem")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesGroupItem(MarketingSalesGroupListDto _dto)        {            #region  参数验证            MarketingSalesStatisticsDtoFoalidator validationRules = new MarketingSalesStatisticsDtoFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            string userSql = "";            List<int> userIds = new List<int>();            userIds = await GetUserIds(_dto.CompanyId, _dto.GroupPickupUserId);            if (userIds.Count <= 0)            {                return Ok(JsonView(true, "操作成功!", new List<object> { }, 0));            }            else userSql = @$" And di.JietuanOperator In ({string.Join(",", userIds)})";            if (!string.IsNullOrEmpty(_dto.SearchCriteria))            {                userSql += string.Format(@$" AND di.TeamName Like '%{_dto.SearchCriteria}%'");            }            string beginDt = $"{_dto.BeginDt} 00:00:00", endDt = $"{_dto.EndDt} 23:59:59";            #region 团组List            string sql = string.Format(@$"SELECT  ROW_NUMBER() OVER (    ORDER BY      CollectionDays  ) AS RowNumber,  *FROM  (    SELECT      di.Id,      di.TeamName,      di.ClientUnit,      di.ClientName,      di.VisitDate,      di.VisitPNumber,      di.JietuanOperator,      di.VisitEndDate,      (        SELECT          CAST(            COALESCE(SUM(ItemSumPrice * Rate), 0) AS DECIMAL(12, 2)          ) AS GroupSales        FROM          Fin_ForeignReceivables        WHERE          IsDel = 0          AND di.Id = Diid          AND AddingWay IN (0, 1, 2)      ) AS GroupSales,      u.CnName AS GroupPickupUser,      DATEADD(DAY, 7, di.VisitEndDate) AS CollectionDays    FROM      Grp_DelegationInfo di    WITH      (NoLock)      LEFT JOIN Sys_Users u ON di.JietuanOperator = u.Id    WHERE      di.Isdel = 0	  AND di.IsSure = 1 {userSql}       AND VisitDate Between '{beginDt}' And  '{endDt}'  ) Temp ");            RefAsync<int> total = 0;            var groupData = await _sqlSugar.SqlQueryable<MarketingSalesGroupList>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);            #endregion            #region 客户类型、客户等级 统计            string sql1 = string.Format(@$"Select 	sd.[Name],	Count(*) As [Count]From Grp_DelegationInfo diLeft Join Sys_SetData sd On di.TeamDid = sd.IdWhere di.Isdel = 0 And IsSure = 1 {userSql} And VisitDate Between '{beginDt}' And  '{endDt}'Group By [Name]Order By Count Desc");            var customerTypeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql1).ToListAsync();            string sql2 = string.Format(@$"Select 	sd.[Name],	Count(*) As [Count]From Grp_DelegationInfo diLeft Join Sys_SetData sd On di.TeamLevSId = sd.IdWhere di.Isdel = 0 And IsSure = 1 {userSql} And VisitDate Between '{beginDt}' And  '{endDt}'Group By [Name]Order By Count Desc");            var clientGradeData = await _sqlSugar.SqlQueryable<MarketingSalesGroupStatisticsView>(sql2).ToListAsync();            #endregion            #region 接单排名            string sql4 = string.Format(@$"Select 	ROW_NUMBER() Over(Order By Count(*) Desc) As RowNumber,	u.CnName As UserName,	Count(*) As [Count]	From Grp_DelegationInfo di	Left Join Sys_Users u On di.JietuanOperator = u.Id	Where di.Isdel = 0     AND IsSure = 1 {userSql} 	And VisitDate Between '{beginDt}' And  '{endDt}'	Group By CnName");            var rankingData = await _sqlSugar.SqlQueryable<MarketingSalesOrderRankingView>(sql4).ToListAsync();            #endregion            var viewData = new {                groupData = groupData,                groupTotal = total,                customerTypeData = customerTypeData,                clientGradeData = clientGradeData,                rankingData = rankingData            };            return Ok(JsonView(true, "操作成功!", viewData, total));        }        /// <summary>        ///  市场部销售额        ///  客户拜访列表        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesVCList")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesVCList(MarketingSalesVCListDto _dto)        {            #region  参数验证            MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            return Ok(await _visitingClientsRep._List(_dto.PortType,_dto.PageIndex,_dto.PageSize,_dto.DiId,_dto.Search));        }        /// <summary>        ///  市场部销售额        ///  客户拜访 操作(添加 Or 编辑)        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesVCOperate")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesVCOperate(MarketingSalesVCOperrateDto _dto)        {            #region  参数验证            MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            return Ok(await _visitingClientsRep._AddOrEdit(_dto));        }        /// <summary>        ///  市场部销售额        ///  客户拜访 Del        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesVCDel")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesVCDel(MarketingSalesVCDelDto _dto)        {                        return Ok(await _visitingClientsRep._Del(_dto.Id,_dto.UserId));        }        /// <summary>        ///  市场部销售额        ///  客户拜访 操作 save        /// </summary>        /// <param name="_dto">市场部销售额请求dto</param>        /// <returns></returns>        [HttpPost("PostMarketingSalesVCSave")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> PostMarketingSalesVCSave(MarketingSalesVCSaveDto _dto)        {            #region  参数验证            MarketingSalesUserPageFuncDtoBaseFoalidator validationRules = new MarketingSalesUserPageFuncDtoBaseFoalidator();            var validResult = await validationRules.ValidateAsync(_dto);            if (!validResult.IsValid)            {                var errors = new StringBuilder();                foreach (var error in validResult.Errors) errors.AppendLine(error.ErrorMessage);                return Ok(JsonView(false, errors.ToString()));            }            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, MsgTips.CheckAuth));            #endregion            #endregion            return Ok(await _visitingClientsRep._Save(_dto));        }        #endregion        #region 日付报表        /// <summary>        /// 日付类型数据        /// </summary>        /// <param name="_dto"></param>        /// <returns></returns>        [HttpPost("DailypaymentTypeInit")]        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]        public async Task<IActionResult> DailypaymentTypeInit(DailypaymentTypeInitDto _dto)        {            #region  参数验证            if (_dto.PortType < 1 || _dto.PortType > 3) return Ok(JsonView(false, msg:MsgTips.Port));            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();            #region 页面操作权限验证            //pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(_dto.UserId, _dto.PageId);            //if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限"));            #endregion            #endregion            if (_dto.PortType == 1 || _dto.PortType == 2 || _dto.PortType == 3) // web/Android/IOS            {                var defaultParentIds = new List<int>() {                                                        48,//  人员费用                                                        49,//  办公费用                                                        50,//  销售费用                                                        51,//  其他费用                                                        55,//  大运会                                                         };                //更改appsettings 值                //AppSettingsHelper.UpdateIntList("Dailypayment",new List<int>() { 666 });                //var listConfig = _config.GetSection("Dailypayment").GetValue<List<int>>();                //listConfig.Add(666);                //读取appsettings json DailypaymentTypeData 配置                List<int> dailypaymentTypeData = AppSettingsHelper.Get<int>("Dailypayment");                var _view = await _sqlSugar.Queryable<DailypaymentParentTypeView>()                                           .Includes(x => x.SubData)                                           .Where(x => defaultParentIds.Contains(x.Id))                                           .ToListAsync();                _view.ForEach(x =>                {                    x.SubData.ForEach(y =>                    {                        int currId = dailypaymentTypeData.Find(z => z == y.Id);                        y.IsChecked = currId == 0 ? false : true;                    });                });                return Ok(JsonView(true, "查询成功!", _view));            }            else            {                return Ok(JsonView(false, "查询失败"));            }        }        #endregion    }}
 |