using Aspose.Words.Tables;
using AutoMapper;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.Util;
using OASystem.Domain;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Financial;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Infrastructure.Repositories.System;
using OASystem.Infrastructure.Tools;
using SqlSugar.Extensions;
using System.Collections.Generic;
using System.Reflection;

namespace OASystem.Infrastructure.Repositories.Groups
{
    public class CarTouristGuideGroundRepository:BaseRepository<Grp_CarTouristGuideGroundReservations, Grp_CarTouristGuideGroundReservationsContent>
    {
        private readonly IMapper _mapper;
        private readonly CheckBoxsRepository _checkRep;
        private readonly SetDataRepository _setDataRep;

        public CarTouristGuideGroundRepository(SqlSugarClient sqlSugar, IMapper mapper , CheckBoxsRepository checkRep, SetDataRepository setDataRep)
            : base(sqlSugar)
        {
            _mapper = mapper;
            _checkRep = checkRep;
            _setDataRep = setDataRep;
        }

        public async Task<Result> OpCarTouristGuideGround(OpCarTouristGuideGroundDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            BeginTran();
            try
            {
                int id = 0;
                Grp_CarTouristGuideGroundReservations grp_CarTouristGuide = _mapper.Map<Grp_CarTouristGuideGroundReservations>(dto);
                if (dto.Status == 1)//添加
                {
                    Grp_CarTouristGuideGroundReservations grp_CarTouristGuideGround = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().First(a => a.IsDel == 0 && a.Area == dto.Area && a.BusName == dto.BusName && a.ServiceGuide == dto.ServiceGuide && a.DiId==dto.DiId && a.BusTel==dto.BusTel && a.ServiceTel==dto.ServiceTel);
                    if (grp_CarTouristGuideGround != null)
                    {
                        return result = new Result() { Code = -1, Msg = "该笔费用已存在,请勿重复添加!" };
                    }
                    else
                    {
                        id = await AddAsyncReturnId(grp_CarTouristGuide);
                        if (id == 0)
                        {
                            RollbackTran();
                            result = new Result() { Code = -1, Msg = "添加失败,请稍后重试!" };
                        }
                        else
                        {
                            result = new Result() { Code = 0, Msg = "添加成功!" };
                        }

                    }

                }
                else if (dto.Status == 2)//修改
                {

                    bool res = await UpdateAsync(a => a.Id == dto.Id, a => new Grp_CarTouristGuideGroundReservations
                    {
                        Area = grp_CarTouristGuide.Area,
                        ServiceCompany = grp_CarTouristGuide.ServiceCompany,
                        ServiceGuide = grp_CarTouristGuide.ServiceGuide,
                        ServiceTel = grp_CarTouristGuide.ServiceTel,
                        BusName = grp_CarTouristGuide.BusName,
                        BusDescription = grp_CarTouristGuide.BusDescription,
                        BusTel = grp_CarTouristGuide.BusTel,
                        ServiceStartTime = grp_CarTouristGuide.ServiceStartTime,
                        ServiceEndTime = grp_CarTouristGuide.ServiceEndTime,
                        ServiceDescription = grp_CarTouristGuide.ServiceDescription,
                        QuotedPriceExplanation = grp_CarTouristGuide.QuotedPriceExplanation,
                        OrbitalPrivateTransfer = grp_CarTouristGuide.OrbitalPrivateTransfer,
                        Remark = grp_CarTouristGuide.Remark,
                    });
                    if (res)
                    {
                        id = dto.Id;
                        result = new Result() { Code = 0, Msg = "修改成功!" };
                    }
                    else
                    {
                        RollbackTran();
                        result = new Result() { Code = -1, Msg = "修改失败,请稍后重试!" };
                    }
                }
                if (id!=0)
                {
                    Res_LocalGuideData _LocalGuideDataCar = _sqlSugar.Queryable<Res_LocalGuideData>().First(a => a.UnitName == dto.BusName && a.ContactTel == dto.BusTel && a.IsDel == 0);
                    if (_LocalGuideDataCar == null)
                    {
                        Res_LocalGuideData res_LocalGuideCar = new Res_LocalGuideData();
                        res_LocalGuideCar.UnitName = dto.BusName;
                        res_LocalGuideCar.ContactTel = dto.BusTel;
                        res_LocalGuideCar.CreateUserId = dto.CreateUserId;
                        int cId = await _sqlSugar.Insertable(res_LocalGuideCar).ExecuteReturnIdentityAsync();
                    }
                    Res_LocalGuideData _LocalGuideDataService = _sqlSugar.Queryable<Res_LocalGuideData>().First(a => a.UnitName == dto.ServiceCompany && a.ContactTel == dto.ServiceTel && a.IsDel == 0);
                    if (_LocalGuideDataService == null)
                    {
                        Res_LocalGuideData res_LocalGuideService = new Res_LocalGuideData();
                        res_LocalGuideService.UnitName = dto.ServiceCompany;

                        res_LocalGuideService.ContactTel = dto.ServiceTel;
                        res_LocalGuideService.Contact = dto.ServiceTel;
                        res_LocalGuideService.CreateUserId = dto.CreateUserId;
                        int cId = await _sqlSugar.Insertable(res_LocalGuideService).ExecuteReturnIdentityAsync();
                    }
                }
                
                CommitTran();
            }
            catch (Exception ex)
            {
                result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }

        public Result CarTouristGuideGroundContent(CarTouristGuideGroundContentDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                DateTime start = new DateTime();
                DateTime end = new DateTime();
                Grp_CarTouristGuideGroundReservations grpCarOp = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservations>().First(x => x.Id == dto.Id);

                if (!DateTime.TryParse(grpCarOp?.ServiceStartTime, out start))
                {
                    result.Msg = "服务开始时间不存在!";
                    result.Code = -1;
                    return result;
                }

                if (!DateTime.TryParse(grpCarOp?.ServiceEndTime, out end))
                {
                    result.Msg = "服务结束时间不存在!";
                    result.Code = -1;
                    return result;
                }

                TimeSpan ts = end - start;  //计算时间差
                int day = ts.Days;

                List<Grp_GroupsTaskAssignment> grp_GroupsTaskAssignment = Query<Grp_GroupsTaskAssignment>(a => a.IsDel == 0 && a.UId == dto.UserId && a.CTId == 79).ToList();

                string DiId = "0";
                foreach (var item in grp_GroupsTaskAssignment)
                {
                    DiId += item.DIId + ",";
                }
                if (DiId != "0")
                {
                    DiId = DiId.Substring(0, DiId.Length - 1);
                }
                string sql = string.Format(@"select * from Grp_DelegationInfo where Id in({0}) and IsDel={1}", DiId, 0);

                //团组下拉框
                List<Grp_DelegationInfo> _Delegations = _sqlSugar.SqlQueryable<Grp_DelegationInfo>(sql).ToList();
                List<ShareGroupInfoIIView> grp_Delegations = _mapper.Map<List<ShareGroupInfoIIView>>(_Delegations);

                //支付方式
                List<Sys_SetData> Payment = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 14 && a.IsDel == 0).ToList();
                List<SetDataInfoView> _Payment = _mapper.Map<List<SetDataInfoView>>(Payment);

                //列表初始化
                List<Sys_SetData> TableInitialization = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.STid == 17 && a.IsDel == 0).ToList();
                List<SetDataInfoView> _TableInitialization = _mapper.Map<List<SetDataInfoView>>(TableInitialization);

