using Aspose.Cells;
using Aspose.Words;
using EyeSoft.Extensions;
using EyeSoft.IO;
using FluentValidation;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OASystem.API.OAMethodLib;
using OASystem.API.OAMethodLib.File;
using OASystem.API.OAMethodLib.QiYeWeChatAPI.AppNotice;
using OASystem.Domain.Dtos.Financial;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Customer;
using OASystem.Domain.Entities.Financial;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Financial;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Infrastructure.Repositories.Financial;
using OASystem.Infrastructure.Repositories.Groups;
using OfficeOpenXml;
using SqlSugar.Extensions;
using System.Collections;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.Globalization;
using System.IO.Compression;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509.Qualified;
using MathNet.Numerics;
using static OASystem.API.OAMethodLib.JWTHelper;
using Org.BouncyCastle.Asn1.Ocsp;
namespace OASystem.API.Controllers
{
    /// 
    /// 财务模块
    /// 
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FinancialController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly IConfiguration _config;
        private readonly SqlSugarClient _sqlSugar;
        private readonly HttpClient _httpClient;
        private readonly SetDataTypeRepository _setDataTypeRep;
        private readonly SetDataRepository _setDataRep;
        private readonly DailyFeePaymentRepository _daiRep;    //日付申请仓库
        private readonly TeamRateRepository _teamRateRep;      //团组汇率仓库
        private readonly ForeignReceivablesRepository _ForForeignReceivablesRep;  //对外收款账单仓库
        private readonly ProceedsReceivedRepository _proceedsReceivedRep;         //已收款项仓库
        private readonly PaymentRefundAndOtherMoneyRepository _paymentRefundAndOtherMoneyRep; //收款退还与其他款项 仓库
        private readonly DelegationInfoRepository _delegationInfoRep;             //团组信息 仓库
        private readonly ForeignReceivablesRepository _foreignReceivablesRepository;
        /// 
        /// 初始化
        /// 
        public FinancialController(IMapper mapper, IConfiguration configuration, DailyFeePaymentRepository daiRep, SqlSugarClient sqlSugar, SetDataTypeRepository setDataTypeRep,
            TeamRateRepository teamRateRep, ForeignReceivablesRepository ForForeignReceivablesRep, ProceedsReceivedRepository proceedsReceivedRep,
            PaymentRefundAndOtherMoneyRepository paymentRefundAndOtherMoneyRep, HttpClient httpClient, DelegationInfoRepository delegationInfoRep, SetDataRepository setDataRep,
            ForeignReceivablesRepository foreignReceivablesRepository)
        {
            _mapper = mapper;
            _config = configuration;
            _daiRep = daiRep;
            _sqlSugar = sqlSugar;
            _setDataTypeRep = setDataTypeRep;
            _teamRateRep = teamRateRep;
            _ForForeignReceivablesRep = ForForeignReceivablesRep;
            _proceedsReceivedRep = proceedsReceivedRep;
            _paymentRefundAndOtherMoneyRep = paymentRefundAndOtherMoneyRep;
            _httpClient = httpClient;
            _delegationInfoRep = delegationInfoRep;
            _setDataRep = setDataRep;
            _foreignReceivablesRepository = foreignReceivablesRepository;
        }
        #region 日付申请
        /// 
        /// 获取日付申请 基础数据源
        /// 
        ///  日付申请 分页 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPageSearchDailyPaymentPriceTypeData(PortDtoBase dto)
        {
            var currUserInfo = JwtHelper.SerializeJwt(HttpContext.Request.Headers.Authorization);
            if (currUserInfo == null) return Ok(JsonView(false, "请传入token!"));
            var result = await _daiRep.GetPagePriceTypeData(dto,currUserInfo.UserId);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            var data = result.Data;
            return Ok(JsonView(data));
        }
        /// 
        /// 获取日付申请 基础数据源 - 转账表识 
        /// 
        ///  日付申请 分页 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task GetSearchDailyPaymentPriceTypeAddData(PortDtoBase dto)
        {
            var result = await _daiRep.GetPriceTypeAddData(dto);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            var data = result.Data;
            return Ok(JsonView(data));
        }
        /// 
        /// 日付申请 Page Search
        /// 
        ///  日付申请 分页 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPageSearchDailyPaymentList(PageDailyFeePaymentDto dto)
        {
            var result = await _daiRep.GetPageSearchAll(dto);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            var data = result.Data;
            if (data == null)
            {
                return Ok(JsonView(false, result.Msg));
            }
            return Ok(JsonView(data));
        }
        /// 
        /// 日付申请 Single Search By Id
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostSearchDailyPaymentInfo(SearchDailyFeePaymentDto dto)
        {
            var result = await _daiRep.GetSearchById(dto);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            return Ok(JsonView(result.Data));
        }
        /// 
        /// 日付申请 添加
        /// 
        ///  日付申请 添加 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAddDailyPayment(AddDailyFeePaymentDto dto)
        {
            var result = await _daiRep.Add(dto);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            #region 应用推送
            try
            {
                int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
                int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
                await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
                //2024-10-21 新增LZ UID
                var userIds = new List() { 21 };
                string title = $"系统通知";
                var dailyInfo = await _sqlSugar.Queryable().Where(x => x.Id == dailyId).FirstAsync();
                string content = $"[新增-日付申请]一项费用:[费用说明:{dailyInfo.Instructions}]{dailyInfo.SumPrice.ToString("#0.00")} CNY;";
                await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
            }
            catch (Exception ex)
            {
            }
            #endregion
            return Ok(JsonView(true));
        }
        /// 
        /// 日付申请 Update
        /// 
        ///  日付申请 修改 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostEditDailyPayment(EditDailyFeePaymentDto dto)
        {
            var result = await _daiRep.Edit(dto);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            #region 应用推送
            try
            {
                int dailyId = result.Data.GetType().GetProperty("dailyId").GetValue(result.Data, null);
                int sign = result.Data.GetType().GetProperty("sign").GetValue(result.Data, null);
                await AppNoticeLibrary.DailyPayReminders_Create_ToCaiwuChat(dailyId, sign, QiyeWeChatEnum.CaiWuChat);
                //2024-10-21 新增LZ UID
                var userIds = new List() { 21 };
                string title = $"系统通知";
                var dailyInfo = await _sqlSugar.Queryable().Where(x => x.Id == dailyId).FirstAsync();
                string content = $"[更新-日付申请]一项费用:[费用说明:{dailyInfo.Instructions}]{dailyInfo.SumPrice.ToString("#0.00")} CNY;";
                await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
            }
            catch (Exception ex)
            {
            }
            #endregion
            return Ok(JsonView(true));
        }
        /// 
        /// 日付申请 Del
        /// 
        ///  日付申请 删除 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostDelDailyPayment(DelDailyFeePaymentDto dto)
        {
            _sqlSugar.BeginTran();
            var result = await _daiRep.Del(dto);
            //删除日付关联表
            var delCount = _sqlSugar.Updateable()
                .Where(x => x.IsDel == 0 && x.DayOverhead == dto.Id)
                .SetColumns(x => new Fin_RoyaltyForm
                {
                    DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    DeleteUserId = dto.UserId,
                    IsDel = 1
                }).ExecuteCommand();
            _sqlSugar.CommitTran();
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            return Ok(JsonView(true));
        }
        /// 
        /// 日付申请 财务审核
        /// 
        ///  dto 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostDelDailyPaymentAudit(DP_AuditStatusDto dto)
        {
            var result = await _daiRep.DailyPaymentAudit(dto);
            if (result == null || result.Code != 0)
            {
                return Ok(JsonView(false, result.Msg));
            }
            return Ok(JsonView(true));
        }
        /// 
        /// 日付申请 Single Excel Download
        /// 
        ///  dto 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostExcelDailyPaymentDownload(SearchDailyFeePaymentDto dto)
        {
            if (dto.PortType == 1 || dto.PortType == 2)
            {
                Fin_DailyFeePaymentInfolView feeData = new Fin_DailyFeePaymentInfolView();
                string feeSql = string.Format(@"Select * From Fin_DailyFeePayment 
                                                Where IsDel=0 And Id = {0} ", dto.Id);
                feeData = await _sqlSugar.SqlQueryable(feeSql).FirstAsync();
                if (feeData == null)
                {
                    return Ok(JsonView(false, "暂无数据!"));
                }
                string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent 
                                                        Where IsDel=0 And DFPId = {0} ", dto.Id);
                feeData.FeeContents = await _sqlSugar.SqlQueryable(feeContentSql).ToListAsync();
                if (feeData != null)
                {
                    string userName = string.Empty;
                    string userSql = string.Format("Select * From  Sys_Users Where Id={0} And Isdel = {1}", feeData.CreateUserId, 0);
                    Sys_Users user = await _sqlSugar.SqlQueryable(userSql).FirstAsync();
                    if (user != null) { userName = user.CnName; }
                    var setData = _setDataTypeRep.QueryDto().ToList();
                    //48人员费用  49办公费用 50 销售费用 51 其他费用 55 大运会
                    var priceSubTypeData = setData.Where(s => s.STid == 55).ToList();
                    Dictionary pairs = new Dictionary();
                    List datas = new List();
                    //if (priceSubTypeData.Where(s => s.Id == feeData.PriceTypeId).ToList().Count() > 0)//大运会专属模板
                    //{
                    //    //AsposeHelper.ExpertExcelToModel("日常费用付款申请模板-大运会数据.xls", "DailyPayment", "大运会所有日常费用付款申请.xls",
                    //    //    pairs, datas);
                    //}
                    //else  //日付常规模板
                    //{
                    pairs.Clear();
                    pairs.Add("Opertor", userName);
                    pairs.Add("DateTime", feeData.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"));
                    pairs.Add("FAuditStatus", feeData.FAuditDesc);
                    pairs.Add("MAuditStatus", feeData.MAuditDesc);
                    pairs.Add("SumPrice", feeData.SumPrice);
                    DataTable data = AsposeHelper.ListToDataTable("DailyFeePayment", feeData.FeeContents);
                    datas.Clear();
                    datas.Add(data);
                    string fileName = string.Format("{0}-日常费用付款申请.xlsx", feeData.Instructions);
                    string msg = AsposeHelper.ExpertExcelToModel("日常费用付款申请模板.xlsx", "DailyPayment", fileName, pairs, datas);
                    return Ok(JsonView(true, msg));
                    //}
                }
                else
                {
                    return Ok(JsonView(false, "暂无数据!"));
                }
            }
            return Ok(JsonView(true));
        }
        /// 
        /// 日付申请 
        /// 总经理未审核 日付信息
        /// 
        ///  dto 
        /// 
        [HttpGet]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task DailyPaymentGMUnAudited()
        {
            var dailyInfos = await _sqlSugar.Queryable()
                                             .LeftJoin((dfp, u) => dfp.CreateUserId == u.Id)
                                             .Where(dfp => dfp.IsDel == 0 &&
                                                           //dfp.FAudit == 1 &&
                                                           //dfp.IsPay == 0 && 
                                                           dfp.MAudit == 0
                                                   )
                                             .OrderBy(dfp => dfp.CreateTime, OrderByType.Desc)
                                             //.OrderBy(dfp => dfp.FAudit, OrderByType.Desc)
                                             .Select((dfp, u) => new
                                             {
                                                 id = dfp.Id,
                                                 amountName = dfp.Instructions,
                                                 amount = dfp.SumPrice,
                                                 fAuditStatus = dfp.FAudit == 1 ? "审核通过" :
                                                                dfp.FAudit == 2 ? "审核未通过" : "未审核",
                                                 fAuditDate = dfp.FAuditDate,
                                                 applicant = u.CnName,
                                                 applicantDate = dfp.CreateTime
                                             })
                                             //.ToListAsync();
                                             .CountAsync();
            //int count = dailyInfos.Count;
            return Ok(JsonView(true, "查询成功", dailyInfos));
        }
        #endregion
        #region 团组提成
        /// 
        /// 提成 Page Search
        /// 
        ///  提成 分页 dto
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPageSearchCommissionList(GroupCommissionDto dto)
        {
            var data = await GroupCommission.GetCommissionPageList(dto);
            return Ok(JsonView(data.Data));
        }
        #endregion
        #region 团组汇率
        /// 
        /// 团组汇率 Select数据源(团组列,汇率列)
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task GetGroupRateDataSources(TeamRateDto dto)
        {
            try
            {
                //迁移数据更新团组汇率
                //Result teamRateData1 = await _teamRateRep.GetGroupRateChangeData();
                //var data = await _teamRateRep.PostGroupTeamRateHot();
                Stopwatch stopwatch = Stopwatch.StartNew();
                GroupNameDto groupNameDto = new GroupNameDto() { PortType = dto.PortType };
                var groups = await _delegationInfoRep.GetGroupNameList(groupNameDto);
                List _currData = new List();
                string currData = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync("GroupTeamCurrencyData");//string 取
                if (!string.IsNullOrEmpty(currData))
                {
                    _currData = JsonConvert.DeserializeObject>(currData);
                }
                else
                {
                    _currData = await _teamRateRep.PostGroupTeamRateHot();
                    //过期时间 25 Hours
                    TimeSpan ts = DateTime.Now.AddHours(25).TimeOfDay;
                    await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync("GroupTeamCurrencyData", JsonConvert.SerializeObject(_currData), ts);
                }
                var _data = new { GroupData = groups.Data, TeamRateData = _currData };
                stopwatch.Stop();
                return Ok(JsonView(true, $"查询成功!耗时:{stopwatch.ElapsedMilliseconds / 1000}s", _data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        ///// 
        ///// 团组汇率 changge
        ///// 
        ///// 
        //[HttpPost]
        //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        //public async Task ChangeGroupRateInfo()
        //{
        //    try
        //    {
        //        Result teamRateData = await _teamRateRep.GetGroupRateChangeData();
        //        if (teamRateData.Code != 0)
        //        {
        //            return Ok(JsonView(false, teamRateData.Msg));
        //        }
        //        return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
        //    }
        //    catch (Exception ex)
        //    {
        //        return Ok(JsonView(false, ex.Message));
        //        throw;
        //    }
        //}
        /// 
        /// 团组汇率 Select汇率详情
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task GetGroupRateInfo(TeamRateInfoDto dto)
        {
            try
            {
                Result teamRateData = await _teamRateRep.GetGroupRateInfoByDiid(dto);
                if (teamRateData.Code != 0)
                {
                    return Ok(JsonView(false, teamRateData.Msg));
                }
                return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        /// 
        /// 团组汇率 添加 or 更新
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupRateUpdate(TeamRateUpdateDto dto)
        {
            try
            {
                Result teamRateData = await _teamRateRep.PostGroupRateUpdate(dto);
                if (teamRateData.Code != 0)
                {
                    return Ok(JsonView(false, teamRateData.Msg));
                }
                return Ok(JsonView(true, teamRateData.Msg, teamRateData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        #endregion
        #region 对外收款账单 关联已收款项
        /// 
        /// 对外收款账单 Select数据源(团组名,币种,汇款方式)
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task GetForeignReceivablesDataSources(ForeignReceivablesDataSourcesDto dto)
        {
            return Ok(await _ForForeignReceivablesRep.GetDataSource(dto));
        }
        /// 
        /// 对外收款账单 
        /// 账单详情
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task GetGroupReceivablesInfoByDiId(ForForeignReceivablesInfoDto dto)
        {
            try
            {
                Result ffrData = await _ForForeignReceivablesRep.GetGroupReceivablesInfoByDiId(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        /// 
        /// 对外收款账单 
        /// 账单 删除
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupReceivablesDel(DelForForeignReceivablesInfoDto dto)
        {
            try
            {
                Result ffrData = await _ForForeignReceivablesRep._Del(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        /// 
        /// 对外收款账单 
        /// 添加 And 更新
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesOperate(ForeignReceivablesAddAndUpdateDto dto)
        {
            try
            {
                Result ffrData = await _ForForeignReceivablesRep.PostReceivablesOperate(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        /// 
        /// 已收款项 
        /// 账单 删除
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAmountReceivedDel(ProceedsReceivedDelDto dto)
        {
            try
            {
                Result ffrData = await _proceedsReceivedRep._Del(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        /// 
        /// 已收款项 
        /// 添加 And 更新
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAmountReceivedOperate(ProceedsReceivedDto dto)
        {
            try
            {
                Result ffrData = await _proceedsReceivedRep.PostAmountReceivedOperate(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        /// 
        /// 财务 已收款项
        /// 分配已收款项至 应收项下
        /// 关联已收款项
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAllocateAmountReceived(AllocateAmountReceivedDto dto)
        {
            try
            {
                Result ffrData = await _proceedsReceivedRep.PostAllocateAmountReceived(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
                throw;
            }
        }
        ///// 
        ///// 财务 收款账单
        ///// 导出Word(北京,四川)
        ///// 
        ///// 
        ///// 
        //[HttpPost]
        //[ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        //public async Task PostAccountReceivableWordExport(AccountReceivableWordExportDto dto)
        //{
        //    try
        //    {
        //        //模板处理
        //        string typeName = string.Empty;
        //        if (dto.TemplateType == 1) //四川
        //        {
        //            typeName = "四川";
        //        }
        //        else if (dto.TemplateType == 2) //北京 
        //        {
        //            typeName = "北京";
        //        }
        //        else return Ok(JsonView(false,"请选择正确的模板类型!"));
        //        string wordTempName = string.Format("收款账单({0})模板.doc", typeName);
        //    }
        //    catch (Exception ex)
        //    {
        //        return Ok(JsonView(false, ex.Message));
        //    }
        //}
        #endregion
        #region 对外收款账单
        /// 
        /// 对外收款账单 
        /// 数据源
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupReceivablesDataSource(ForeignReceivablesDataSourcesDto dto)
        {
            return Ok(await _ForForeignReceivablesRep.PostDataSource(dto));
        }
        /// 
        /// 对外收款账单 
        /// 账单详情
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupReceivablesInfoByDiId(ForForeignReceivablesNewDto dto)
        {
            return Ok(await _ForForeignReceivablesRep.PostGroupReceivablesInfoByDiId(dto));
        }
        /// 
        /// 对外收款账单 
        /// 添加 And 更新
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesSave(ForeignReceivablesSaveDto dto)
        {
            return Ok(await _ForForeignReceivablesRep.PostReceivablesSave(dto));
        }
        /// 
        /// 对外收款账单 
        /// 审核
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesAudit(FeeAuditDto dto)
        {
            return Ok(await _ForForeignReceivablesRep.FeeAudit(dto));
        }
        /// 
        /// 已收账单 
        /// 删除
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesDel(ForeignReceivablesDelDto dto)
        {
            Result ffrData = await _ForForeignReceivablesRep.PostReceivablesDel(dto);
            if (ffrData.Code != 0)
            {
                return Ok(JsonView(false, ffrData.Msg));
            }
            return Ok(JsonView(true, ffrData.Msg, ffrData.Data));
        }
        /// 
        /// 已收账单 
        /// File Download
        /// Init 
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesFeilDownloadInit()
        {
            return Ok(JsonView(true, "操作成功!", new List {
                new { Id = 1, Name = "生成收款单(四川)" },
                new { Id = 2, Name = "生成收款单(北京)" },
                new { Id = 3, Name = "汇款账单" }
            }
            ));
        }
        private class EnterExitCostCurrency 
        {
            public string Name { get; set; }
            public string Code { get; set; }
            public decimal Rate { get; set; }
        }
        /// 
        /// 已收账单 
        /// File Downloasd
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesFeilDownload(ForeignReceivablesFeilDownloadDto dto)
        {
            try
            {
                if (dto.DiId < 1)
                {
                    return Ok(JsonView(false, "请传入有效DiId参数!"));
                }
                if (dto.FileType < 1 || dto.FileType > 3)
                {
                    return Ok(JsonView(false, "请传入有效FileType参数! 1 生成收款单(四川)  2 生成收款单(北京)  3 汇款账单"));
                }
                var _currencyDatas = _sqlSugar.Queryable().Where(x => x.IsDel == 0 && x.STid == 66).ToList();
                var _DelegationInfo = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.Id == dto.DiId).First();
                if (_DelegationInfo == null)
                {
                    return Ok(JsonView(false, "暂无团组信息!!"));
                }
                if (dto.FileType == 1 || dto.FileType == 2)
                {
                    var _ForeignReceivables = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.Diid == dto.DiId).ToList();
                    if (_ForeignReceivables.Count < 1)
                    {
                        return Ok(JsonView(false, "暂无收款信息!!"));
                    }
                    string tempName = "";
                    if (dto.FileType == 1) tempName = $"收款账单(四川)模板.docx";
                    else if (dto.FileType == 2) tempName = $"收款账单(北京)模板.docx";
                    string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/{tempName}";
                    //载入模板
                    Document doc = new Document(tempPath);
                    DocumentBuilder builder = new DocumentBuilder(doc);
                    #region 替换Word模板书签内容
                    //这里可以创建个DataTable循环添加书签的值,这里提示一下就不多做修改了
                    //付款方
                    if (doc.Range.Bookmarks["To"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["To"];
                        mark.Text = _ForeignReceivables[0].To == null ? "" : _ForeignReceivables[0].To.ToString();
                    }
                    //付款方电话
                    if (doc.Range.Bookmarks["ToTel"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["ToTel"];
                        mark.Text = _ForeignReceivables[0].ToTel == null ? "" : _ForeignReceivables[0].ToTel.ToString();
                    }
                    //导出时间
                    if (doc.Range.Bookmarks["Date"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["Date"];
                        mark.Text = DateTime.Now.ToString("yyyy-MM-dd");
                    }
                    //注
                    if (doc.Range.Bookmarks["Attention"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["Attention"];
                        mark.Text = _ForeignReceivables[0].Attention == null ? "" : _ForeignReceivables[0].Attention.ToString();
                    }
                    //团队名称
                    if (doc.Range.Bookmarks["Team"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["Team"];
                        mark.Text = _DelegationInfo.VisitCountry == null ? "" : _DelegationInfo.VisitCountry.Replace("|", "、").ToString();
                    }
                    //付款日期
                    if (doc.Range.Bookmarks["PayDate"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["PayDate"];
                        mark.Text = _ForeignReceivables[0].PayDate == null ? "" : Convert.ToDateTime(_ForeignReceivables[0].PayDate).ToString("yyyy年MM月dd日");
                    }
                    decimal sumPrice = 0;
                    //各项费用
                    if (doc.Range.Bookmarks["PayItemContent"] != null)
                    {
                        string items = "";
                        foreach (var fr in _ForeignReceivables)
                        {
                            var currInfo = _sqlSugar.Queryable().Where(it => it.Id == fr.Currency).First();
                            items += $"{fr.PriceName}   {currInfo?.Name} {fr.Price.ToString("#0.00")}  *  {fr.Count} {fr.Unit} * {fr.Rate}.................. RMB {fr.ItemSumPrice.ToString("#0.00")}\n";
                            sumPrice += fr.ItemSumPrice;
                        }
                        Bookmark mark = doc.Range.Bookmarks["PayItemContent"];
                        mark.Text = items;
                    }
                    //合计
                    if (doc.Range.Bookmarks["Total"] != null)
                    {
                        Bookmark mark = doc.Range.Bookmarks["Total"];
                        mark.Text = sumPrice.ToString("#0.00");
                    }
                    #endregion
                    //文件名
                    string strFileName = _DelegationInfo.TeamName + "-收款账单.docx";
                    //去水印
                    new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
                    doc.Save(AppSettingsHelper.Get("WordBasePath") + "ForeignReceivables/File/" + strFileName);
                    string url = AppSettingsHelper.Get("WordBaseUrl") + "Office/Word/ForeignReceivables/File/" + strFileName;
                    return Ok(JsonView(true, "成功", new { Url = url }));
                }
                else if (dto.FileType == 3) //汇款通知
                {
                    var _EnterExitCosts = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.DiId == dto.DiId).First();
                    var _DayAndCosts = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.DiId == dto.DiId && it.NationalTravelFeeId > 0).ToList();
                    if (_EnterExitCosts == null)
                    {
                        return Ok(JsonView(false, "该团组未填写出入境费用;"));
                    }
                    var _EnterExitCostCurrencys = new List();
                    if (!string.IsNullOrEmpty(_EnterExitCosts.CurrencyRemark))
                    { 
                        var currency1 = _EnterExitCosts.CurrencyRemark.Split("|");
                        foreach (var item in currency1)
                        {
                            var currency2 = item.Split(":");
                            var currency3 = currency2[0].Split("(");
                            var currencyName = currency3[0].ToString();
                            var currencyCode = currency3[1].Split(")")[0].ToString();
                            _EnterExitCostCurrencys.Add(new EnterExitCostCurrency
                            {
                                Name = currencyName,
                                Code = currencyCode,
                                Rate = Convert.ToDecimal(currency2[1] ?? "0")
                            });
                        }
                    }
                    var _cityFee = _sqlSugar.Queryable().Where(it => it.IsDel == 0).ToList();
                    foreach (var item in _DayAndCosts)
                    {
                        var cityInfo = _cityFee.Where(it => it.Id == item.NationalTravelFeeId).FirstOrDefault();
                        if (cityInfo != null)
                        {
                            if (cityInfo.City.Contains("全部城市") || cityInfo.City.Contains("其他城市") || cityInfo.City.Contains("所有城市"))
                            {
                                item.Place = cityInfo.Country;
                            }
                            else item.Place = cityInfo.City;
                        }
                    }
                    //数据源
                    List dac1 = _DayAndCosts.Where(it => it.Type == 1).ToList(); //住宿费
                    List dac2 = _DayAndCosts.Where(it => it.Type == 2).ToList(); //伙食费
                    List dac3 = _DayAndCosts.Where(it => it.Type == 3).ToList(); //公杂费
                    List dac4 = _DayAndCosts.Where(it => it.Type == 4).ToList(); //培训费
                    //币种Data
                    var currData = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.STid == 66).ToList();
                    var DeleClientList = _sqlSugar.Queryable()
                                                  .LeftJoin((tcl, dc) => tcl.ClientId == dc.Id && dc.IsDel == 0)
                                                  .LeftJoin((tcl, dc, cc) => dc.CrmCompanyId == cc.Id && dc.IsDel == 0)
                                                  .Where((tcl, dc, cc) => tcl.IsDel == 0 && tcl.DiId == dto.DiId)
                                                  .Select((tcl, dc, cc) => new
                                                  {
                                                      Name = dc.LastName + dc.FirstName,
                                                      Sex = dc.Sex,
                                                      Birthday = dc.BirthDay,
                                                      Company = cc.CompanyFullName.Replace("\n", ""),
                                                      Job = dc.Job,
                                                      AirType = tcl.ShippingSpaceTypeId
                                                  })
                                                  .ToList();
                    if (DeleClientList.Count < 1)
                    {
                        return Ok(JsonView(false, "暂无团组成员,请先填写团组成员!!!"));
                    }
                    var _ClientNames = DeleClientList.Select(x => x.Name).ToList();
                    var _GroupClient = DeleClientList.GroupBy(x => x.Company).ToList();
                    Dictionary bookmarkArr = null;
                    string tempPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/Temp/汇款通知.docx";
                    //载入模板
                    Document doc = new Document(tempPath);
                    DocumentBuilder builder = null;
                    List filesToZip = new List();
                    foreach (var ClientItem in _GroupClient) //遍历单位
                    {
                        doc = new Document(tempPath);
                        builder = new DocumentBuilder(doc);
                        Paragraph paragraph = new Paragraph(doc);
                        bookmarkArr = new Dictionary();
                        bookmarkArr.Add("titleClientUnit", ClientItem.Key); //title单位
                        bookmarkArr.Add("ClientUnit", ClientItem.Key); //单位
                        bookmarkArr.Add("VisitStartDate", _DelegationInfo.VisitStartDate.ToString("yyyy年MM月dd日"));//出发日期
                        bookmarkArr.Add("name", string.Join(",", ClientItem.Select(x => x.Name).ToArray()).TrimEnd(','));//全部人员信息
                        bookmarkArr.Add("VisitCountry", _DelegationInfo.VisitCountry.Replace("|", "、"));//出访国家
                        bookmarkArr.Add("dayTime", DateTime.Now.ToString("yyyy年MM月dd日"));//今天日期
                        var ClientItemList = ClientItem.ToList();
                        string UsersTop = string.Empty;//word中人员以及金额
                        decimal WordAllPrice = 0.00M;
                        //int[] infoColumn = new int[5] {dac1.Select(x=>x.Place.Length).ToList().Max(),2, dac1.Select(x => x.Cost.Length).Max() + dac1.Select(x => x.Currency.Length).Max(),
                        //    6, 3 + dac1.Where(x=>!string.IsNullOrWhiteSpace(x.Place)).Select(x=>(Convert.ToDecimal(x.SubTotal) / Convert.ToDecimal(x.Cost)).ToString().Length).Max() };
                        //遍历人员
                        for (int i = 0; i < ClientItemList.Count(); i++)
                        {
                            Dictionary TeableBookmarkArr = new Dictionary();
                            var client = ClientItemList[i]; //每个人员
                            var firstName = ClientItemList[i].Name;
                            /*
                             *  457	头等舱
                             *  458	公务舱
                             *  460	经济舱
                             */
                            decimal airPrice = 0.00M;
                            string airName = string.Empty;
                            if (client.AirType == 457)
                            {
                                airName = $"头等舱";
                                airPrice = _EnterExitCosts.AirTD;
                            }
                            else if (client.AirType == 458)
                            {
                                airName = $"公务舱";
                                airPrice = _EnterExitCosts.AirGW;
                            }
                            else if (client.AirType == 460)
                            {
                                airName = $"经济舱";
                                airPrice = _EnterExitCosts.AirJJ;
                            }
                            //计算费用总和
                            decimal AllPrice = airPrice + _EnterExitCosts.CityTranffic + dac1.Sum(x => x.SubTotal) + dac2.Sum(x => x.SubTotal) +
                                               dac3.Sum(x => x.SubTotal) + dac4.Sum(x => x.SubTotal) + _EnterExitCosts.Visa + _EnterExitCosts.Safe +
                                               +_EnterExitCosts.YiMiao + _EnterExitCosts.YiMiao + _EnterExitCosts.Ticket + _EnterExitCosts.Service;
                            WordAllPrice += AllPrice;
                            UsersTop += firstName + "出访费用为¥" + AllPrice.ToString("#0.00") + "元、";
                            TeableBookmarkArr.Add("jp", airPrice.ToString("#0.00") + " 元"); //机票金额
                            TeableBookmarkArr.Add("cs", _EnterExitCosts.CityTranffic.ToString("#0.00") + " 元"); //城市交通费用
                            TeableBookmarkArr.Add("zs", dac1.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //住宿费
                            string zsinfo = string.Empty;
                            string hsinfo = string.Empty;
                            string gzinfo = string.Empty;
                            List placeArr = new List();
                            Aspose.Words.Tables.Table FirstTable = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
                            Aspose.Words.Tables.Table ChildTable = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 0, true);
                            Aspose.Words.Tables.Table ChildTable1 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 1, true);
                            Aspose.Words.Tables.Table ChildTable2 = (Aspose.Words.Tables.Table)FirstTable.GetChild(NodeType.Table, 2, true);
                            int rowIndex = 0;
                            foreach (var item in dac1)
                            {
                                if (string.IsNullOrWhiteSpace(item.Place))
                                {
                                    continue;
                                }
                                if (placeArr.Contains(item.Place))
                                {
                                    continue;
                                }
                                else
                                {
                                    placeArr.Add(item.Place);
                                }
                                if (!string.IsNullOrWhiteSpace(item.Place))
                                {
                                    if (rowIndex > ChildTable.Rows.Count - 1)
                                    {
                                        var chitableRow = ChildTable.LastRow.Clone(true);
                                        ChildTable.AppendChild(chitableRow);
                                    }
                                    int days = dac1.FindAll(x => x.Place == item.Place).Count();
                                    SetCells(ChildTable, doc, rowIndex, 0, item.Place);
                                    SetCells(ChildTable, doc, rowIndex, 1, days + "晚");
                                    string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
                                    SetCells(ChildTable, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/晚");
                                    var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
                                    var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
                                    if (sys_currencyInfo != null)
                                    {
                                        var sys_currencyCode = sys_currencyInfo.Name;
                                        var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
                                        if (eec_currencyInfo != null)
                                        {
                                            currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
                                        }
                                    }
                                    SetCells(ChildTable, doc, rowIndex, 3, "汇率" + currencyRate);
                                    SetCells(ChildTable, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
                                    rowIndex++;
                                    zsinfo += item.Place + "  " + days + "晚 " + item.Cost.ToString("#0.00") + currencyCode + "/晚" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + "   CNY " + item.SubTotal * days + "\r\n";
                                }
                            }
                            placeArr.Clear();
                            rowIndex = 0;
                            foreach (var item in dac2)
                            {
                                if (string.IsNullOrWhiteSpace(item.Place))
                                {
                                    continue;
                                }
                                if (placeArr.Contains(item.Place))
                                {
                                    continue;
                                }
                                else
                                {
                                    placeArr.Add(item.Place);
                                }
                                if (!string.IsNullOrWhiteSpace(item.Place))
                                {
                                    if (rowIndex > ChildTable1.Rows.Count - 1)
                                    {
                                        var chitableRow = ChildTable1.LastRow.Clone(true);
                                        ChildTable1.AppendChild(chitableRow);
                                    }
                                    int days = dac2.FindAll(x => x.Place == item.Place).Count();
                                    SetCells(ChildTable1, doc, rowIndex, 0, item.Place);
                                    SetCells(ChildTable1, doc, rowIndex, 1, days + "天");
                                    string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
                                    SetCells(ChildTable1, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
                                    var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
                                    var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
                                    if (sys_currencyInfo != null)
                                    {
                                        var sys_currencyCode = sys_currencyInfo.Name;
                                        var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
                                        if (eec_currencyInfo != null)
                                        {
                                            currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
                                        }
                                    }
                                    SetCells(ChildTable1, doc, rowIndex, 3, "汇率" + currencyRate);
                                    SetCells(ChildTable1, doc, rowIndex, 4, "CNY " + item.SubTotal);
                                    rowIndex++;
                                    hsinfo += item.Place + "  " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.0000") + "   CNY " + item.SubTotal * days + "\r\n";
                                }
                            }
                            placeArr.Clear();
                            rowIndex = 0;
                            foreach (var item in dac3)
                            {
                                if (string.IsNullOrWhiteSpace(item.Place))
                                {
                                    continue;
                                }
                                if (placeArr.Contains(item.Place))
                                {
                                    continue;
                                }
                                else
                                {
                                    placeArr.Add(item.Place);
                                }
                                if (!string.IsNullOrWhiteSpace(item.Place))
                                {
                                    if (rowIndex > ChildTable2.Rows.Count - 1)
                                    {
                                        var chitableRow = ChildTable2.LastRow.Clone(true);
                                        ChildTable2.AppendChild(chitableRow);
                                    }
                                    int days = dac3.FindAll(x => x.Place == item.Place).Count();
                                    SetCells(ChildTable2, doc, rowIndex, 0, item.Place);
                                    SetCells(ChildTable2, doc, rowIndex, 1, days + "天");
                                    string currencyCode = currData.Find(it => it.Id == item.Currency)?.Remark ?? "Unknown";
                                    SetCells(ChildTable2, doc, rowIndex, 2, item.Cost.ToString("#0.00") + currencyCode + "/天");
                                    var currencyRate = DecimalToString((item.SubTotal / item.Cost), 4);
                                    var sys_currencyInfo = _currencyDatas.Find(x => item.Currency == x.Id);
                                    if (sys_currencyInfo != null)
                                    {
                                        var sys_currencyCode = sys_currencyInfo.Name;
                                        var eec_currencyInfo = _EnterExitCostCurrencys.Find(x => x.Code.Equals(sys_currencyCode));
                                        if (eec_currencyInfo != null)
                                        {
                                            currencyRate = DecimalToString(eec_currencyInfo.Rate, 4);
                                        }
                                    }
                                    SetCells(ChildTable2, doc, rowIndex, 3, "汇率" + currencyRate);
                                    SetCells(ChildTable2, doc, rowIndex, 4, "CNY " + item.SubTotal + "\r\n");
                                    rowIndex++;
                                    gzinfo += item.Place + "  " + days + "天 " + item.Cost.ToString("#0.00") + currencyCode + "/天" + " 汇率" + (item.SubTotal / item.Cost).ToString("#0.00") + "   CNY " + item.SubTotal * days + "\r\n";
                                }
                            }
                            placeArr.Clear();
                            TeableBookmarkArr.Add("zsinfo", zsinfo); //住宿费详情
                            TeableBookmarkArr.Add("hs", dac2.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //伙食费
                            TeableBookmarkArr.Add("hsinfo", hsinfo); //伙食费详情
                            TeableBookmarkArr.Add("gz", dac3.Sum(x => Convert.ToDecimal(x.SubTotal)).ToString("#0.00") + " 元"); //公杂费
                            TeableBookmarkArr.Add("gzinfo", gzinfo); //公杂费详情
                            string otherFeestr = "";
                            decimal otherFee = 0.00M;
                            if (_EnterExitCosts.Visa > 0.00M)
                            {
                                otherFee += _EnterExitCosts.Visa;
                                otherFeestr += $"签证费{_EnterExitCosts.Visa.ToString("#0.00")}元、";
                            }
                            if (_EnterExitCosts.YiMiao > 0.00M)
                            {
                                otherFee += _EnterExitCosts.YiMiao;
                                otherFeestr += $"疫苗费{_EnterExitCosts.YiMiao.ToString("#0.00")}元、";
                            }
                            if (_EnterExitCosts.HeSuan > 0.00M)
                            {
                                otherFee += _EnterExitCosts.HeSuan;
                                otherFeestr += $"核酸检测费{_EnterExitCosts.HeSuan.ToString("#0.00")}元、";
                            }
                            if (_EnterExitCosts.Safe > 0.00M)
                            {
                                otherFee += _EnterExitCosts.Safe;
                                otherFeestr += $"保险费{_EnterExitCosts.Safe.ToString("#0.00")}元、";
                            }
                            if (_EnterExitCosts.Ticket > 0.00M)
                            {
                                otherFee += _EnterExitCosts.Ticket;
                                otherFeestr += $"参展门票费{_EnterExitCosts.Ticket.ToString("#0.00")}元、";
                            }
                            if (otherFeestr.Length > 0)
                            {
                                otherFeestr = otherFeestr.Substring(0, otherFeestr.Length - 1);
                                otherFeestr += "等费用";
                            }
                            TeableBookmarkArr.Add("qt", otherFee.ToString("#0.00") + " 元");//其他费用
                            TeableBookmarkArr.Add("qtinfo", otherFeestr);//其他费用第二列
                            TeableBookmarkArr.Add("fw", _EnterExitCosts.Service.ToString("#0.00") + "元/人");//服务费
                            TeableBookmarkArr.Add("AllPrice", AllPrice.ToString("#0.00") + "元/人");//表格合计费用
                            TeableBookmarkArr.Add("title", $"费用清单-{airName}({firstName})");
                            foreach (var book in TeableBookmarkArr.Keys)
                            {
                                if (doc.Range.Bookmarks[book] != null)
                                {
                                    Bookmark mark = doc.Range.Bookmarks[book];
                                    mark.Text = TeableBookmarkArr[book];
                                }
                            }
                            if (i != ClientItemList.Count - 1)
                            {
                                builder.PageSetup.Orientation = Aspose.Words.Orientation.Portrait;
                                Aspose.Words.Tables.Table table = (Aspose.Words.Tables.Table)doc.GetChild(NodeType.Table, 0, true);
                                table.ParentNode.InsertAfter(paragraph, table);
                                var CloneTable = (Aspose.Words.Tables.Table)table.Clone(true);
                                table.ParentNode.InsertAfter(CloneTable, paragraph);
                            }
                            TeableBookmarkArr.Clear();
                        }
                        bookmarkArr.Add("VisitPrice", WordAllPrice.ToString());//出访费用总额
                        bookmarkArr.Add("CnAllPrice", WordAllPrice.ConvertCNYUpper());//出访费用总额中文
                        bookmarkArr.Add("namesPrice", UsersTop.TrimEnd('、'));//各人员出访费用  付辰同志出访费用为¥73,604.8元
                        foreach (var book in bookmarkArr.Keys)
                        {
                            if (doc.Range.Bookmarks[book] != null)
                            {
                                Bookmark mark = doc.Range.Bookmarks[book];
                                mark.Text = bookmarkArr[book];
                            }
                        }
                        //MemoryStream outSteam = new MemoryStream();
                        string filsPath = AppSettingsHelper.Get("WordBasePath") + $"ForeignReceivables/File/{ClientItem.Key.Replace("\n", "")}_{_DelegationInfo.VisitCountry.Replace("|","、")}.docx";
                        //去水印
                        new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String(AsposeHelper.asposeKey)));
                        doc.Save(filsPath);
                        filesToZip.Add(filsPath);
                        //streams.Add(ClientItem.Key + ".docx", outSteam.ToArray());
                    }
                    //文件名
                    string zipFileName = _DelegationInfo.TeamName + "-收款账单.zip";
                    string zipPath = $"ForeignReceivables/File/{_DelegationInfo.TeamName}-收款账单{DateTime.Now.ToString("yyyyMMddHHmmss")}.zip";
                    try
                    {
                        using (var zip = ZipFile.Open(AppSettingsHelper.Get("WordBasePath") + zipPath, ZipArchiveMode.Create))
                        {
                            foreach (var file in filesToZip)
                            {
                                zip.CreateEntryFromFile(file, Path.GetFileName(file));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        return Ok(JsonView(false, ex.Message));
                    }
                    string url = AppSettingsHelper.Get("WordBaseUrl") + $"Office/Word/{zipPath}";
                    return Ok(JsonView(true, "成功", new { Url = url }));
                }
                return Ok(JsonView(false, "操作失败!"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
         /// 
         /// decimal保留指定位数小数
         /// 
         /// 原始数量
         /// 保留小数位数
         /// 截取指定小数位数后的数量字符串
         private static string DecimalToString(decimal num, int scale)
         {
             string numToString = num.ToString();
             int index = numToString.IndexOf(".");
             int length = numToString.Length;
             if (index != -1)
             {
                 return string.Format("{0}.{1}",
                     numToString.Substring(0, index),
                     numToString.Substring(index + 1, Math.Min(length - index - 1, scale)));
             }
             else
             {
                 return num.ToString();
             }
         }
        /// 
        /// 保留小数位数
        /// 
        /// 待处理的值
        /// 保留位数
        /// 是否四舍五入
        /// 
        private static decimal Round(decimal n, int d, bool isEnter = false)
        {
            if (isEnter)
                return decimal.Round(n, d, MidpointRounding.AwayFromZero);
            return Math.Truncate(n * (decimal)Math.Pow(10, d)) / (decimal)Math.Pow(10, d);
        }
        private void SetCells(Aspose.Words.Tables.Table table, Document doc, int rows, int cells, string val)
        {
            //获取table中的某个单元格,从0开始
            Aspose.Words.Tables.Cell lshCell = table.Rows[rows].Cells[cells];
            //将单元格中的第一个段落移除
            lshCell.FirstParagraph.Remove();
            //if (cells == 0) lshCell.CellFormat.Width = 120;
            //else if (cells == 1) lshCell.CellFormat.Width = 50;
            //else if (cells == 2) lshCell.CellFormat.Width = 120;
            //else if (cells == 3) lshCell.CellFormat.Width = 100;
            //else if (cells == 4) lshCell.CellFormat.Width = 120;
            //新建一个段落
            Paragraph p = new Paragraph(doc);
            var r = new Run(doc, val);
            r.Font.Size = 8;
            //把设置的值赋给之前新建的段落
            p.AppendChild(r);
            //将此段落加到单元格内
            lshCell.AppendChild(p);
        }
        /// 
        /// 已收账单 
        /// 提示导入出入境报价费用
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostReceivablesImportFee(int groupId)
        {
            if (groupId < 1) return Ok(JsonView(false, "请传入有效的GroupId参数!"));
            var data = await GeneralMethod.ReceivablesImportFeeAsync(groupId);
            var view = _mapper.Map>(data);
            return Ok(JsonView(true, "操作成功", view));
        }
        #endregion
        #region 已收款项
        /// 
        /// 已收款项
        /// 查询
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAmountReceived(AmountReceivedDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Ok(JsonView(false, "参数不能为空!"));
                }
                Result ffrData = await _proceedsReceivedRep.PostAmountReceived(dto.DiId);
                dynamic data = null;
                if (dto.PortType == 1)
                {
                    if (ffrData.Code != 0)
                    {
                        return Ok(JsonView(false, ffrData.Msg));
                    }
                    data = ffrData.Data;
                }
                else if (dto.PortType == 2)
                {
                    if (ffrData.Code != 0)
                    {
                        return Ok(JsonView(false, ffrData.Msg));
                    }
                    data = ffrData.Data;
                }
                else if (dto.PortType == 2)
                {
                    if (ffrData.Code != 0)
                    {
                        return Ok(JsonView(false, ffrData.Msg));
                    }
                    data = ffrData.Data;
                }
                else
                {
                    return Ok(JsonView(false, "请选择正确的端口号!"));
                }
                return Ok(JsonView(true, "操作成功!", data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 已收款项
        /// Add Or Edit
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAmountReceivedAddOrEdit(AmountReceivedAddOrEditDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Ok(JsonView(false, "参数不能为空!"));
                }
                Result ffrData = await _proceedsReceivedRep.PostAmountReceivedAddOrEditDto(dto);
                if (dto.PortType == 1)
                {
                    if (ffrData.Code != 0)
                    {
                        return Ok(JsonView(false, ffrData.Msg));
                    }
                }
                else if (dto.PortType == 2)
                {
                    if (ffrData.Code != 0)
                    {
                        return Ok(JsonView(false, ffrData.Msg));
                    }
                }
                else if (dto.PortType == 2)
                {
                    if (ffrData.Code != 0)
                    {
                        return Ok(JsonView(false, ffrData.Msg));
                    }
                }
                else
                {
                    return Ok(JsonView(false, "请选择正确的端口号!"));
                }
                return Ok(JsonView(true, "操作成功!"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 已收款项
        /// Del
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostAmountReceived_Del(AmountReceivedDelDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Ok(JsonView(false, "参数不能为空!"));
                }
                Result ffrData = await _proceedsReceivedRep.PostAmountReceivedDel(dto);
                if (ffrData.Code != 0)
                {
                    return Ok(JsonView(false, ffrData.Msg));
                }
                return Ok(JsonView(true, "操作成功!"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        #endregion
        #region 收款退还与其他款项 --> 收款退还
        /// 
        /// 收款退还与其他款项
        /// 查询 根据团组Id
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPaymentRefundAndOtherMoneyItemByDiId(PaymentRefundAndOtherMoneyItemByDiIdDto dto)
        {
            try
            {
                if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
                if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
                if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
                #region 页面功能权限处理
                PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase();
                pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
                if (pageFunAuth.CheckAuth == 0)
                {
                    return Ok(JsonView(false, "您没有当前页面查询权限!"));
                }
                #endregion
                Result _result = await _paymentRefundAndOtherMoneyRep._ItemByDiId(dto.DiId);
                if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3)  //1 Web 2 Android 3 Ios
                {
                    if (_result.Code != 0)
                    {
                        return Ok(JsonView(false, _result.Msg));
                    }
                    var data = new
                    {
                        PageFuncAuth = pageFunAuth,
                        Data = _result.Data
                    };
                    return Ok(JsonView(true, "操作成功!", data));
                }
                else
                {
                    return Ok(JsonView(false, "请输入正确的端口号! 1 Web 2 Android 3 Ios;"));
                }
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 收款退还与其他款项
        /// 删除 
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPaymentRefundAndOtherMoneyDel(PaymentRefundAndOtherMoneyDelDto dto)
        {
            try
            {
                if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
                if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
                if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
                PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase();
                #region 页面功能权限处理
                pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
                #endregion
                if (pageFunAuth.DeleteAuth == 0)
                {
                    return Ok(JsonView(false, "您没有当前页面删除权限!"));
                }
                Result _result = await _paymentRefundAndOtherMoneyRep._Del(dto);
                if (_result.Code != 0)
                {
                    return Ok(JsonView(false, _result.Msg));
                }
                return Ok(JsonView(true, "操作成功!"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 收款退还与其他款项
        /// Info Data Source
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPaymentRefundAndOtherMoneyInfoDataSource(PortDtoBase dto)
        {
            try
            {
                Result _result = await _paymentRefundAndOtherMoneyRep._InfoDataSource(dto);
                if (_result.Code != 0)
                {
                    return Ok(JsonView(false, _result.Msg));
                }
                return Ok(JsonView(true, "查询成功!", _result.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 收款退还与其他款项
        /// Info
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPaymentRefundAndOtherMoneyInfo(PaymentRefundAndOtherMoneyInfoDto dto)
        {
            if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
            var view = await _paymentRefundAndOtherMoneyRep._Info(dto);
            return Ok(view);
        }
        /// 
        /// 收款退还与其他款项 --> 收款退还(只保留人名币)
        /// 操作(Add Or Edit)
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPaymentRefundAndOtherMoneyAddOrEdit(PaymentRefundAndOtherMoneyAddOrEditDto dto)
        {
            if (dto == null) return Ok(JsonView(false, "参数不能为空!"));
            if (dto.PageId <= 0) return Ok(JsonView(false, "请传入正确的的页面Id!"));
            if (dto.UserId <= 0) return Ok(JsonView(false, "请传入正确的的员工Id!"));
            #region 页面功能权限处理
            PageFunAuthViewBase pageFunAuth = new PageFunAuthViewBase();
            pageFunAuth = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
            #endregion
            if (dto.Status == 1) //add
            {
                if (pageFunAuth.AddAuth == 0) return Ok(JsonView(false, "您没有当前页面添加权限!"));
            }
            else if (dto.Status == 2) //edit
            {
                if (pageFunAuth.EditAuth == 0) return Ok(JsonView(false, "您没有当前页面编辑权限!"));
            }
            else return Ok(JsonView(false, "请输入正确的操作状态! 1 添加 2 修改!"));
            return Ok(await _paymentRefundAndOtherMoneyRep._AddOrEdit(dto));
        }
        #endregion
        #region 应收报表
        /// 
        /// 应收报表
        /// 查询 根据日期范围
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostSyntheticalReceivableByDateRange(PostSyntheticalReceivableByDateRangeDto dto)
        {
            string sqlWhere = " Where di.IsDel=0 ";
            #region 验证
            if (string.IsNullOrEmpty(dto.beginDt) && string.IsNullOrEmpty(dto.endDt))
            {
                return Ok(JsonView(false, "日期参数至少填写一个!"));
            }
            if (!string.IsNullOrEmpty(dto.beginDt))
            {
                if (Regex.Match(dto.beginDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
                {
                    return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
                }
                else
                {
                    sqlWhere += string.Format(@" And di.VisitDate >= '{0} 00:00:00' ", dto.beginDt);
                }
            }
            if (!string.IsNullOrEmpty(dto.endDt))
            {
                if (Regex.Match(dto.endDt, @"^\d{4}-\d{2}-\d{2}$").Value.Length < 1)
                {
                    return Ok(JsonView(false, "日期参数格式错误,应为yyyy-MM-dd!"));
                }
                else
                {
                    sqlWhere += string.Format(@" And di.VisitDate <= '{0} 23:59:59' ", dto.endDt);
                }
            }
            if (!string.IsNullOrEmpty(dto.groupName))
            {
                sqlWhere += string.Format(@" And di.TeamName Like '%{0}%' ", dto.groupName);
            }
            #endregion
            //已收款项 判断如果是市场部的人员进来的话 只显示自己的 其他的都显示全部的
            string userSqlWhere = "";
            var userInfos = await _sqlSugar.Queryable()
                                           .InnerJoin((u, d) => u.DepId == d.Id)
                                           .Where((u, d) => u.IsDel == 0 && d.DepName.Contains("市场部") && u.Id == dto.CurrUserId)
                                           .ToListAsync();
            if (userInfos.Count > 0) userSqlWhere = string.Format(@$" And JietuanOperator={dto.CurrUserId} ");
            //排序倒序
            string sql = string.Format(@$"select distinct fr.diid,di.TeamName,di.ClientUnit,di.VisitDate,di.CreateTime from Fin_ForeignReceivables fr join Grp_DelegationInfo di on fr.DIID = di.id {sqlWhere}  {userSqlWhere}  Order By di.VisitDate Desc");
            var list_rst = _sqlSugar.SqlQueryable(sql).ToList();
            var setData = _sqlSugar.Queryable().Where(it => it.IsDel == 0).ToList();
            decimal sumAll_fr = 0M; //应收
            decimal sumAll_pr = 0M; //已收
            decimal sumAll_balance = 0M; //尾款
            if (list_rst.Count > 0)
            {
                int rowNumber = 1;
                foreach (var item_rst in list_rst)
                {
                    DateTime dtTemp;
                    bool b = DateTime.TryParse(item_rst.visitDate, out dtTemp);
                    if (b)
                    {
                        item_rst.visitDate = dtTemp.ToString("yyyy-MM-dd");
                    }
                    item_rst.No = rowNumber;
                    rowNumber++;
                    int diId = item_rst.diid;
                    decimal sum_fr = 0M;
                    decimal sum_pr = 0M;
                    string str_client = string.Empty;
                    decimal sum_refund = 0M; //收款退还
                    decimal sum_extra = 0M; //超支费用
                    decimal balance = 0M;
                    string str_schedule = string.Empty;
                    //1.应收
                    string sql_fr = string.Format(@" Select * From Fin_ForeignReceivables Where IsDel=0 And Diid={0} ", diId);
                    List list_fr = _sqlSugar.SqlQueryable(sql_fr).ToList();
                    sum_fr = list_fr.Sum(s => s.ItemSumPrice);
                    //2.已收
                    string sql_pr = string.Format(@" Select * From Fin_ProceedsReceived Where IsDel=0 And Diid={0} ", diId);
                    List list_pr = _sqlSugar.SqlQueryable(sql_pr).ToList();
                    foreach (var item_pr in list_pr)
                    {
                        sum_pr += item_pr.Price;
                        str_client += string.Format(@"{0};", item_pr.Client);
                        str_schedule += string.Format(@"{0};", item_pr.Remark);
                    }
                    if (str_schedule.Length > 0)
                    {
                        str_schedule = str_schedule.TrimEnd(';');
                    }
                    if (str_client.Length > 0)
                    {
                        str_client = str_client.TrimEnd(';');
                    }
                    //3.收款退还
                    string sql_other = string.Format(@"Select * From  Fin_PaymentRefundAndOtherMoney prao
					  Inner Join Grp_CreditCardPayment ccp On prao.Id = ccp.CId
					  Where ccp.CTable = 285 And ccp.IsPay = 1 And prao.IsDel = 0 And ccp.IsDel = 0 And prao.DiId = {0}", diId);
                    List list_other = _sqlSugar.SqlQueryable(sql_other).ToList();
                    sum_refund = list_other.Sum(s => s.PayMoney * s.DayRate);
                    //4.超支
                    //string sql_extra = string.Format(@" Select c.* From Fin_GroupExtraCost f 
                    //Inner join Grp_CreditCardPayment c On f.Id = c.CId 
                    //Where c.CTable = 1015 And c.IsPay = 1 And f.IsDel = 0 And c.IsDel = 0 And f.DiId = {0} ", diId);
                    //List list_extra = _sqlSugar.SqlQueryable(sql_extra).ToList();
                    //sum_extra = list_extra.Sum(s => s.PayMoney * s.DayRate);
                    item_rst.frPrice = sum_fr.ToString("#0.00");
                    item_rst.extraPrice = sum_extra.ToString("#0.00");
                    item_rst.receivableTotal = (sum_fr + sum_extra).ToString("#0.00");
                    item_rst.prPrice = sum_pr.ToString("#0.00");
                    item_rst.refundAmount = sum_refund.ToString("#0.00");
                    item_rst.receivedTotal = (sum_pr - sum_refund).ToString("#0.00");
                    item_rst.balPrice = ((sum_fr + sum_extra) - (sum_pr - sum_refund)).ToString("#0.00");
                    item_rst.prClient = str_client;
                    item_rst.schedule = str_schedule;
                    string tempVisitDate = Convert.ToDateTime(item_rst.visitDate).ToString("yyyy-MM-dd");
                    sumAll_fr += (sum_fr + sum_extra);
                    sumAll_pr += (sum_pr - sum_refund);
                    sumAll_balance += ((sum_fr + sum_extra) - (sum_pr - sum_refund));
                    #region 单位应收已收细项(以应收费用名称为主去(已收费用)匹配) 新增 雷怡 2024-5-08 16:35:28
                    List feeDatas = new List();
                    //匹配上的数据
                    foreach (var item in list_fr)
                    {
                        var prInfo = list_pr.Find(it => item.PriceName.Contains(it.Client) || item.PriceName.Equals(it.Client));
                        decimal _balancePayment = 0.00M;
                        if (item.Currency == prInfo?.Currency)
                        {
                            _balancePayment = item.ItemSumPrice - prInfo?.Price ?? 0.00M;
                        }
                        feeDatas.Add(new ClientFeeInfoView
                        {
                            client = item.PriceName,
                            frMoney = item.ItemSumPrice.ToString("#0.00"),
                            frCurrency = setData.Find(it => it.Id == item.Currency)?.Name ?? "-",
                            frRate = item.Rate.ToString("#0.0000"),
                            prReceivablesType = setData.Find(it => it.Id == prInfo?.ReceivablesType)?.Name ?? "",
                            prTime = prInfo?.SectionTime ?? "-",
                            prMoney = prInfo?.Price.ToString("#0.00") ?? "-",
                            prCurrency = setData.Find(it => it.Id == prInfo?.Currency)?.Name ?? "",
                            balPayment = _balancePayment.ToString("#0.00")
                        });
                    }
                    //未匹配上的数据
                    foreach (var item in list_pr)
                    {
                        var frInfo = list_fr.Find(it => it.PriceName.Contains(item.Client) || it.PriceName.Equals(item.Client));
                        if (frInfo == null)
                        {
                            feeDatas.Add(new ClientFeeInfoView
                            {
                                client = item.Client + "[未匹配上的已收数据(应收已收公司名称不一致)]",
                                frMoney = "0.00",
                                frCurrency = "-",
                                frRate = "0.0000",
                                prReceivablesType = setData.Find(it => it.Id == item?.ReceivablesType)?.Name ?? "",
                                prTime = item?.SectionTime ?? "-",
                                prMoney = item?.Price.ToString("#0.00") ?? "0.00",
                                prCurrency = setData.Find(it => it.Id == item?.Currency)?.Name ?? "",
                                balPayment = "0.00"
                            });
                        }
                    }
                    item_rst.feeItem = feeDatas;
                    #endregion
                }
                PostSyntheticalReceivableByDateRangeResultView result = new PostSyntheticalReceivableByDateRangeResultView();
                result.total_fr = sumAll_fr.ToString("#0.00");
                result.total_pr = sumAll_pr.ToString("#0.00");
                result.total_balance = sumAll_balance.ToString("#0.00");
                result.dataList = new List(list_rst);
                if (dto.requestType == 1)
                {
                    return Ok(JsonView(true, "请求成功", result, list_rst.Count));
                }
                else
                {
                    //----------------------------
                    List list_Ex = new List();
                    WorkbookDesigner designer = new WorkbookDesigner();
                    designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/应收款项模板 - 副本.xls");
                    int excNo = 1;
                    foreach (var item in list_rst)
                    {
                        Excel_SyntheticalReceivableByDateRange exc = new Excel_SyntheticalReceivableByDateRange();
                        exc.No = excNo.ToString();
                        excNo++;
                        exc.TeamName = item.teamName;
                        exc.ClientUnit = item.clientUnit;
                        exc.VisitDate = item.visitDate;
                        exc.Accounts = item.frPrice;
                        exc.Extra = item.extraPrice;
                        exc.ReceivableTotal = item.receivableTotal;
                        exc.Received = item.prPrice;
                        exc.RefundAmount = item.refundAmount;
                        exc.ReceivedTotal = item.receivedTotal;
                        exc.Balance = item.balPrice;
                        exc.Collection = item.schedule;
                        DateTime time = Convert.ToDateTime(item.visitDate);
                        TimeSpan ts = DateTime.Now - time;
                        float SY = float.Parse(item.balPrice);
                        if (ts.Days >= 365 && SY > 0)
                        {
                            exc.Sign = "需收款";
                        }
                        else
                        {
                            exc.Sign = "";
                        }
                        list_Ex.Add(exc);
                    }
                    var dt = CommonFun.GetDataTableFromIList(list_Ex);
                    dt.TableName = "Excel_SyntheticalReceivableByDateRange";
                    if (dt != null)
                    {
                        designer.SetDataSource("SumPrice", "应收合计:" + result.total_fr + "RMB  已收合计:" + result.total_pr + "RMB  余款合计:" + result.total_balance + "RMB");
                        //数据源
                        designer.SetDataSource(dt);
                        //根据数据源处理生成报表内容
                        designer.Process();
                        string fileName = ("Receivable/应收款项(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
                        designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
                        string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
                        return Ok(JsonView(true, "成功", new { url = rst }));
                    }
                }
            }
            return Ok(JsonView(true, "获取成功", "", list_rst.Count));
        }
        #endregion
        #region 付款申请
        /// 
        /// 付款申请
        /// 基础数据
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPayRequestInit()
        {
            try
            {
                var conpanyDatas = _sqlSugar.Queryable()
                                            .Where(it => it.IsDel == 0)
                                            .Select(it => new
                                            {
                                                Id = it.Id,
                                                ConpamyName = it.CompanyName
                                            }).ToList();
                return Ok(JsonView(true, "操作成功!", new { ConpanyData = conpanyDatas }));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 付款申请 (PageId=51)
        /// 查询 根据日期范围
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPayRequest_Center(PostPayRequestByDateRangeDto dto)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            #region 验证
            DateTime beginDt, endDt;
            string format = "yyyy-MM-dd";
            if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out beginDt))
            {
                return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
            }
            if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt))
            {
                return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
            }
            #region 页面操作权限验证
            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
            if (pageFunAuthView.CheckAuth == 0) return Ok(JsonView(false, "您没有查看权限!"));
            #endregion
            #endregion
            try
            {
                PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
                var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync("paymentRequestCheckedData");
                if (checkedStr != null)
                {
                    checkedView = JsonConvert.DeserializeObject(checkedStr.ToString());
                    if (checkedView.GroupIds.Count > 0)
                    {
                        checkedView.GroupIds = checkedView.GroupIds.OrderBy(x => x).ToList();
                    }
                }
                tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(dto.Status, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
                tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(dto.Status, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
                stopwatch.Stop();
                return Ok(JsonView(true, $"查询成功!耗时{stopwatch.ElapsedMilliseconds / 1000}s", new { daily = dailyResult, group = groupResult }));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// 
        /// 根据团组类型类型处理团组费用所属公司
        /// 
        /// 
        /// 
        private CompanyInfo ExpenseCompanyByTeamId(int teamId)
        {
            CompanyInfo _companyInfo = new CompanyInfo();
            List _SiChuan = new List() {
                38 , // 政府团
                39 , // 企业团
                40 , // 散客团
                102, // 未知
                248, // 非团组
                691, // 四川-会务活动
                762, // 四川-赛事项目收入
                1048,//高校团
            };
            List _ChengDu = new List() {
                302,  // 成都-会务活动
                1047, // 成都-赛事项目收入
            };
            if (_SiChuan.Contains(teamId))
            {
                _companyInfo.Id = 2;
                _companyInfo.ConpanyName = "四川泛美交流有限公司";
            }
            if (_ChengDu.Contains(teamId))
            {
                _companyInfo.Id = 1;
                _companyInfo.ConpanyName = "成都泛美商务有限公司";
            }
            return _companyInfo;
        }
        /// 
        /// 付款申请(团组费用申请相关) 
        /// 查询 根据日期范围
        /// 
        /// 
        /// 
        /// 
        /// 
        private tree_Group_DailyFeePaymentResult PayRequest_GroupPaymentByDateRange(int status, List _groupIds, List _hotelSubIds, string beginDt, string endDt)
        {
            tree_Group_DailyFeePaymentResult _DailyFeePaymentResult = new tree_Group_DailyFeePaymentResult();
            List dataList = new List();
            #region sql条件处理
            string sqlWhere = string.Format(@" And (AuditGMDate Between '{0} 00:00:00' And '{1} 23:59:59') ", beginDt, endDt);
            if (status == 2)
            {
                if (_hotelSubIds.Count > 1)
                {
                    var hrIds = _sqlSugar.Queryable().Where(it => _hotelSubIds.Contains(it.Id) && it.Price != 0).Select(it => it.HrId).Distinct().ToList();
                    var hrIds1 = _sqlSugar.Queryable().Where(it => it.CTable == 76 && hrIds.Contains(it.CId)).Select(it => it.Id).ToList();
                    if (hrIds1.Count > 1)
                    {
                        _groupIds.AddRange(hrIds1);
                    }
                }
                if (_groupIds.Count < 1)
                {
                    _DailyFeePaymentResult.dataList = new List();
                    return _DailyFeePaymentResult;
                }
                sqlWhere += string.Format(@" And Id In ({0})", string.Join(",", _groupIds));
            }
            string sql_1 = string.Format(@"Select * From Grp_CreditCardPayment Where IsDel = 0 And IsPay = 0 And (IsAuditGM = 1 Or IsAuditGM = 3 ){0}", sqlWhere);
            #endregion
            var _paymentDatas = _sqlSugar.SqlQueryable(sql_1).ToList();//付款信息
            _DailyFeePaymentResult.gz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 0).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); //公转
            _DailyFeePaymentResult.sz = _paymentDatas.Where(it => it.OrbitalPrivateTransfer == 1).Sum(it => ((it.PayMoney * it.DayRate) / 100) * it.PayPercentage); ; //私转
            List groupIds = _paymentDatas.Select(it => it.DIId).Distinct().ToList();
            var _groupDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
            //_groupDatas = (List)_groupDatas.GroupBy(it => it.TeamDid);
            #region 相关基础数据源
            var userDatas = _sqlSugar.Queryable().ToList();
            var setDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0).ToList();
            var countryFeeDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0).ToList();
            var hotelDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            var hotelContentDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && it.IsPay == 0 && it.Price != 0 && groupIds.Contains(it.DiId)).ToList();
            var opDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            var visaDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
            var ioaDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            var insureDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            var airDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DIId)).ToList();
            //var otherMoneyDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.Diid)).ToList();
            var otherMoneyDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            var refundPaymentDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            var ExtraCostDatas = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.DiId)).ToList();
            #endregion
            //Expense company
            foreach (var groupInfo in _groupDatas)
            {
                List childList = new List();
                var groupPaymentDatas = _paymentDatas.Where(it => groupInfo.Id == it.DIId).ToList();
                int rouNumber = 1;
                foreach (var payInfo in groupPaymentDatas)
                {
                    string priName = "-";
                    string orbitalPrivateTransfer = payInfo.OrbitalPrivateTransfer == 0 ? "公转" : payInfo.OrbitalPrivateTransfer == 1 ? "私转" : "-";
                    switch (payInfo.CTable)
                    {
                        case 76:  //76	酒店预订
                            priName = $"[费用名称:{hotelDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.HotelName ?? ""}]";
                            break;
                        case 79:  //79	车/导游地接
                            var opData = opDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id);
                            if (opData != null)
                            {
                                string area = "";
                                bool b = int.TryParse(opData.Area, out int areaId);
                                if (b)
                                {
                                    string area1 = countryFeeDatas.Find(it => it.Id == areaId)?.Country ?? "-";
                                    area = $"{area1}({setDatas.Find(it => it.Id == opData.PriceType)?.Name ?? "-"})";
                                }
                                else area = opData.Area;
                                string opPriName = "-";
                                if (!string.IsNullOrEmpty(opData.PriceName)) opPriName = opData.PriceName;
                                area += $"({opPriName})";
                                if (payInfo.OrbitalPrivateTransfer == 0) //公转
                                {
                                    priName = $"【{orbitalPrivateTransfer}】【导游: {opData.ServiceGuide} 】[费用名称:{area}]";
                                }
                                else if (payInfo.OrbitalPrivateTransfer == 1) //私转
                                {
                                    priName = $"【{orbitalPrivateTransfer}】【导游:{opData.ServiceGuide}】[费用名称:{area}]";
                                }
                            }
                            break;
                        case 80:  // 80   签证
                            string sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from  Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
                            List arr = _sqlSugar.SqlQueryable(sql).ToList();
                            string visaClientName = visaDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.VisaClient ?? "";
                            string clientName = "-";
                            if (Regex.Match(visaClientName, @"\d+,?").Value.Length > 0)
                            {
                                string[] temparr = visaClientName.Split(',');
                                string fistrStr = temparr[0];
                                int count = temparr.Count();
                                int tempId;
                                bool success = int.TryParse(fistrStr, out tempId);
                                if (success)
                                {
                                    SimplClientInfo tempInfo = arr.FirstOrDefault(s => s.Id == tempId);
                                    if (tempInfo != null)
                                    {
                                        if (count > 1)
                                        {
                                            clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
                                        }
                                        else
                                        {
                                            clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
                                        }
                                    }
                                }
                                else
                                {
                                    clientName = fistrStr;
                                }
                            }
                            priName = $"[费用名称:{clientName}]";
                            break;
                        case 81:  // 81	邀请/公务活动
                            priName = $"[费用名称:{ioaDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.Inviter ?? " -"}]";
                            break;
                        case 82:  // 82	团组客户保险
                            string bx_sql = string.Format("select b.Id,b.Pinyin,b.lastName,b.firstName,b.phone from  Grp_TourClientList a, Crm_DeleClient b where a.clientid = b.id and a.isdel = 0 and a.diid = {0}", groupInfo.Id);
                            List bx_arr = _sqlSugar.SqlQueryable(bx_sql).ToList();
                            string bx_ClientName = insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? "";
                            string bx_clientName = "-";
                            if (Regex.Match(bx_ClientName, @"\d+,?").Value.Length > 0)
                            {
                                string[] temparr = bx_ClientName.Split(',');
                                string fistrStr = temparr[0];
                                int count = temparr.Count();
                                int tempId;
                                bool success = int.TryParse(fistrStr, out tempId);
                                if (success)
                                {
                                    SimplClientInfo tempInfo = bx_arr.FirstOrDefault(s => s.Id == tempId);
                                    if (tempInfo != null)
                                    {
                                        if (count > 1)
                                        {
                                            bx_clientName = string.Format(@"{0}{1}等{2}人", tempInfo.LastName, tempInfo.FirstName, count);
                                        }
                                        else
                                        {
                                            bx_clientName = string.Format(@"{0}{1}", tempInfo.LastName, tempInfo.FirstName);
                                        }
                                    }
                                }
                                else
                                {
                                    bx_clientName = fistrStr;
                                }
                            }
                            //priName = $"[费用名称:{insureDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.ClientName ?? " -"}]";
                            priName = $"[费用名称:{bx_clientName}]";
                            break;
                        case 85:  // 85	机票预订
                            string flightsCode = airDatas.Find(it => payInfo.DIId == it.DIId && payInfo.CId == it.Id)?.FlightsCode ?? "-";
                            string airPayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "-";
                            priName = $"{flightsCode}【{airPayType}】";
                            break;
                        case 98:  //  98	其他款项
                            priName = $"[费用名称:{otherMoneyDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
                            break;
                        case 285:  //  285 收款退还
                            priName = $"[费用名称:{refundPaymentDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
                            break;
                        case 1015:  //  1015	超支费用
                            priName = $"[费用名称:{ExtraCostDatas.Find(it => payInfo.DIId == it.DiId && payInfo.CId == it.Id)?.PriceName ?? " -"}]";
                            break;
                        default:
                            priName = "";
                            break;
                    }
                    bool status1 = false;
                    if (_groupIds != null)
                    {
                        status1 = _groupIds.Contains(payInfo.Id);
                    }
                    if (payInfo.CTable == 76) //酒店单独处理
                    {
                        var hotelContents = hotelContentDatas.Where(it => it.HrId == payInfo.CId);
                        List childInfos = new List();
                        foreach (var hotelContent in hotelContents)
                        {
                            string subPriceName = "";
                            if (hotelContent.PriceType == 1) subPriceName = "房费";
                            else if (hotelContent.PriceType == 2) subPriceName = "早餐";
                            else if (hotelContent.PriceType == 3) subPriceName = "地税";
                            else if (hotelContent.PriceType == 4) subPriceName = "城市税";
                            if (string.IsNullOrEmpty(subPriceName)) subPriceName = priName;
                            else subPriceName = $"{priName.Replace("]", "")}-{subPriceName}]";
                            string payeeStr1 = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
                            string.IsNullOrEmpty(hotelContent.Payee) ? "-" : hotelContent.Payee,
                            string.IsNullOrEmpty(hotelContent.OtherBankName) ? "-" : hotelContent.OtherBankName,
                            string.IsNullOrEmpty(hotelContent.OtherSideNo) ? "-" : hotelContent.OtherSideNo);
                            decimal _PaymentAmount1 = hotelContent.Price;//此次付款金额
                            decimal _CNYSubTotalAmount1 = _PaymentAmount1 * hotelContent.Rate;//此次付款金额
                            _CNYSubTotalAmount1 = Convert.ToDecimal(_CNYSubTotalAmount1.ToString("#0.00"));
                            //酒店子项Id选中状态更改
                            if (_hotelSubIds != null) status1 = _hotelSubIds.Contains(hotelContent.Id);
                            var childInfo1 = new Group_DailyFeePaymentContentInfolView()
                            {
                                IsChecked = status1,
                                Id = payInfo.Id,
                                HotelSubId = hotelContent.Id,
                                Payee = payeeStr1,
                                RowNumber = rouNumber,
                                Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
                                ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                                PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
                                TransferMark = orbitalPrivateTransfer,
                                PriceName = subPriceName,
                                ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
                                PayCurrCode = setDatas.Find(it => it.Id == hotelContent.Currency)?.Name ?? "",
                                PaymentAmount = _PaymentAmount1,
                                PayRate = hotelContent.Rate,
                                CNYSubTotalAmount = _CNYSubTotalAmount1,
                                AuditStatus = payInfo.IsAuditGM
                            };
                            string remaksDescription1 = $"【{childInfo1.PayType}】【{childInfo1.ModuleName}】{rouNumber}、[申请人:{childInfo1.Applicant}]{subPriceName}[收款方:{childInfo1.Payee}] {childInfo1.PayCurrCode} {_PaymentAmount1.ToString("#0.00")}、CNY:{childInfo1.CNYSubTotalAmount.ToString("#0.00")}(团组:{groupInfo.TeamName})";
                            childInfo1.RemaksDescription = remaksDescription1;
                            if (status == 2)
                            {
                                if (status1)
                                {
                                    childInfos.Add(childInfo1);
                                }
                            }
                            else childInfos.Add(childInfo1);
                            rouNumber++;
                        }
                        childList.AddRange(childInfos);
                    }
                    else
                    {
                        string payeeStr = string.Format(@" {0},开户行:{1},银行卡号:{2} ",
                            string.IsNullOrEmpty(payInfo.Payee) ? "-" : payInfo.Payee,
                            string.IsNullOrEmpty(payInfo.OtherBankName) ? "-" : payInfo.OtherBankName,
                            string.IsNullOrEmpty(payInfo.OtherSideNo) ? "-" : payInfo.OtherSideNo);
                        decimal _PaymentAmount = (payInfo.PayMoney / 100) * payInfo.PayPercentage;//此次付款金额
                        decimal _CNYSubTotalAmount = _PaymentAmount * payInfo.DayRate;//此次付款金额
                        _CNYSubTotalAmount = Convert.ToDecimal(_CNYSubTotalAmount.ToString("#0.00"));
                        var childInfo = new Group_DailyFeePaymentContentInfolView()
                        {
                            IsChecked = status1,
                            Id = payInfo.Id,
                            Payee = payeeStr,
                            RowNumber = rouNumber,
                            Applicant = userDatas.Find(it => it.Id == payInfo.CreateUserId)?.CnName ?? "",
                            ApplicantDt = payInfo.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                            PayType = setDatas.Find(it => it.Id == payInfo.PayDId)?.Name ?? "",
                            TransferMark = orbitalPrivateTransfer,
                            PriceName = priName,
                            ModuleName = setDatas.Find(it => it.Id == payInfo.CTable)?.Name ?? "",
                            PayCurrCode = setDatas.Find(it => it.Id == payInfo.PaymentCurrency)?.Name ?? "",
                            PaymentAmount = _PaymentAmount,
                            PayRate = payInfo.DayRate,
                            CNYSubTotalAmount = _CNYSubTotalAmount,
                            AuditStatus = payInfo.IsAuditGM
                        };
                        string remaksDescription = $"【{childInfo.PayType}】【{childInfo.ModuleName}】{rouNumber}、[申请人:{childInfo.Applicant}]{priName}[收款方:{childInfo.Payee}] {childInfo.PayCurrCode} {_PaymentAmount.ToString("#0.00")}、CNY:{childInfo.CNYSubTotalAmount.ToString("#0.00")}(团组:{groupInfo.TeamName})";
                        childInfo.RemaksDescription = remaksDescription;
                        childList.Add(childInfo);
                        rouNumber++;
                    }
                }
                CompanyInfo companyInfo = new CompanyInfo();
                companyInfo = ExpenseCompanyByTeamId(groupInfo.TeamDid);
                dataList.Add(new tree_Group_DailyFeePaymentPageListView()
                {
                    Id = Guid.NewGuid().ToString("N"),
                    GroupName = groupInfo.TeamName,
                    CompanyId = companyInfo.Id,
                    ConpanyName = companyInfo.ConpanyName,
                    CNYTotalAmount = childList.Sum(it => it.CNYSubTotalAmount),
                    ChildList = childList,
                });
            }
            _DailyFeePaymentResult.dataList = dataList;
            return _DailyFeePaymentResult;
        }
        /// 
        /// 付款申请(日付申请相关)
        /// 查询 根据日期范围
        /// 
        /// 
        /// 
        /// 
        /// 
        private tree_Fin_DailyFeePaymentResult PayRequest_DailyByDateRange(int status, List _dailyIds, string beginDt, string endDt)
        {
            #region sql条件处理
            string sqlWhere = string.Format(@" And dfp.CreateTime between '{0} 00:00:00' And '{1} 23:59:59' ", beginDt, endDt);
            if (status == 2)
            {
                if (_dailyIds.Count < 1)
                {
                    return new tree_Fin_DailyFeePaymentResult() { childList = new List() };
                }
                sqlWhere += string.Format(@" And dfp.Id  In({0}) ", string.Join(",", _dailyIds));
            }
            string sql_1 = string.Format(@"Select * From (	
                                                Select row_number() over (order by dfp.Id Desc) as RowNumber,
                                                    dfp.Id,dfp.CompanyId,c.CompanyName,dfp.Instructions,dfp.SumPrice,
                                                    dfp.CreateUserId,u.CnName CreateUser,dfp.CreateTime,dfp.FAudit,dfp.MAudit,
                                                    dfp.PriceTypeId,dfp.TransferTypeId 
                                                From Fin_DailyFeePayment dfp
                                                Inner Join Sys_Company c On dfp.CompanyId = c.Id
                                                Left Join Sys_Users u On dfp.CreateUserId = u.Id
                                                Where dfp.IsDel=0 {0} And dfp.FAudit = 1 And dfp.MAudit = 1 And dfp.IsPay = 0
                                                ) temp ", sqlWhere);
            #endregion
            List DailyFeePaymentData = _sqlSugar.SqlQueryable(sql_1).ToList();
            Dictionary dic_setData = new Dictionary();
            Sys_SetDataType stGZ = _daiRep.Query(s => s.Name == "公转").First();
            Sys_SetDataType stSZ = _daiRep.Query(s => s.Name == "私转").First();
            foreach (var item in DailyFeePaymentData)
            {
                if (_dailyIds != null)
                {
                    item.IsChecked = _dailyIds.Contains(item.Id);
                }
                if (dic_setData.ContainsKey(item.PriceTypeId))
                {
                    item.priceTypeStr = dic_setData[item.PriceTypeId];
                }
                else
                {
                    Sys_SetData sd_priceType = _daiRep.Query(s => s.Id == item.PriceTypeId).First();
                    if (sd_priceType != null)
                    {
                        item.priceTypeStr = sd_priceType.Name;
                        dic_setData.Add(item.PriceTypeId, sd_priceType.Name);
                    }
                }
                if (dic_setData.ContainsKey(item.transferTypeId))
                {
                    item.transferTypeIdStr = dic_setData[item.transferTypeId];
                    Sys_SetData sd_transfer = _daiRep.Query(s => s.Id == item.transferTypeId).First();
                    if (sd_transfer != null)
                    {
                        item.transferParentId = sd_transfer.STid;
                        item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
                    }
                }
                else
                {
                    Sys_SetData sd_transfer = _daiRep.Query(s => s.Id == item.transferTypeId).First();
                    if (sd_transfer != null)
                    {
                        item.transferTypeIdStr = sd_transfer.Name;
                        item.transferParentId = sd_transfer.STid;
                        item.transferParentIdStr = sd_transfer.STid == stGZ.Id ? "公转" : sd_transfer.STid == stSZ.Id ? "私转" : "";
                        dic_setData.Add(item.transferTypeId, sd_transfer.Name);
                    }
                }
                string feeContentSql = string.Format(@"Select * From Fin_DailyFeePaymentContent 
                                                        Where IsDel=0 And DFPId = {0} ", item.Id);
                item.childList = _sqlSugar.SqlQueryable(feeContentSql).ToList();
                int rowNumber = 1;
                foreach (var subItem in item.childList)
                {
                    string remaksDescription = $"{rowNumber}、【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.0000")}(单价:{subItem.Price.ToString("#0.0000")} * {subItem.Quantity.ToString("#0.0000")})";
                    subItem.RemaksDescription = remaksDescription;
                    string excelRemaksDescription = $"【{item.priceTypeStr}】{item.Instructions}({subItem.PriceName}) CNY:{subItem.ItemTotal.ToString("#0.0000")}(单价:{subItem.Price.ToString("#0.0000")} * {subItem.Quantity.ToString("#0.0000")})【申请人:{item.CreateUser}  申请时间:{item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss")}】";
                    subItem.ExcelRemaksDescription = excelRemaksDescription;
                    rowNumber++;
                }
            }
            decimal total_gz = DailyFeePaymentData.Where(s => s.transferParentId == stGZ.Id).Sum(d => d.SumPrice ?? 0M);
            decimal total_sz = DailyFeePaymentData.Where(s => s.transferParentId == stSZ.Id).Sum(d => d.SumPrice ?? 0M);
            var result = new tree_Fin_DailyFeePaymentResult() { gz = total_gz, sz = total_sz, dataList = DailyFeePaymentData };
            return result;
        }
        ///  
        /// 付款申请 (PageId=51)
        /// 团组,日付相关费用 选中状态变更
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPayRequestCheckedChange(PayRequestCheckedChangeDto dto)
        {
            #region 验证
            if (dto.Type < 1 || dto.Type > 2)
            {
                return Ok(JsonView(false, "请传入有效的Type参数! 1 checked 2 清除上次勾选"));
            }
            #endregion
            PaymentRequestCheckedView requestCheckedView = new PaymentRequestCheckedView();
            List groupIds = new List();
            List dailyPaymentIds = new List();
            List hotelIds = new List();
            #region 参数处理
            if (!string.IsNullOrEmpty(dto.GroupIds))
            {
                if (dto.GroupIds.Contains(","))
                {
                    groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
                }
                else
                {
                    groupIds.Add(int.Parse(dto.GroupIds));
                }
            }
            if (!string.IsNullOrEmpty(dto.HotelSubIds))
            {
                if (dto.HotelSubIds.Contains(","))
                {
                    hotelIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
                }
                else
                {
                    hotelIds.Add(int.Parse(dto.HotelSubIds));
                }
            }
            if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
            {
                if (dto.DailyPaymentIds.Contains(","))
                {
                    dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
                }
                else
                {
                    dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
                }
            }
            #endregion
            requestCheckedView.GroupIds = groupIds;
            requestCheckedView.HotelSubIds = hotelIds;
            requestCheckedView.DailyPaymentIds = dailyPaymentIds;
            if (dto.Type == 1)
            {
                TimeSpan ts = DateTime.Now.AddDays(180) - DateTime.Now; //设置redis 过期时间 半年(180)
                var status = await RedisRepository.RedisFactory.CreateRedisRepository().StringSetAsync("paymentRequestCheckedData", JsonConvert.SerializeObject(requestCheckedView), ts);
                if (status)
                {
                    return Ok(JsonView(true, "操作成功!"));
                }
            }
            else if (dto.Type == 2)
            {
                var status = await RedisRepository.RedisFactory.CreateRedisRepository().KeyDeleteAsync("paymentRequestCheckedData");
                if (status)
                {
                    return Ok(JsonView(true, "操作成功!"));
                }
            }
            return Ok(JsonView(false, "操作失败!"));
        }
        /// 
        /// 付款申请 (PageId=51)
        /// 团组,日付相关费用 汇率变更
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPayRequestRateChange(PayRequestRateChangeDto dto)
        {
            #region 验证
            DateTime beginDt, endDt;
            string format = "yyyy-MM-dd";
            if (!DateTime.TryParseExact(dto.beginDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out beginDt))
            {
                return Ok(JsonView(false, "开始日期格式不正确!正确格式:yyyy-MM-dd"));
            }
            if (!DateTime.TryParseExact(dto.endDt, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out endDt))
            {
                return Ok(JsonView(false, "结束日期格式不正确!正确格式:yyyy-MM-dd"));
            }
            if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
            if (dto.Id < 1) return Ok(JsonView(false, "请传入有效的Id参数!"));
            if (dto.Rate <= 0) return Ok(JsonView(false, "请传入有效的Rate参数!"));
            #endregion
            int hotelSubStatus = 0, status = 0;
            int diid = 0, cTable = 0, currId = 0;
            if (dto.HotelSubId > 0)
            {
                //更改酒店子表汇率
                hotelSubStatus = _sqlSugar.Updateable()
                                     .SetColumns(it => it.Rate == dto.Rate)
                                     .Where(it => it.Id == dto.HotelSubId)
                                     .ExecuteCommand();
                if (hotelSubStatus > 0)
                {
                    var hotelSubInfo = _sqlSugar.Queryable().Where(it => it.Id == dto.HotelSubId).First();
                    if (hotelSubInfo != null)
                    {
                        diid = hotelSubInfo.DiId;
                        currId = hotelSubInfo.Currency;
                    }
                    //付款申请汇率更改成功;更改团组汇率对应币种
                    string currCode = _sqlSugar.Queryable().Where(it => it.Id == currId).First()?.Name ?? "";
                    await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, 76, currCode, dto.Rate);
                }
            }
            if (dto.Id > 0)
            {
                var ccpInfo = _sqlSugar.Queryable().Where(it => it.Id == dto.Id).First();
                decimal cnyMoney = 0.00M;
                if (ccpInfo != null)
                {
                    cnyMoney = ccpInfo.PayMoney * dto.Rate;
                    diid = ccpInfo.DIId;
                    cTable = ccpInfo.CTable;
                    currId = ccpInfo.PaymentCurrency;
                }
                status = _sqlSugar.Updateable()
                                  .SetColumns(it => it.DayRate == dto.Rate)
                                  .SetColumns(it => it.RMBPrice == cnyMoney)
                                  .Where(it => it.Id == dto.Id)
                                  .ExecuteCommand();
                if (status > 0)
                {
                    //付款申请汇率更改成功;更改团组汇率对应币种
                    if (cTable != 76)
                    {
                        string currCode = _sqlSugar.Queryable().Where(it => it.Id == currId).First()?.Name ?? "";
                        await _teamRateRep.UpdateGroupRateByDiIdAndCTableId(diid, cTable, currCode, dto.Rate);
                    }
                }
            }
            if (hotelSubStatus > 0 || status > 0)
            {
                PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
                var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync("paymentRequestCheckedData");
                if (checkedStr != null)
                {
                    checkedView = JsonConvert.DeserializeObject(checkedStr.ToString());
                }
                tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(1, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
                tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(1, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
                decimal _gz = dailyResult.gz + groupResult.gz;
                decimal _sz = dailyResult.sz + groupResult.sz;
                return Ok(JsonView(true, "操作成功!", new { gz = dailyResult, sz = groupResult }));
            }
            return Ok(JsonView(false, "该项汇率修改失败!"));
        }
        /// 
        /// 付款申请 (PageId=51)
        /// 团组,日付相关费用 付款状态变更
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPayRequestPayChange(PayRequestPayChangeDto dto)
        {
            if (dto.UserId < 1) return Ok(JsonView(false, "请传入有效的UserId参数!"));
            //if (string.IsNullOrEmpty(dto.GroupIds))
            //{
            //    return Ok(JsonView(false, "请传入有效的GroupIds参数!"));
            //}
            //if (string.IsNullOrEmpty(dto.DailyPaymentIds))
            //{
            //    return Ok(JsonView(false, "请传入有效的DailyPaymentIds参数!"));
            //}
            List groupIds = new List();
            List dailyPaymentIds = new List();
            List hotelSubIds = new List();
            #region 参数处理
            if (!string.IsNullOrEmpty(dto.GroupIds))
            {
                if (dto.GroupIds.Contains(",")) groupIds = dto.GroupIds.Split(',').Select(int.Parse).ToList();
                else groupIds.Add(int.Parse(dto.GroupIds));
            }
            if (!string.IsNullOrEmpty(dto.HotelSubIds))
            {
                if (dto.HotelSubIds.Contains(",")) hotelSubIds = dto.HotelSubIds.Split(',').Select(int.Parse).ToList();
                else hotelSubIds.Add(int.Parse(dto.HotelSubIds));
                if (hotelSubIds.Count > 0)
                {
                    foreach (var item in hotelSubIds)
                    {
                        if (item < 1)
                        {
                            hotelSubIds.Remove(item);
                        }
                    }
                }
            }
            if (!string.IsNullOrEmpty(dto.DailyPaymentIds))
            {
                if (dto.DailyPaymentIds.Contains(",")) dailyPaymentIds = dto.DailyPaymentIds.Split(',').Select(int.Parse).ToList();
                else dailyPaymentIds.Add(int.Parse(dto.DailyPaymentIds));
            }
            #endregion
            bool changeStatus = false;
            _sqlSugar.BeginTran();
            if (groupIds.Count > 0)
            {
                var ccpInfos = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && groupIds.Contains(it.Id)).ToList();
                var otherTypeCcpIds = ccpInfos.Where(it => it.CTable != 76).Select(it => it.Id).ToList();
                var hotelTyprCcpIds = ccpInfos.Where(it => it.CTable == 76).Select(it => it.Id).ToList();
                int groupStatus = 0;
                if (otherTypeCcpIds.Count > 0) //其他费用类型 正常付款
                {
                    groupStatus = _sqlSugar.Updateable()
                                           .SetColumns(it => it.IsPay == 1)
                                           .Where(it => otherTypeCcpIds.Contains(it.Id))
                                           .ExecuteCommand();
                    changeStatus = true;
                }
                if (hotelTyprCcpIds.Count > 0) //酒店费用子项逻辑付款,酒店子项费用全部付完款,c表ispay=1
                {
                    if (hotelSubIds.Count > 0)
                    {
                        List hrPayIds = new List();
                        var hrIspayStatus = _sqlSugar.Updateable()
                                                   .SetColumns(it => it.IsPay == 1)
                                                   .Where(it => hotelSubIds.Contains(it.Id))
                                                   .ExecuteCommand();
                        changeStatus = true;
                        //酒店子项是否全部付完款
                        List hrIds = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && hotelSubIds.Contains(it.Id)).Select(it => it.HrId).Distinct().ToList();
                        if (hrIds.Count > 0)
                        {
                            var hotelSubFeeData = _sqlSugar.Queryable().Where(it => it.IsDel == 0 && hrIds.Contains(it.HrId)).ToList();
                            var hotelSubFeeGroupData = hotelSubFeeData.GroupBy(it => it.HrId).ToList();
                            foreach (var item in hotelSubFeeGroupData)
                            {
                                var allTotal = item.Where(it => it.Price > 0).ToList().Count;
                                var paymentTotal = item.Where(it => it.Price > 0 && it.IsPay == 1).ToList().Count;
                                if (allTotal == paymentTotal)
                                {
                                    hrPayIds.Add(item.Key);
                                }
                            }
                        }
                        if (hrPayIds.Count > 0)
                        {
                            //c表更改全部付款的酒店费用
                            groupStatus = _sqlSugar.Updateable()
                                               .SetColumns(it => it.IsPay == 1)
                                               .Where(it => it.CTable == 76 && hrPayIds.Contains(it.CId))
                                               .ExecuteCommand();
                        }
                    }
                }
            }
            //if (hotelSubIds.Count > 0)
            //{
            //    var groupStatus = _sqlSugar.Updateable()
            //                               .SetColumns(it => it.IsPay == 1)
            //                               .Where(it => hotelSubIds.Contains(it.Id))
            //                               .ExecuteCommand();
            //    if (groupStatus > 0)
            //    {
            //        changeStatus = true;
            //    }
            //}
            if (dailyPaymentIds.Count > 0)
            {
                var dailyPaymentStatus = _sqlSugar.Updateable()
                                           .SetColumns(it => it.IsPay == 1)
                                           .Where(it => dailyPaymentIds.Contains(it.Id))
                                           .ExecuteCommand();
                //修改提成关联表
                var ids = _sqlSugar.Queryable()
                    .LeftJoin((dfp, rf) => dfp.Id == rf.DayOverhead && rf.IsDel == 0)
                    .Where(dfp => dailyPaymentIds.Contains(dfp.Id) && dfp.IsDel == 0)
                    .Select((dfp, rf) => rf.ConfirmIdArr).ToList();
                var idsList = string.Join(',', ids).Split(',')
                            .Select(x =>
                            {
                                if (!string.IsNullOrWhiteSpace(x) && int.TryParse(x, out int intx))
                                {
                                    return intx;
                                }
                                return 0;
                            })
                            .Where(x => x != 0)
                            .Distinct()
                            .ToList();
                _sqlSugar.Updateable()
                    .SetColumns(it => it.IsSeed == 1)
                    .Where(it => idsList.Contains(it.Id) && it.IsSeed == 0)
                    .ExecuteCommand();
                if (dailyPaymentStatus > 0)
                {
                    changeStatus = true;
                }
            }
            if (changeStatus)
            {
                _sqlSugar.CommitTran();
                #region 应用推送
                try
                {
                    foreach (int ccpId in groupIds)
                    {
                        List tempList = new List() { ccpId.ToString() };
                        await AppNoticeLibrary.SendUserMsg_GroupStatus_PayResult(ccpId, tempList);
                    }
                    foreach (int dailyId in dailyPaymentIds)
                    {
                        List tempList = new List() { dailyId.ToString() };
                        await AppNoticeLibrary.DailyPayReminder_Pay_ToUser(dailyId, tempList);
                    }
                }
                catch (Exception ex)
                {
                }
                #endregion
                return Ok(JsonView(true, "操作成功!"));
            }
            _sqlSugar.RollbackTran();
            return Ok(JsonView(false, "付款状态修改失败!"));
        }
        /// 
        /// 付款申请 (PageId=51)
        /// File Download
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostPayRequestFileDownload(PayRequestFileDownloadDto dto)
        {
            Stopwatch stopwatch = Stopwatch.StartNew();
            #region 参数,权限 验证
            if (dto.PortType < 1)
            {
                return Ok(JsonView(false, "请传入有效的PortType参数!"));
            }
            if (dto.UserId < 1)
            {
                return Ok(JsonView(false, "请传入有效的UserId参数!"));
            }
            if (dto.PageId < 1)
            {
                dto.PageId = 51;
                return Ok(JsonView(false, "请传入有效的PageId参数!"));
            }
            if (dto.ConpanyId < 1 || dto.ConpanyId > 4)
            {
                return Ok(JsonView(false, "请传入有效的ConpanyId参数!"));
            }
            PageFunAuthViewBase pageFunAuthView = new PageFunAuthViewBase();
            #region 页面操作权限验证
            pageFunAuthView = await GeneralMethod.PostUserPageFuncDatas(dto.UserId, dto.PageId);
            if (pageFunAuthView.FilesDownloadAuth == 0) return Ok(JsonView(false, "您没有文件下载权限!"));
            #endregion
            #endregion
            try
            {
                PaymentRequestCheckedView checkedView = new PaymentRequestCheckedView();
                var checkedStr = await RedisRepository.RedisFactory.CreateRedisRepository().StringGetAsync("paymentRequestCheckedData");
                if (checkedStr != null)
                {
                    checkedView = JsonConvert.DeserializeObject(checkedStr.ToString());
                }
                if (checkedView == null)
                {
                    return Ok(JsonView(false, "没有选中的数据!"));
                }
                if (checkedView.GroupIds == null && checkedView.DailyPaymentIds == null)
                {
                    return Ok(JsonView(false, "没有选中的数据!"));
                }
                tree_Fin_DailyFeePaymentResult dailyResult = PayRequest_DailyByDateRange(2, checkedView.DailyPaymentIds, dto.beginDt, dto.endDt);
                tree_Group_DailyFeePaymentResult groupResult = PayRequest_GroupPaymentByDateRange(2, checkedView.GroupIds, checkedView.HotelSubIds, dto.beginDt, dto.endDt);
                if (dailyResult.childList == null)
                {
                    dailyResult.childList = new List();
                }
                List _GroupData = new List();
                List _DailyData = new List();
                //1	成都泛美商务有限公司
                if (dto.ConpanyId == 1)
                {
                    if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 1).ToList();
                    if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 1).ToList();
                }
                //2	四川泛美交流有限公司
                else if (dto.ConpanyId == 2)
                {
                    if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 2).ToList();
                    if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 2).ToList();
                }
                //3 成都纽茵教育科技有限公司
                else if (dto.ConpanyId == 3)
                {
                    if (groupResult.dataList != null && groupResult.dataList.Count > 0) _GroupData = groupResult.dataList.Where(it => it.CompanyId == 3).ToList();
                    if (dailyResult.dataList != null && dailyResult.dataList.Count > 0) _DailyData = dailyResult.dataList.Where(it => it.CompanyId == 3).ToList();
                }
                //4 成都鸿企中元科技有限公司
                else if (dto.ConpanyId == 4)
                {
                    return Ok(JsonView(false, "暂未开放该类型!"));
                }
                else
                {
                    return Ok(JsonView(false, "参数ConpanyId不可使用!"));
                }
                string _requestPaymentDt = DateTime.Now.ToString("yyyy-MM-dd"),//申请付款日期
                       _appliedAmount = "", //申请付款金额
                       _GZStr = "",    //公转价格描述
                       _SZStr = "";    //私转价格描述
                decimal groupGZAmout = 0.00M, groupSZAmout = 0.00M;
                decimal dailyGZAmout = 0.00M, dailySZAmout = 0.00M;
                string dailyGZStr = "", dailySZStr = "", groupGZStr = "", groupSZStr = "";
                #region 数据处理
                //团组费用相关
                foreach (var item in _GroupData)
                {
                    string groupGZSubStr = "";
                    string groupSZSubStr = "";
                    foreach (var subItem in item.ChildList)
                    {
                        if (subItem.TransferMark.Equals("公转"))
                        {
                            groupGZAmout += subItem.CNYSubTotalAmount;
                            groupGZSubStr += $"{subItem.RemaksDescription}\r\n";
                        }
                        else if (subItem.TransferMark.Equals("私转"))
                        {
                            groupSZAmout += subItem.CNYSubTotalAmount;
                            groupSZSubStr += $"{subItem.RemaksDescription}\r\n";
                        }
                        //groupGZSubStr += $"\t";
                    }
                    //if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"团组:{item.GroupName}\r\n{groupGZSubStr}\r\n";
                    //if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"团组:{item.GroupName}\r\n{groupSZSubStr}\r\n";
                    if (!string.IsNullOrEmpty(groupGZSubStr)) groupGZStr += $"{groupGZSubStr}\r\n";
                    if (!string.IsNullOrEmpty(groupSZSubStr)) groupSZStr += $"{groupSZSubStr}\r\n";
                }
                //日常费用相关
                foreach (var item in _DailyData)
                {
                    foreach (var subItem in item.childList)
                    {
                        if (item.transferParentId == 62) //公转
                        {
                            dailyGZAmout += item.SumPrice ?? 0.00M;
                            dailyGZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
                        }
                        else if (item.transferParentId == 63) //私转
                        {
                            dailySZAmout += item.SumPrice ?? 0.00M;
                            dailySZStr += $"{item.RowNumber}、【{item.CompanyName}】{subItem.ExcelRemaksDescription}\r\n";
                        }
                    }
                }
                _GZStr = $"【公转】团组相关费用(合计:CNY {groupGZAmout.ToString("#0.00")}):\r\n{groupGZStr}【公转】日常付款费用(合计:CNY {dailyGZAmout.ToString("#0.00")}):\r\n{dailyGZStr}";
                _SZStr = $"【私转】团组相关费用(合计:CNY {groupSZAmout.ToString("#0.00")}):\r\n{groupSZStr}【私转】日常付款费用(合计:CNY {dailySZAmout.ToString("#0.00")}):\r\n{dailySZStr}";
                _appliedAmount = $"公转:CNY {(groupGZAmout + dailyGZAmout).ToString("#0.00")}\r\n私转:CNY {(groupSZAmout + dailySZAmout).ToString("#0.00")}";
                #endregion
                WorkbookDesigner designer = new WorkbookDesigner();
                designer.Workbook = new Workbook(AppSettingsHelper.Get("ExcelBasePath") + "Template/付款申请书.xls");
                designer.SetDataSource("Date", _requestPaymentDt);
                designer.SetDataSource("Price", _appliedAmount);
                designer.SetDataSource("Content", _GZStr);
                designer.SetDataSource("Content1", _SZStr);
                //根据数据源处理生成报表内容
                designer.Process();
                string fileName = ("PayRequest/付款申请(" + dto.beginDt + "~" + dto.endDt + ").xlsx");
                designer.Workbook.Save(AppSettingsHelper.Get("ExcelBasePath") + fileName);
                string rst = AppSettingsHelper.Get("ExcelBaseUrl") + AppSettingsHelper.Get("ExcelFtpPath") + fileName;
                stopwatch.Stop();
                return Ok(JsonView(true, $"操作成功!{stopwatch.ElapsedMilliseconds / 1000}s", new { url = rst }));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        #endregion
        #region 超支费用
        /// 
        /// 超支费用
        /// 1增、2改、3删
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupExtraCost_Operator(Fin_GroupExtraCostDto_OP dto)
        {
            #region 验证
            #endregion
            Fin_GroupExtraCost _entity = new Fin_GroupExtraCost();
            _entity.DiId = dto.diId;
            _entity.PriceName = dto.priceName;
            _entity.Price = dto.price;
            _entity.PriceCurrency = dto.currency;
            _entity.PriceType = dto.priceType;
            _entity.Coefficient = dto.coefficient;
            _entity.PriceDetailType = dto.priceDetailType;
            _entity.FilePath = dto.filePath;
            _entity.Remark = dto.remark;
            _entity.PriceCount = dto.PriceCount;
            _entity.Area = dto.Area;
            _entity.SupervisorConfirm = dto.SupervisorConfirm;
            _entity.ManagerConfirm = dto.ManagerConfirm;
            DateTime dt_PriceDt;
            bool b_PriceDt = DateTime.TryParse(dto.PriceDt, out dt_PriceDt);
            if (b_PriceDt)
            {
                _entity.PriceDt = dt_PriceDt;
            }
            else
            {
                _entity.PriceDt = DateTime.MinValue;
            }
            _entity.PriceSum = dto.price * dto.PriceCount;
            _daiRep.BeginTran();
            if (dto.editType == 1)
            {
                _entity.CreateUserId = dto.createUser;
                _entity.CreateTime = DateTime.Now;
                _entity.IsDel = 0;
                int returnId = await _daiRep.AddAsyncReturnId(_entity);
                if (returnId > 0)
                {
                    dto.Id = returnId;
                }
            }
            else if (dto.editType == 2)
            {
                bool res = await _daiRep.UpdateAsync(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
                {
                    PriceName = dto.priceName,
                    Price = dto.price,
                    PriceCurrency = dto.currency,
                    PriceType = dto.priceType,
                    PriceDetailType = dto.priceDetailType,
                    Coefficient = dto.coefficient,
                    FilePath = dto.filePath,
                    Remark = dto.remark,
                    PriceCount = dto.PriceCount,
                    PriceDt = _entity.PriceDt,
                    PriceSum = _entity.PriceSum,
                    Area = _entity.Area,
                });
                if (!res)
                {
                    _daiRep.RollbackTran();
                    return Ok(JsonView(false, "2操作失败!"));
                }
            }
            else if (dto.editType == 3)
            {
                string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                bool res = await _daiRep.UpdateAsync(s => s.Id == dto.Id, s => new Fin_GroupExtraCost
                {
                    IsDel = 1,
                    DeleteTime = delTime,
                    DeleteUserId = dto.createUser
                });
                if (!res)
                {
                    _daiRep.RollbackTran();
                    return Ok(JsonView(false, "3操作失败!"));
                }
            }
            else
            {
                _daiRep.RollbackTran();
                return Ok(JsonView(false, "未知的editType"));
            }
            if (!extraCost_editCreditCardPayment(dto))
            {
                return Ok(JsonView(false, "ccp操作失败"));
            }
            //同步修改收款账单
            _foreignReceivablesRepository.OverSpSeteceivables(new OverSpSeteceivablesDto
            {
                CreateUserId = dto.createUser,
                DiId = dto.diId,
            });
        _daiRep.CommitTran();
            return Ok(JsonView(true, "操作成功"));
        }
        private Result PostCurrencyByDiid_Sync(int diId, int CId, int currencyId)
        {
            if (diId == 0)
            {
                return new Result() { Code = -1, Msg = "请传入团组Id!" };
            }
            if (CId == 0)
            {
                return new Result() { Code = -1, Msg = "请传入类型Id!" };
            }
            if (currencyId == 0)
            {
                return new Result() { Code = -1, Msg = "请传入币种Id!" };
            }
            Grp_TeamRate _TeamRate = _sqlSugar.Queryable().First(a => a.DiId == diId && a.IsDel == 0 && a.CTable == CId);
            List currencyInfos = new List();
            CurrencyInfo CurrencyRate = new CurrencyInfo();
            try
            {
                if (_TeamRate != null)
                {
                    Sys_SetData _SetData = _sqlSugar.Queryable().First(a => a.IsDel == 0 && a.Id == currencyId);
                    if (_SetData != null)
                    {
                        currencyInfos = CommonFun.GetCurrencyChinaToList(_TeamRate.Remark);
                        CurrencyRate = currencyInfos.FirstOrDefault(a => a.CurrencyCode == _SetData.Name);
                        if (CurrencyRate != null)
                        {
                            return new Result() { Code = 0, Msg = "查询成功!", Data = CurrencyRate };
                        }
                        else
                        {
                            return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
                        }
                    }
                    else
                    {
                        return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
                    }
                }
                else
                {
                    return new Result() { Code = -1, Msg = "暂无团组汇率,请前往设置!", Data = CurrencyRate };
                }
            }
            catch (Exception)
            {
                return new Result() { Code = -1, Msg = "查询异常!", Data = CurrencyRate };
            }
        }
        private bool extraCost_editCreditCardPayment(Fin_GroupExtraCostDto_OP costDto)
        {
            //设置团组汇率
            decimal dcm_dayrate = 1M;
            decimal dcm_rmbPrice = costDto.price;
            int ispay = costDto.payType == 72 ? 1 : 0;
            if (costDto.costSign != 3)
            {
                //获取新汇率  int diId,int CId, int currencyId
                Result rate = this.PostCurrencyByDiid_Sync(costDto.diId, 1015, costDto.currency);
                if (rate.Code == 0)
                {
                    var rateInfo = (rate.Data as CurrencyInfo);
                    if (rateInfo is not null)
                    {
                        dcm_dayrate = rateInfo.Rate;
                        dcm_rmbPrice = rateInfo.Rate * dcm_rmbPrice;
                    }
                    else
                    {
                        dcm_dayrate = 1;
                    }
                }
            }
            Grp_CreditCardPayment ccp = _daiRep.Query(s => s.CId == costDto.Id && s.CTable == 1015).First();
            if (ccp == null)
            {
                ccp = new Grp_CreditCardPayment();
                ccp.PayDId = costDto.payType;// dto
                ccp.ConsumptionPatterns = "";
                ccp.ConsumptionDate = "";
                ccp.CTDId = costDto.payCardId;// dto
                ccp.BankNo = "";
                ccp.CardholderName = "";
                ccp.PayMoney = costDto.price;// dto
                ccp.PaymentCurrency = costDto.currency;// dto
                ccp.CompanyBankNo = "";
                ccp.OtherBankName = "";
                ccp.OtherSideNo = "";
                ccp.OtherSideName = "";
                ccp.Remark = "";
                ccp.CreateUserId = costDto.createUser;
                ccp.CreateTime = DateTime.Now;
                ccp.MFOperator = 0;
                ccp.MFOperatorDate = "";
                ccp.IsAuditDM = 0;
                ccp.AuditDMOperate = 0;
                ccp.AuditDMDate = "";
                ccp.IsAuditMF = 0;
                ccp.AuditMFOperate = 0;
                ccp.AuditMFDate = "";
                ccp.IsAuditGM = 0;
                ccp.AuditGMOperate = 0;
                ccp.AuditGMDate = "";
                ccp.IsPay = ispay; // upd
                ccp.DIId = costDto.diId;// dto
                ccp.CId = costDto.Id;// dto
                ccp.CTable = 1015; //超支费用指向id
                ccp.IsDel = 0;
                ccp.PayPercentage = 100M;
                ccp.PayThenMoney = 0M;
                ccp.PayPercentageOld = 100M;
                ccp.PayThenMoneyOld = 0M;
                ccp.UpdateDate = "";
                ccp.Payee = costDto.payee;// dto
                ccp.OrbitalPrivateTransfer = costDto.costSign;// dto
                ccp.ExceedBudget = 0;
                ccp.DayRate = dcm_dayrate; //upd
                ccp.RMBPrice = dcm_rmbPrice; //upd
                int ccpInsertId = _daiRep.AddReturnId(ccp);
                if (ccpInsertId > 0)
                {
                    return true;
                }
            }
            else
            {
                if (costDto.editType == 2)
                {
                    bool res = _daiRep.Update(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
                    {
                        PayDId = costDto.payType,
                        CTDId = costDto.payCardId,
                        PayMoney = costDto.price,
                        PaymentCurrency = costDto.currency,
                        IsPay = ispay,
                        Payee = costDto.payee,
                        OrbitalPrivateTransfer = costDto.costSign,
                        DayRate = dcm_dayrate,
                        RMBPrice = dcm_rmbPrice
                    });
                    return res;
                }
                else if (costDto.editType == 3)
                {
                    string delTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    bool res2 = _daiRep.Update(s => s.Id == ccp.Id, s => new Grp_CreditCardPayment
                    {
                        IsDel = 1,
                        DeleteTime = delTime,
                        DeleteUserId = costDto.createUser
                    });
                    return res2;
                }
            }
            return false;
        }
        /// 
        /// 超支费用
        /// 详情查询
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupExtraCost_Detail(Fin_GroupExtraCostDto_Detail dto)
        {
            if (dto.Id < 1)
            {
                return Ok(JsonView(false, "查询失败"));
            }
            string sql = string.Format(@" Select 
                                                f.Id,f.DiId,
												f.PriceName,f.Price,f.PriceCurrency,c.Payee,c.OrbitalPrivateTransfer,c.PayDId,f.area, 
												c.CTDId,f.PriceType,f.PriceDetailType,f.Coefficient,f.Remark,f.PriceCount,f.PriceDt													
                                                From Fin_GroupExtraCost f
                                                Inner Join Grp_CreditCardPayment c On f.Id = c.CId
                                                Left Join Sys_Users u On f.CreateUserId = u.Id
                                                Where f.IsDel=0 And c.CTable = 1015 
												And f.Id = {0} ", dto.Id);
            Fin_GroupExtraCostDetailView detailView = await _sqlSugar.SqlQueryable(sql).FirstAsync();
            if (detailView == null)
            {
                return Ok(JsonView(false, "查询失败"));
            }
            return Ok(JsonView(true, "查询成功", detailView));
        }
        /// 
        /// 超支费用
        /// 列表查询
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupExtraCost_Search(Fin_GroupExtraCostDto_Search dto)
        {
            string sqlWhere = string.Format(@" And f.DiId = {0} ", dto.diId);
            int startIndex = (dto.PageIndex - 1) * dto.PageSize + 1;
            int endIndex = startIndex + dto.PageSize - 1;
            string sql_data = string.Format(@"Select * From (	
                                                Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
												f.PriceName,f.PriceType,f.PriceDetailType,CAST(f.Price as varchar)+' '+s.[Name] as PriceStr,f.PriceCount,CAST(f.PriceSum as varchar)+' '+s.[Name] as PriceSumStr,
                                                f.CreateUserId,f.PriceDt,c.IsAuditGM,f.ManagerConfirm,f.SupervisorConfirm,
                                                CASE  ManagerConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'ManagerConfirmStr' , CASE  SupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END  as 'SupervisorConfirmStr'														
                                                From Fin_GroupExtraCost f
                                                Inner Join Grp_CreditCardPayment c On f.Id = c.CId
                                                Inner Join Sys_SetData s On f.PriceCurrency = s.Id
                                                Left Join Sys_Users u On f.CreateUserId = u.Id
                                                Where f.IsDel=0 And c.CTable = 1015 {0}
                                                ) temp Where RowNumber Between {1} and {2}", sqlWhere, startIndex, endIndex);
            string sql_count = string.Format(@"Select Count(1) as DataCount From (	
                                                Select row_number() over (order by f.Id Desc) as RowNumber,f.Id,f.DiId,
												f.PriceName,f.PriceType,f.Price,f.FilePath,f.CreateUserId,f.CreateTime,c.IsAuditGM,f.ManagerConfirm,f.SupervisorConfirm,
                                                CASE  ManagerConfirm WHEN 1 THEN '已确认' ELSE '未确认' END as 'ManagerConfirmStr' , CASE  SupervisorConfirm WHEN 1 THEN '已确认' ELSE '未确认' END  as 'SupervisorConfirmStr'
                                                From Fin_GroupExtraCost f
                                                Inner Join Grp_CreditCardPayment c On f.Id = c.CId
                                                Inner Join Sys_SetData s On f.PriceCurrency = s.Id
                                                Left Join Sys_Users u On f.CreateUserId = u.Id
                                                Where f.IsDel=0 And c.CTable = 1015 {0}
                                                ) temp ", sqlWhere);
            if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3) //web
            {
                //Fin_DailyFeePaymentPageCount
                var count = await _sqlSugar.SqlQueryable(sql_count).FirstAsync();
                List dataList = await _sqlSugar.SqlQueryable(sql_data).ToListAsync();
                Dictionary dic_setData = new Dictionary();
                Dictionary dic_user = new Dictionary();
                foreach (var item in dataList)
                {
                    DateTime dtTemp_PriceDt;
                    bool b_ct = DateTime.TryParse(item.PriceDt, out dtTemp_PriceDt);
                    if (b_ct)
                    {
                        item.PriceDt = dtTemp_PriceDt.ToString("yyyy-MM-dd");
                    }
                    //费用类型
                    if (dic_setData.ContainsKey(item.PriceType))
                    {
                        item.PriceTypeStr = dic_setData[item.PriceType];
                    }
                    else
                    {
                        Sys_SetData sd_priceTypeDetail = _daiRep.Query(s => s.Id == item.PriceType).First();
                        if (sd_priceTypeDetail != null)
                        {
                            string tempName = sd_priceTypeDetail.Name.Replace("n", "");
                            item.PriceTypeStr = tempName;
                            dic_setData.Add(item.PriceType, tempName);
                        }
                    }
                    if (item.PriceDetailType > 0)
                    {
                        if (dic_setData.ContainsKey(item.PriceDetailType))
                        {
                            item.PriceTypeStr = item.PriceTypeStr + " - " + dic_setData[item.PriceDetailType];
                        }
                        else
                        {
                            Sys_SetData sd_priceTypeDetail = _daiRep.Query(s => s.Id == item.PriceDetailType).First();
                            if (sd_priceTypeDetail != null)
                            {
                                string tempName = sd_priceTypeDetail.Name.Replace("n", "");
                                item.PriceTypeStr = item.PriceTypeStr + " - " + tempName;
                                dic_setData.Add(item.PriceDetailType, tempName);
                            }
                        }
                    }
                    //系统用户
                    if (dic_user.ContainsKey(item.CreateUserId))
                    {
                        item.CreateUserIdStr = dic_user[item.CreateUserId];
                    }
                    else
                    {
                        Sys_Users users = _daiRep.Query(s => s.Id == item.CreateUserId).First();
                        if (users != null)
                        {
                            item.CreateUserIdStr = users.CnName;
                            dic_user.Add(item.CreateUserId, users.CnName);
                        }
                    }
                    switch (item.IsAuditGM)
                    {
                        case 0: item.IsAuditGMStr = "未审核"; break;
                        case 1: item.IsAuditGMStr = "已通过"; break;
                        case 2: item.IsAuditGMStr = "未通过"; break;
                        default: item.IsAuditGMStr = "未知状态"; break;
                    }
                }
                var result = new ListViewBase
                {
                    CurrPageIndex = dto.PageIndex,
                    CurrPageSize = dto.PageSize,
                    DataCount = count.DataCount,
                    DataList = dataList
                };
                return Ok(JsonView(true, "查询成功", result));
            }
            return Ok(JsonView(false, "查询失败"));
        }
        /// 
        /// 超支费用
        /// 数据集合配置
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupExtraCost_ListDataInit(Fin_GroupExtraCostDto_DataListInit dto)
        {
            //支付方式
            List Payment = _sqlSugar.Queryable().Where(a => a.STid == 14 && a.IsDel == 0).ToList();
            List _Payment = _mapper.Map>(Payment);
            //信用卡类型
            List Card = _sqlSugar.Queryable().Where(a => a.STid == 15 && a.IsDel == 0).ToList();
            List _Card = _mapper.Map>(Card);
            //超支费用类型
            List PriceType = _sqlSugar.Queryable().Where(a => a.STid == 79 && a.IsDel == 0).ToList();
            List _PriceType = _mapper.Map>(PriceType);
            //超支费用详细类型
            List PriceDetailType = _sqlSugar.Queryable().Where(a => a.STid == 80 && a.IsDel == 0).ToList();
            PriceDetailType.ForEach(a => { a.Name = a.Name.Replace("n", ""); });
            List _PriceDetailType = _mapper.Map>(PriceDetailType);
            var data = new
            {
                Payment = _Payment,
                Card = _Card,
                PriceType = _PriceType,
                PriceDetailType = _PriceDetailType
            };
            return Ok(JsonView(true, "", data));
        }
        /// 
        /// 超支费用
        /// 导出团组超支费用Excel
        /// 
        /// 
        /// 
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task PostGroupExtraCost_OutputExcel(Fin_GroupExtraCostExcelDto dto)
        {
            string sqlGroup = string.Format(@" Select * From Grp_DelegationInfo WIth(Nolock) where Id = {0} ", dto.diId);
            Grp_DelegationInfo grp_DelegationInfo = await _sqlSugar.SqlQueryable(sqlGroup).FirstAsync();
            if (grp_DelegationInfo == null)
            {
                return Ok(JsonView(false, "导出失败,未查询到团组"));
            }
            Workbook workbook = new Workbook();
            Worksheet sheet = workbook.Worksheets[0];
            Cells cells = sheet.Cells;
            //sheet.Protect(Aspose.Cells.ProtectionType.All, "123123", "");//保护工作表
            //sheet.Protection.IsSelectingLockedCellsAllowed = true;//设置只能选择解锁单元格
            //sheet.Protection.IsFormattingColumnsAllowed = true;//设置可以调整列
            //sheet.Protection.IsFormattingRowsAllowed = true;//设置可以调整行
            #region 数据源
            string sqlData = string.Format(@" Select f.PriceType,REPLACE(s2.[Name],'超支费用','') as PriceTypeStr,'('+REPLACE(s3.[Name],'n','')+')' as PriceDetailTypeStr, PriceDt,PriceName,
Price,PriceCount,s.[Name] as Currency,PriceSum,f.Remark
From Fin_GroupExtraCost as f With(Nolock)
Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
Inner Join Sys_SetData as s With(Nolock) On f.PriceCurrency = s.Id
Inner Join Sys_SetData as s2 With(Nolock) On f.PriceType = s2.Id
Inner Join Sys_SetData as s3 With(Nolock) On f.PriceDetailType = s3.Id
Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
Order by PriceType ASC,PriceDt ASC ", dto.diId);
            string sqlDataCount = string.Format(@" Select f.PriceType,COUNT(f.PriceType) as DataCount
From Fin_GroupExtraCost as f With(Nolock)
Inner Join Grp_CreditCardPayment as c With(Nolock) On f.Id = c.CId
Where f.DiId = {0} And f.IsDel=0 And c.CTable=1015
Group by PriceType ", dto.diId);
            List dataList = await _sqlSugar.SqlQueryable(sqlData).ToListAsync();
            List countList = await _sqlSugar.SqlQueryable