using Microsoft.AspNetCore.Components.Web;
using MySqlX.XDevAPI.Relational;
using OASystem.Domain.Dtos.Financial;
using OASystem.Domain.Dtos.Groups;
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;

namespace OASystem.API.OAMethodLib
{
    /// <summary>
    /// 团组提成
    /// 雷怡 2023-08-14 16:04
    /// </summary>
    public static class GroupCommission
    {
        //团组信息
        private readonly static DelegationInfoRepository _dirRep = AutofacIocManager.Instance.GetService<DelegationInfoRepository>(); 
        //团组实付金额
        private readonly static CreditCardPaymentRepository _ccpRep = AutofacIocManager.Instance.GetService<CreditCardPaymentRepository>();
        //团组应收款项
        private readonly static ForeignReceivablesRepository _frRep = AutofacIocManager.Instance.GetService<ForeignReceivablesRepository>();
        //团组已收款项
        private readonly static ProceedsReceivedRepository _prRep = AutofacIocManager.Instance.GetService<ProceedsReceivedRepository>();
        //团组其他款项
        private readonly static OtherPriceRepository _opRep = AutofacIocManager.Instance.GetService<OtherPriceRepository>(); 

        /// <summary>
        /// 获取团组提成 Page List
        /// </summary>
        public static async Task<Result> GetCommissionPageList(GroupCommissionDto dto)
        {
            Result result = new Result() { Code = -1 };

            var groupResult = await _dirRep.GetGroupPageList(dto);
            if (groupResult.Code != 0)
            {
                result.Code = groupResult.Code;
                result.Msg = groupResult.Msg;
                return result;
            }
            if (groupResult.Data == null) { }

           // ListViewBase<DelegationPageListView> groupData = JsonConvert.DeserializeObject<ListViewBase<DelegationPageListView>>(groupResult.Data);
            result.Data = groupResult.Data;
            List<int> diids = new List<int>();
            foreach (var item in result.Data.DataList)
            {
                diids.Add(item.Id);
            }
            await GetCommissionByDiids(diids.ToArray());
            return result;

        }

        /// <summary>
        /// 根据团组Id计算 团组利润
        /// </summary>
        /// <param name="DiId">团组Id</param>
        public static async Task<Fin_GroupProfitInfoView> GetCommissionByDiid(int DiId)
        {

            int[] ints = new int[DiId];

            decimal sumFr = 0.00M,  //团组 应收款项
                    sumPr = 0.00M,  //团组 已收款项
                    refund = 0.00M, //团组 退款和其他费用
                    cost = 0.00M;   //团组 成本费用
            if (DiId == 0) return new Fin_GroupProfitInfoView();

            #region 计算各项费用

            //应收款项
            Result frData = await _frRep.GetGroupReceivablesByDiid(DiId);
            if (frData.Code == 0 && frData.Data != null)
            {
                foreach (var item in frData.Data)
                {
                    sumFr += item.Price;
                }
            }

            //已收款项
            Result prData = await _prRep.GetGroupReceivedByDiid(DiId);
            if (frData.Code == 0 && frData.Data != null)
            {
                foreach (var item in prData.Data)
                {
                    sumPr += item.Price;
                }
            }

            //收款退还费用
            Result ccpData = await _ccpRep.GetGroupRefundByDiid(DiId, true);
            if (ccpData.Code == 0 && ccpData.Data != null)
            {
                foreach (var item in ccpData.Data)
                {
                    refund += item.Price;
                }
            }

            //实际的团组类型已收金额需除去退款 
            sumPr = sumPr - refund;

            //团组与非团组产生的成本费用数据
            Result _ccpData =  await _ccpRep.GetGroupPaymentInfoByDiid(DiId, true);
            if (_ccpData.Code == 0 && _ccpData.Data != null)
            {
                foreach (Grp_Fin_CreditCardPaymentView item in _ccpData.Data)
                {
                    if (item.PayThenMoney != 0M)
                        cost += item.PayThenMoney * item.DayRate;
                    else
                        cost += item.PayMoney * (item.PayPercentage * 0.01M) * item.DayRate;

                }

                //实际的团组成本需除去退款 
                cost -= refund;
            }
            #endregion

            //团组净利润=已收金额-成本
            decimal groupProfit = sumPr - cost;

            //团组尾款=应收款项-已收款项
            decimal groupRatainage = sumPr - sumPr;

            return new Fin_GroupProfitInfoView() { ReceivableFund = sumFr, ReceivedFund = sumPr,Refund = refund,Cost=cost,RetainedProfits=groupProfit,FinalPayment = groupRatainage };
        }