                List<Sys_SetData> ssd = _sqlSugar.Queryable<Sys_SetData>().Where(x => x.STid == 78).ToList();
                List<SetDataInfoView> ssdv = _mapper.Map<List<Sys_SetData>,List<SetDataInfoView>>(ssd);

                List<Grp_CarTouristGuideGroundReservationsContent> grp_CarTouristsContent = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(a => a.IsDel == 0 && a.CTGGRId == dto.Id).ToList();
                List<CarTouristGuideGroundReservationsContentView> carTouristGuides = _mapper.Map<List<CarTouristGuideGroundReservationsContentView>>(grp_CarTouristsContent);

                foreach (var itemSt in TableInitialization)
                {
                    var findResult = carTouristGuides.Find(x => x.SId == itemSt.Id);
                    if (findResult == null)
                    {
                        carTouristGuides.Add(new CarTouristGuideGroundReservationsContentView
                        {
                             SId = itemSt.Id,
                             Count = 1,
                             SidName = itemSt.Name,
                        });
                    }
                }
                
                var groupResult = carTouristGuides.GroupBy(x => x.SId).ToDictionary(x => x.Key, x => x.ToList());
                foreach (var item in groupResult.Keys)
                {
                    #region 倒推初始化逻辑
                    //while (groupResult[item].Count <= day)
                    //{
                    //    groupResult[item] = groupResult[item].OrderByDescending(x => x.DatePrice).ToList();
                    //    if (groupResult[item][0]?.DatePrice is not null)
                    //    {
                    //        groupResult[item].Add(new CarTouristGuideGroundReservationsContentView
                    //        {
                    //            DatePrice = groupResult[item][0].DatePrice.ObjToDate().AddDays(1),
                    //            SId = item,
                    //            Count = 1,
                    //        });
                    //    }
                    //    else
                    //    {
                    //        groupResult[item][0].DatePrice = start;
                    //    }
                    //}
                    #endregion

                    var startForTime = start;

                    var dayResult = new List<CarTouristGuideGroundReservationsContentView>();

                    for (var i = 0; i <= day; i++)
                    {
                        dayResult.Add(new CarTouristGuideGroundReservationsContentView
                        {
                            Count = 1,
                            DatePrice = startForTime,
                            SId = item,
                        });
                        startForTime = startForTime.AddDays(1);
                    }

                    if (groupResult[item].Count != day)
                    {

                        for (var m = 0; m< groupResult[item].Count; m++)
                        {
                            for (var m1 = 0; m1 < dayResult.Count; m1++)
                            {
                                if (groupResult[item][m].DatePrice == dayResult[m1].DatePrice)
                                {
                                    dayResult[m1] = groupResult[item][m];
                                }
                            }
                        }
                    }
                    else
                    {
                        groupResult[item] = groupResult[item].OrderBy(x => x.DatePrice).ToList();

                        if (groupResult[item][0].DatePrice == dayResult[0].DatePrice && groupResult[item][day - 1].DatePrice == dayResult[day - 1].DatePrice)
                        {
                            dayResult = groupResult[item];
                        }
                        else
                        {
                            for (var m = 0; m < groupResult[item].Count; m++)
                            {
                                for (var m1 = 0; m1 < dayResult.Count; m1++)
                                {
                                    if (groupResult[item][m].DatePrice == dayResult[m1].DatePrice)
                                    {
                                        dayResult[m1] = groupResult[item][m];
                                    }
                                }
                            }
                        }
                    }

                    groupResult[item] = dayResult;
                }