        /// <summary>
        /// 根据团组 Ids 计算 团组利润
        /// </summary>
        /// <param name="DiIds"></param>
        /// <returns></returns>
        public static async Task<List<Fin_GroupProfitInfoView>> GetCommissionByDiids(int[] DiIds)
        {
           
            if (DiIds.Length <= 0) return new  List<Fin_GroupProfitInfoView>();

            List<Fin_GroupProfitInfoView> fin_GroupProfitInfoViews = new List<Fin_GroupProfitInfoView>();

            #region string
            //string _diidsStr = string.Empty;
            //#region 处理Diid
            //StringBuilder diidSb = new StringBuilder();
            //for (int i = 0; i < DiIds.Length; i++)
            //{
            //    if (i == DiIds.Length - 1)
            //    {
            //        diidSb.Append(DiIds[i]);
            //    }
            //    else
            //    {
            //        diidSb.Append(DiIds[i]).Append(",");
            //    }
            //}
            //_diidsStr = diidSb.ToString().Trim();
            //#endregion
            #endregion



            #region 计算各项费用

            //应收款项
            Result frData = await _frRep.GetGroupReceivablesByDiids(DiIds);

            //已收款项
            Result prData = await _prRep.GetGroupReceivedByDiids(DiIds);

            //收款退还费用
            Result ccpData = await _ccpRep.GetGroupRefundByDiids(DiIds, true);

            //团组与非团组产生的成本费用数据
            Result ccpData1 = await _ccpRep.GetGroupPaymentInfoByDiids(DiIds, true);


            foreach (int item in DiIds)
            {
                decimal sumFr = 0.00M,  //团组 应收款项
                   sumPr = 0.00M,        //团组 已收款项
                   refund = 0.00M,       //团组 退款和其他费用
                   cost = 0.00M;         //团组 成本费用

                //团组 应收款项
                if (frData.Code == 0 && frData.Data != null)
                {
                    List<Fin_ForeignReceivables> _frData = JsonConvert.DeserializeObject<List<Fin_ForeignReceivables>>
                        (JsonConvert.SerializeObject(frData.Data));
                    _frData = _frData.Where(fr => item == fr.Diid).ToList();
                    foreach (Fin_ForeignReceivables itemFr in _frData)
                    {
                        sumPr += itemFr.Price;
                    }
                }

                //团组 已收款项
                if (prData.Code == 0 && prData.Data != null)
                {
                    List<Fin_ProceedsReceived> _prData = JsonConvert.DeserializeObject<List<Fin_ProceedsReceived>>
                        (JsonConvert.SerializeObject(prData.Data));
                    _prData = _prData.Where(pr => item == pr.Diid).ToList();
                    foreach (var itemPr in _prData)
                    {
                        sumFr += itemPr.Price;
                    }
                }

                //团组 退款和其他费用
                if (ccpData.Code == 0 && ccpData.Data != null)
                {
                    List<GroupRefundView> _ccpData = JsonConvert.DeserializeObject<List<GroupRefundView>>
                        (JsonConvert.SerializeObject(ccpData.Data));
                    _ccpData = _ccpData.Where(ccp => item == ccp.DIId).ToList();
                    foreach (var itemCcp in _ccpData)
                    {
                        refund += itemCcp.Price;
                    }
                }

                //实际的团组类型已收金额需除去退款 
                sumPr = sumPr - refund;


                if (ccpData1.Code == 0 && ccpData1.Data != null)
                {
                    List<Grp_CreditCardPayment> _ccpData1 = JsonConvert.DeserializeObject<List<Grp_CreditCardPayment>>
                        (JsonConvert.SerializeObject(ccpData1.Data));
                    _ccpData1 = _ccpData1.Where(ccp => item == ccp.DIId).ToList();
                    foreach (Grp_CreditCardPayment itemCcp in _ccpData1)
                    {
                        if (itemCcp.PayThenMoney != 0M)
                            cost += itemCcp.PayThenMoney * itemCcp.DayRate;
                        else
                            cost += itemCcp.PayMoney * (itemCcp.PayPercentage * 0.01M) * itemCcp.DayRate;

                    }

                    //实际的团组成本需除去退款 
                    cost -= refund;
                }
                #endregion

                decimal groupProfit = 0.00M,    //团组净利润=已收金额-成本
                    groupRatainage = 0.00M;     //团组尾款=应收款项-已收款项


                groupProfit = sumPr - cost;
                groupRatainage = sumPr - sumPr;

                fin_GroupProfitInfoViews.Add(new Fin_GroupProfitInfoView() { Diid = item, ReceivableFund = sumFr, ReceivedFund = sumPr, Refund = refund, Cost = cost, RetainedProfits = groupProfit, FinalPayment = groupRatainage });
            }


            
            return fin_GroupProfitInfoViews;
        }
    }
}