                carTouristGuides = groupResult.Values.SelectMany(sublist => sublist).OrderBy(x => x.SId).ThenBy(x => x.DatePrice).ToList();
                foreach (var item in carTouristGuides.Where(x => string.IsNullOrWhiteSpace(x.SidName)).ToList())
                {
                    item.SidName = TableInitialization.Find(x => x.Id == item.SId)?.Name;
                }

                Grp_CreditCardPayment CreditCardPayment = _sqlSugar.Queryable<Grp_CreditCardPayment>().First(a => a.CId == dto.Id && a.IsDel == 0 && a.CTable == 79);
                CarTouristCreditCardPaymentView _CreditCardPayment = _mapper.Map<CarTouristCreditCardPaymentView>(CreditCardPayment);

                if (_CreditCardPayment != null)
                {
                    _CreditCardPayment.PayName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == _CreditCardPayment.PayDId).Name;
                    _CreditCardPayment.PaymentCurrencyName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == _CreditCardPayment.PaymentCurrency).Name;
                    if (_CreditCardPayment.OrbitalPrivateTransfer == 0) _CreditCardPayment.OrbitalPrivateTransferStr = "公转";
                    else _CreditCardPayment.OrbitalPrivateTransferStr = "私转";
                }

                Dictionary<string, string> soureDic = new Dictionary<string, string>()
                {
                    {"车费", "VF"},
                    {"导游费", "T/G S"},
                    {"客户午餐费用" , "L"},
                    {"导游景点费" , "T/G EF"},
                    {"导游小费" , "T/G T"},
                      // --
                     {"司机小费", "DRV T"},
                     {"司机餐补", "C/F M"},
                     {"车超时费", "C/F OF"},
                     {"导游餐补", "T/G M"},
                     {"导游房补", "T/G A"},
                     {"导游交通", "T/G TF"},
                     {"客户早餐费用", "B"},
                     {"客户晚餐费用", "D"},
                     {"景点门票费", "EF"},
                     {"饮料/零食/水果", "B/R/F"},
                     {"翻译费", "I/F"},
                };

                var checkedItem = new List<string>();
                var checkedItemId = new List<int>();

                if (string.IsNullOrWhiteSpace(grpCarOp.SelectCheck))
                {
                    //获取成本选中
                    var checkTopArr = _checkRep.GetCheckBoxsByDiid(grpCarOp.DiId);
                    if (true)
                    {
                        var FindTop = checkTopArr.Find(x => x.CbType == "Top");
                        if (FindTop != null)
                        {
                            var selectName = FindTop.CbValues.Split(',').ToList<string>();
                            foreach (var soureKey in soureDic.Keys)
                            {
                                var find = selectName.Find(x => x == soureDic[soureKey]);
                                if (find == null)
                                {
                                    var Lindex = carTouristGuides.FindIndex(x => x.SidName == soureKey);
                                    //carTouristGuides.RemoveRange(Lindex, day + 1);
                                }
                                else
                                {
                                    checkedItem.Add(soureKey);
                                    checkedItemId.Add(_TableInitialization.Find(x=>x.Name == soureKey)!.Id);
                                }
                            }
                        }
                        else
                        {
                            checkedItem = new List<string>() { "车费", "导游费", "客户午餐费用", "导游景点费", "导游小费", "接送机费", "其他费用", "司机工资", "司机小费", "司机餐补", "车超时费", "导游餐补", "导游房补", "导游交通", "客户早餐费用", "客户晚餐费用", "景点门票费", "饮料/零食/水果", "住补费用", "翻译费" };
                            checkedItemId.AddRange(_TableInitialization.Select(x => x.Id).ToList());
                        }
                    }
                }
                else
                {
                    checkedItem = grpCarOp.SelectCheck.Split(",").ToList<string>();
                    int number = 0;
                    foreach (var item in checkedItem)
                    {
                        if (!int.TryParse(item,out number))
                        {
                            checkedItemId.Add(_TableInitialization.Find(x => x.Name == item)!.Id);
                        }
                        else
                        {
                            checkedItemId.Add(number);
                        }
                    }
                }

                if(dto.PortType == 1)
                {
                    var data = new
                    {
                        Payment = _Payment,
                        Delegations = grp_Delegations,
                        carTouristGuides = carTouristGuides,
                        CreditCardPayment = _CreditCardPayment,
                        start,
                        end,
                        ssdv,
                        checkedItem
                    };

                    return result = new Result() { Code = 0, Msg = "查询成功", Data = data };

                } else if(dto.PortType == 2)
                {
                    var data = new
                    {
                        Payment = _Payment,
                        TableInitialization = _TableInitialization,
                        carTouristGuides = carTouristGuides,
                        CreditCardPayment = _CreditCardPayment,
                        ssdv,
                        checkedItemId
                    };
                    return result = new Result() { Code = 0, Msg = "查询成功", Data = data };
                }

                return result = new Result() { Code = -1, Msg = "请传入有效portType" };
}
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "未知错误" };
            }
        }

        /// <summary>
        /// web弃用
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public  Result OpCarTouristGuideGroundContentById(CarTouristGuideGroundIdDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {

               
                List<Grp_CarTouristGuideGroundReservationsContent> grp_CarTouristsContent = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(a=>a.IsDel==0 && a.CTGGRId==dto.Id).ToList();
                List<CarTouristGuideGroundReservationsContentView> carTouristGuides = _mapper.Map<List<CarTouristGuideGroundReservationsContentView>>(grp_CarTouristsContent);

                foreach (var item in carTouristGuides)
                {
                    item.SidName= _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == item.SId).Name;
                }
                Grp_CreditCardPayment CreditCardPayment = _sqlSugar.Queryable<Grp_CreditCardPayment>().First(a => a.CId == dto.Id && a.IsDel == 0 && a.CTable == 79);
                CarTouristCreditCardPaymentView _CreditCardPayment = _mapper.Map<CarTouristCreditCardPaymentView>(CreditCardPayment);
                if (_CreditCardPayment!=null)
                {
                    _CreditCardPayment.PayName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == _CreditCardPayment.PayDId).Name;
                    _CreditCardPayment.PaymentCurrencyName = _sqlSugar.Queryable<Sys_SetData>().First(a => a.Id == _CreditCardPayment.PaymentCurrency).Name;
                    if (_CreditCardPayment.OrbitalPrivateTransfer==0) _CreditCardPayment.OrbitalPrivateTransferStr = "公转";
                    else _CreditCardPayment.OrbitalPrivateTransferStr = "私转";
                }
                var data = new
                {
                    CarTouristsContent = carTouristGuides,
                    CreditCardPayment = _CreditCardPayment,
                };
                return result = new Result() { Code = 0, Msg = "查询成功", Data = data };

            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "未知错误(" + ex.Message+")" };
            }
        }

        /// <summary>
        /// 根据diid查询op费用列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> QueryCarTouristGuideGroundByDiId(CarTouristGuideGroundDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            if (dto.PortType == 0 || string.IsNullOrWhiteSpace(dto.PortType.ToString()))
            {
                return result = new Result() { Code = -1, Msg = "请传入PortType参数,请求端口分类 1 Web 2 Android 3 IOS" };
            }
            try
            {
                #region SQL条件拼接

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

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

                #endregion
                int startIndex = (dto.PageIndex - 1) * dto.PageSize + 1;
                int endIndex = startIndex + dto.PageSize - 1;
                if (dto.PortType == 1)
                {
                    string sql = string.Format(@"select t.*,s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage,c.PayMoney,c.PayDid from 
                                                Grp_CarTouristGuideGroundReservations t
                                                left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id  and c.isdel=0
                                                left Join Sys_SetData s on s.Id=c.PaymentCurrency {0}
                                                order by c.IsAuditGM,c.PayPercentage desc", sqlWhere);
                    List<Grp_CarTouristGuideGroundView> infoViews = _sqlSugar.SqlQueryable<Grp_CarTouristGuideGroundView>(sql).ToList();
                    foreach (var item in infoViews)
                    {
                        if (item.OrbitalPrivateTransfer == 0) item.OrbitalPrivateTransferStr = "公转";
                        else if (item.OrbitalPrivateTransfer == 1) item.OrbitalPrivateTransferStr = "私转";
                        
                        item.ServiceStartTime = Convert.ToDateTime(item.ServiceStartTime).ToString("yyyy-MM-dd");
                        item.ServiceEndTime = Convert.ToDateTime(item.ServiceEndTime).ToString("yyyy-MM-dd");
                        item.ServiceQuotedPrice = item.PayMoney;
                        item.PayThenMoney = Math.Round(item.PayPercentage/100 * item.ServiceQuotedPrice, 2);
                        item.RemainingBalance = Math.Round(item.ServiceQuotedPrice- item.PayPercentage / 100 * item.ServiceQuotedPrice);
                        if (item.IsAuditGM == 0) item.IsAuditGMStr = "未审核";
                        else if (item.IsAuditGM == 1) item.IsAuditGMStr = "已通过";
                        else if (item.IsAuditGM == 2) item.IsAuditGMStr = "未通过";
                        else if (item.IsAuditGM == 3) item.IsAuditGMStr = "自动审核";
                        Sys_SetData s = _sqlSugar.Queryable<Sys_SetData>().First(a=>a.IsDel==0 && a.Id==item.PayDid);
                        if (s!=null)
                        {
                            item.PayStrd = s.Name;
                        }else item.PayStrd ="未选择";
                    }
                    return result = new Result() { Code = 0, Msg = "查询成功!", Data = infoViews };
                }
                else if (dto.PortType == 2 || dto.PortType == 3)
                {
                    string sql = string.Format(@"Select * From (	
                                            Select row_number() over (order by c.IsAuditGM,c.PayPercentage desc) as RowNumber,t.*,s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage,c.PayDid,c.PayMoney
                                            from 
                                            Grp_CarTouristGuideGroundReservations t
                                            left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id  and c.isdel=0
                                            left Join Sys_SetData s on s.Id=c.PaymentCurrency {0}
                                            ) temp Where RowNumber Between {1} and {2}", sqlWhere, startIndex, endIndex);

                    List<Grp_CarTouristGuideGroundView> grp_CarTourists = _sqlSugar.SqlQueryable<Grp_CarTouristGuideGroundView>(sql).ToList();
                    foreach (var item in grp_CarTourists)
                    {
                        if (item.OrbitalPrivateTransfer == 0) item.OrbitalPrivateTransferStr = "公转";
                        else if (item.OrbitalPrivateTransfer == 1) item.OrbitalPrivateTransferStr = "私转";
                        item.ServiceStartTime = Convert.ToDateTime(item.ServiceStartTime).ToString("yyyy-MM-dd");
                        item.ServiceEndTime = Convert.ToDateTime(item.ServiceEndTime).ToString("yyyy-MM-dd");
                        if (item.IsAuditGM == 0) item.IsAuditGMStr = "未审核";
                        else if (item.IsAuditGM == 1) item.IsAuditGMStr = "已通过";
                        else if (item.IsAuditGM == 2) item.IsAuditGMStr = "未通过";
                        else if (item.IsAuditGM == 3) item.IsAuditGMStr = "自动审核";
                        item.ServiceQuotedPrice = item.PayMoney;
                        item.PayThenMoney = Math.Round(item.PayPercentage / 100 * item.ServiceQuotedPrice, 2);
                        item.RemainingBalance = Math.Round(item.ServiceQuotedPrice - item.PayPercentage / 100 * item.ServiceQuotedPrice);
                        Sys_SetData s = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == item.PayDid);
                        if (s != null)
                        {
                            item.PayStrd = s.Name;
                        }
                        else item.PayStrd = "未选择";
                    }
                    string CountSql = string.Format(@"Select COUNT(1) as Count From (	
                                                        select t.*,s.Name as CurrencyStr,c.IsAuditGM,c.PayPercentage from 
                                                        Grp_CarTouristGuideGroundReservations t
                                                        left Join Grp_CreditCardPayment c on CTable=79 and c.CId=t.Id  and c.isdel=0
                                                        left Join Sys_SetData s on s.Id=t.CId {0}
                                                        ) temp ", sqlWhere);
                    DataCount dataCount = _sqlSugar.SqlQueryable<DataCount>(CountSql).First();
                    if (dataCount != null)
                    {
                        int count = dataCount.Count;
                        float totalPage = (float)count / dto.PageSize;//总页数
                        if (totalPage == 0) totalPage = 1;
                        else totalPage = (int)Math.Ceiling((double)totalPage);


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

        /// <summary>
        /// OP费用录入填写详情
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<Result> OpCarTouristGuideGroundContent(OpCarTouristGuideGroundContentDto dto)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                BeginTran();
                List<Grp_CarTouristGuideGroundReservationsContent> carTouristList = dto.OPContentList.Select(item => new Grp_CarTouristGuideGroundReservationsContent
                {
                    Id = item.Id,
                    DiId = dto.DiId,
                    CTGGRId = dto.CTGGRId,
                    SId = item.SId,
                    Price = item.Price,
                    PriceContent = item.priceContent,
                    Currency = dto.Currency,
                    CreateUserId = dto.CreateUserId,
                    Units = item.Units,
                    DatePrice = item.DatePrice,
                    Count = item.Count,
                }).ToList();

                if (carTouristList.Count > 0)
                {
                    //#region load


                    ////车超时费
                    ////餐费和三公经费那个表做完匹配后也放进超支表里
                    //DataTable tb = new DataTable();
                    //tb.Columns.Add("日期", typeof(DateTime));
                    //tb.Columns.Add("费用", typeof(decimal));
                    //tb.Columns.Add("币种", typeof(string));
                    //var addsTourClientList = new List<Grp_TourClientList>();
                    //var carExtraList = carTouristList.Where(x => x.SId == 982).ToList();
                    //var mealPriceList = carTouristList.Where(x => x.SId == 93 || x.SId == 988 || x.SId == 989).GroupBy(x => x.DatePrice).ToList();
                    //mealPriceList.ForEach(x =>
                    //{
                    //    var row = tb.NewRow();
                    //    row["日期"] = x.Key;
                    //    row["费用"] = x.Sum(x => x.Price * x.Count);
                    //    row["币种"] = x.FirstOrDefault()?.Currency;
                    //    tb.Rows.Add(row);
                    //});

                    ////限制只能选择地区


                    ////三公费用
                    //var cityPrice = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(x =>
                    //    !string.IsNullOrEmpty(x.City) && x.City.Contains("")
                    //).First();

                    ////超支费用表(数据添加)  Fin_GroupExtraCost
                    //List<Fin_GroupExtraCost> groupExtraCostsArr = new List<Fin_GroupExtraCost>();

                    ////币种
                    //var currOpResult = await _setDataRep.PostCurrencyByDiid(carTouristList[0].DiId, 79, carTouristList[0].Currency);
                    //var currOp = currOpResult.Code == 0 ? (currOpResult.Data as CurrencyInfo) == null ? 1 : (currOpResult.Data as CurrencyInfo).Rate : 1;
                    //var cityCurrResult = await _setDataRep.PostCurrencyByDiid(carTouristList[0].DiId, 79, cityPrice.Currency);
                    //var cityCurr = cityCurrResult.Code == 0 ? (cityCurrResult.Data as CurrencyInfo) == null ? 1 : (cityCurrResult.Data as CurrencyInfo).Rate : 1;
                    //var di = _sqlSugar.Queryable<Grp_DelegationInfo>().First(x => x.Id == dto.DiId);

                    //if (di == null)
                    //{
                    //    result.Code = -1;
                    //    result.Msg = "无该团组信息!";
                    //    return result;
                    //}


                    //if (carExtraList.Count > 0)
                    //{
                    //    foreach (var item in carExtraList)
                    //    {
                    //        groupExtraCostsArr.Add(new Fin_GroupExtraCost
                    //        {
                    //            Price = item.Price * item.Count,
                    //            CreateTime = DateTime.Now,
                    //            CreateUserId = dto.CreateUserId,
                    //            Coefficient = 1,
                    //            DiId = dto.DiId,
                    //            PriceCurrency = item.Currency,
                    //            PriceName = di.TeamName + "车超时费(地接导入)",
                    //            PriceType = 1050,
                    //            PriceDt = item.DatePrice.ObjToDate(),
                    //        });
                    //    }
                    //}


                    //if (tb.Rows.Count > 0)
                    //{
                    //    foreach (DataRow item in tb.Rows)
                    //    {
                    //        decimal foodCost = 1;
                    //        if (!decimal.TryParse(cityPrice.FoodCost, out foodCost))
                    //        {
                    //            //三公费用 ( 城市餐费用有问题! )
                    //        }

                    //        var price = Convert.ToDecimal(item["费用"]);
                    //        if (item["币种"].ToString() != cityPrice.Currency.ToString()) //币种不相同
                    //        {
                    //            //全部转换为rmb;
                    //            item["费用"] = price * currOp;
                    //            cityPrice.FoodCost = (foodCost * cityCurr).ToString("F2");

                    //            item["币种"] = "836";
                    //            cityPrice.Currency = 836;
                    //        }

                    //        if (price > foodCost)
                    //        {
                    //            //每天费用大于三公费用
                    //            groupExtraCostsArr.Add(new Fin_GroupExtraCost
                    //            {
                    //                Price = price - foodCost,
                    //                CreateTime = DateTime.Now,
                    //                CreateUserId = dto.CreateUserId,
                    //                Coefficient = 1,
                    //                DiId = dto.DiId,
                    //                PriceCurrency = cityPrice.Currency,
                    //                PriceName = di.TeamName + "餐费(地接导入)",
                    //                PriceType = 1049,
                    //                PriceDt = Convert.ToDateTime(item["日期"]),
                    //            });

                    //        }
                    //    }
                    //}

                    //if (groupExtraCostsArr.Count > 0)
                    //{
                    //    _sqlSugar.Insertable<Fin_GroupExtraCost>(groupExtraCostsArr);
                    //}
                    //#endregion
                }


                foreach (var item in carTouristList)
                {
                   
                    Grp_CarTouristGuideGroundReservationsContent QueryData = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().First(a => a.SId == item.SId && a.Id == item.Id && a.DiId == item.DiId && a.IsDel==0);
                    if (QueryData==null)
                    {
                        int id = await _sqlSugar.Insertable(item).ExecuteReturnIdentityAsync();
                        if (id == 0)
                        { 
                            RollbackTran();
                            return result = new Result() { Code = -2, Msg = "添加失败" };
                        }
                    }
                    else
                    {
                        int CTable = await _sqlSugar.Updateable<Grp_CarTouristGuideGroundReservationsContent>().Where(a => a.Id == item.Id).SetColumns(a => new Grp_CarTouristGuideGroundReservationsContent
                        {
                            Price = item.Price,
                            PriceContent = item.PriceContent,
                            Currency = dto.Currency,
                            Remark = item.Remark,
                            DatePrice = item.DatePrice,
                            Count = item.Count,
                            Units = item.Units,
                        }).ExecuteCommandAsync();
                        if (CTable==0)
                        {
                            RollbackTran();
                            return result = new Result() { Code = -1, Msg = "修改失败,请稍后重试!" };
                        }
                    }
                }

                //修改C表数据
                //List<Grp_CarTouristGuideGroundReservationsContent> carTouristListEnd = _sqlSugar.Queryable<Grp_CarTouristGuideGroundReservationsContent>().Where(a=>a.DiId==dto.DiId && a.CTGGRId==dto.CTGGRId && a.IsDel==0).ToList();
                Grp_CreditCardPayment c = new Grp_CreditCardPayment();
                c.PaymentCurrency = dto.Currency;
                c.PayMoney = carTouristList.Sum(x => x.Price);
                c.PayPercentage = dto.PayPercentage;
                c.ConsumptionDate= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                c.CTable = 79;
                c.CId = dto.CTGGRId;
                c.IsAuditGM = 0;
                c.PayDId=dto.PayDId;
                c.DIId = dto.DiId;
                c.OrbitalPrivateTransfer = dto.OrbitalPrivateTransfer;
                c.Payee=dto.Payee;
                c.CreateUserId=dto.CreateUserId;
                if (c.PayDId == 72)
                {
                    c.IsPay = 1;
                }
                c.RMBPrice = c.PayMoney;
                c.DayRate = 1;
                Grp_TeamRate _TeamRate = _sqlSugar.Queryable<Grp_TeamRate>().First(a => a.DiId == dto.DiId && a.IsDel == 0 && a.CTable == 79);
                List<CurrencyInfo> currencyInfos = new List<CurrencyInfo>();
                if (_TeamRate != null)
                {
                    Sys_SetData _SetData = _sqlSugar.Queryable<Sys_SetData>().First(a => a.IsDel == 0 && a.Id == c.PaymentCurrency);
                    if (_SetData != null)
                    {
                        currencyInfos = CommonFun.GetCurrencyChinaToList(_TeamRate.Remark);
                        CurrencyInfo CurrencyRate = currencyInfos.FirstOrDefault(a => a.CurrencyCode == _SetData.Name);
                        if (CurrencyRate != null)
                        {
                            c.RMBPrice = c.PayMoney * Convert.ToDecimal(CurrencyRate.Rate);
                            c.DayRate = CurrencyRate.Rate;
                        }
                    }
                }
                Grp_CreditCardPayment grp_CreditCard = _sqlSugar.Queryable<Grp_CreditCardPayment>().First(a=>a.CId==dto.CTGGRId && a.IsDel==0 && a.CTable==79 && a.DIId==dto.DiId);
                if (grp_CreditCard!=null)//修改
                {
                    int CTable = await _sqlSugar.Updateable<Grp_CreditCardPayment>().Where(a => a.CId == dto.CTGGRId && a.CTable == 79 && a.DIId==dto.DiId).SetColumns(a => new Grp_CreditCardPayment
                    {
                        PaymentCurrency = c.PaymentCurrency,
                        PayMoney = c.PayMoney,
                        PayPercentage = c.PayPercentage,
                        CTable = c.CTable,
                        PayDId = c.PayDId,
                        OrbitalPrivateTransfer = c.OrbitalPrivateTransfer,
                        Payee = c.Payee,
                        IsPay = c.IsPay,
                        RMBPrice = c.RMBPrice,
                        DayRate = c.DayRate,

                    }).ExecuteCommandAsync();

                    if (CTable == 0)
                    {
                        RollbackTran();
                        return result = new Result() { Code = -2, Msg = "修改失败" };
                    }
                }
                else//添加
                {
                    int id = await _sqlSugar.Insertable(c).ExecuteReturnIdentityAsync();
                    if (id == 0)
                    {
                        RollbackTran();
                        return result = new Result() { Code = -2, Msg = "添加失败" };
                    }
                }
                int CarTouristGuideCTable = await _sqlSugar.Updateable<Grp_CarTouristGuideGroundReservations>().Where(a => a.Id == dto.CTGGRId && a.DiId == dto.DiId).SetColumns(a => new Grp_CarTouristGuideGroundReservations
                {
                    CId = dto.Currency,
                    ServiceQuotedPrice = c.PayMoney,
                    OrbitalPrivateTransfer = dto.OrbitalPrivateTransfer,
                    SelectCheck = string.Join(',', dto.SelectCheck)

                }).ExecuteCommandAsync();

                if (CarTouristGuideCTable == 0)
                {
                    RollbackTran();
                    return result = new Result() { Code = -2, Msg = "修改失败" };
                }
                result = new Result() { Code =0, Msg = "保存成功" };
                CommitTran();
            }
            catch (Exception ex)
            {
                RollbackTran();
                return result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }
        
    }
}