using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Mall.Common;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.Product;
using Mall.Model.Extend.Finance;
using Mall.Repository;
using Mall.Repository.Finance;
using Mall.Repository.Product;
using Newtonsoft.Json;

namespace Mall.Module.Finance
{
    /// <summary>
    /// 财务处理层
    /// </summary>
    public class FinanceModule
    {
        /// <summary>
        /// 财务配置
        /// </summary>
        private readonly RB_Finance_ConfigurineRepository finance_ConfigurineRepository = new RB_Finance_ConfigurineRepository();
        /// <summary>
        /// 财务流程
        /// </summary>
        private readonly Rb_Workflow_TemplateRepository workflow_TemplateRepository = new Rb_Workflow_TemplateRepository();
        /// <summary>
        /// 费用类型
        /// </summary>
        private readonly RB_CosttypeRepository costtypeRepository = new RB_CosttypeRepository();
        /// <summary>
        /// 账户类型
        /// </summary>
        private readonly RB_AccountTypeRepository accountTypeRepository = new RB_AccountTypeRepository();
        /// <summary>
        /// 银行账户
        /// </summary>
        private readonly RB_BackAccountRepository backAccountRepository = new RB_BackAccountRepository();
        /// <summary>
        /// 币种
        /// </summary>
        private readonly RB_CurrencyRepository currencyRepository = new RB_CurrencyRepository();

        /// <summary>
        /// 财务生成记录
        /// </summary>
        private static RB_Finance_RecordRepository financeRecordRepository = new RB_Finance_RecordRepository();
        /// <summary>
        /// 财务生成记录详情
        /// </summary>
        private static RB_Finance_RecordDetailRepository financeRecordDetailRepository = new RB_Finance_RecordDetailRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Finance_Configurine_Extend> GetFinanceConfigurineList(RB_Finance_Configurine_Extend dmodel)
        {
            return finance_ConfigurineRepository.GetList(dmodel);
        }



        /// <summary>
        /// 获取财务配置
        /// </summary>
        /// <param name="type"></param>
        /// <param name="tenantId"></param>
        /// <param name="mallBaseId"></param>
        /// <returns></returns>
        public object GetFinanceConfigurationInfo(int type, int tenantId, int mallBaseId)
        {
            var fmodel = finance_ConfigurineRepository.GetList(new RB_Finance_Configurine_Extend() { Type = type, TenantId = tenantId, MallBaseId = mallBaseId }).FirstOrDefault();
            if (fmodel == null)
            {
                return new
                {
                    Status = 1,
                    Msg = "需新增"
                };
            }
            else
            {
                int TypeId = 0;
                if (fmodel.Type == 1)
                {
                    var backModel = backAccountRepository.GetAccountList(new RB_BackAccount_Extend() { BankType = fmodel.AccountType, ID = fmodel.AccountId ?? 0, RB_Group_Id = 2 }).FirstOrDefault();
                    TypeId = backModel?.TypeId ?? 0;
                }
                return new
                {
                    Status = 2,
                    FModel = new
                    {
                        fmodel.Id,
                        fmodel.IsPublic,
                        TypeId,
                        fmodel.AccountType,
                        fmodel.AccountId,
                        fmodel.RemitterName,
                        fmodel.CurrencyId,
                        fmodel.IncomeCostTypeId,
                        fmodel.FreightCostTypeId,
                        fmodel.RefundCostTypeId,
                        fmodel.CBCostTypeId,
                        fmodel.ExpensesCostTypeId,
                        fmodel.RemitCostTypeId,
                        fmodel.WorkFlowId,
                        fmodel.Type,
                        StartTime = fmodel.StartTime.HasValue ? fmodel.StartTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                        fmodel.IntervalDay
                    }
                };
            }
        }

        /// <summary>
        /// 新增  修改  财务配置
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public bool SetFinanceConfigurationInfo(RB_Finance_Configurine_Extend demodel)
        {
            var fmodel = finance_ConfigurineRepository.GetList(new RB_Finance_Configurine_Extend() { Type = demodel.Type, TenantId = demodel.TenantId, MallBaseId = demodel.MallBaseId }).FirstOrDefault();
            if (fmodel == null)
            {
                return finance_ConfigurineRepository.Insert(demodel) > 0;
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Finance_Configurine_Extend.IsPublic),demodel.IsPublic},
                    { nameof(RB_Finance_Configurine_Extend.AccountType),demodel.AccountType},
                    { nameof(RB_Finance_Configurine_Extend.AccountId),demodel.AccountId},
                    { nameof(RB_Finance_Configurine_Extend.RemitterName),demodel.RemitterName},
                    { nameof(RB_Finance_Configurine_Extend.CurrencyId),demodel.CurrencyId},
                    { nameof(RB_Finance_Configurine_Extend.IncomeCostTypeId),demodel.IncomeCostTypeId},
                    { nameof(RB_Finance_Configurine_Extend.FreightCostTypeId),demodel.FreightCostTypeId},
                    { nameof(RB_Finance_Configurine_Extend.RefundCostTypeId),demodel.RefundCostTypeId},
                    { nameof(RB_Finance_Configurine_Extend.CBCostTypeId),demodel.CBCostTypeId},
                    { nameof(RB_Finance_Configurine_Extend.ExpensesCostTypeId),demodel.ExpensesCostTypeId},
                    { nameof(RB_Finance_Configurine_Extend.RemitCostTypeId),demodel.RemitCostTypeId},
                    { nameof(RB_Finance_Configurine_Extend.WorkFlowId),demodel.WorkFlowId},
                    { nameof(RB_Finance_Configurine_Extend.StartTime),demodel.StartTime},
                    { nameof(RB_Finance_Configurine_Extend.IntervalDay),demodel.IntervalDay}
                };
                List<WhereHelper> whereHelpers = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName=nameof(RB_Finance_Configurine_Extend.Id),
                          FiledValue=fmodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                return finance_ConfigurineRepository.Update(keyValues, whereHelpers);
            }
        }

        /// <summary>
        /// 获取费用类型列表
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public object GetFinanceCostTypeList(int type)
        {
            var list = costtypeRepository.GetList(new RB_Costtype_Extend() { RB_Group_Id = 2, Type = (Common.Enum.Finance.WFTempLateClassEnum)type });
            return list.Select(x => new
            {
                Id = x.ID,
                x.Name
            });
        }

        /// <summary>
        /// 获取币种
        /// </summary>
        /// <returns></returns>
        public object GetFinanceCurrencyList()
        {
            var list = currencyRepository.GetList(new Model.Entity.Finance.RB_Currency() { RB_Group_Id = 2 });
            return list.Select(x => new
            {
                Id = x.ID,
                x.Name
            });
        }

        /// <summary>
        /// 获取流程列表
        /// </summary>
        /// <returns></returns>
        public object GetFinanceWorkFlowTemplateList(int TempLateClass)
        {
            var list = workflow_TemplateRepository.GetList(new Rb_Workflow_Template_Extend() { RB_GroupId = 2, Status = 1, TempLateClass = (Common.Enum.Finance.WFTempLateClassEnum)TempLateClass, TemplateSorce = 1 });
            return list.Select(x => new
            {
                x.Id,
                x.Name
            });
        }

        /// <summary>
        /// 获取账户类型
        /// </summary>
        /// <returns></returns>
        public object GetAccountTypeList()
        {
            var list = accountTypeRepository.GetList(new RB_AccountType_Extend() { RB_Group_Id = 2 });
            return list.Select(x => new
            {
                Id = x.ID,
                x.IsPublic,
                x.Name
            });
        }

        /// <summary>
        /// 获取账户列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<RB_BackAccount_Extend> GetAccountList(RB_BackAccount_Extend model)
        {
            var list = backAccountRepository.GetAccountList(model);
            return list;
        }



        #region 财务记录
        public bool SetFinanceRecord(RB_Finance_Record_Extend model)
        {
            bool flag = false;
            var trans = financeRecordRepository.DbTransaction;
            try
            {
                int recordId = 0;
                if (model.ID == 0)
                {
                    recordId = financeRecordRepository.Insert(model, trans);
                    flag = recordId > 0;
                    if (model.RecordDetailList != null && model.RecordDetailList.Any())
                    {
                        model.RecordDetailList.ForEach(x => x.RecordId = recordId);
                        model.RecordDetailList.ForEach(x => x.FinanceId = model.FinanceId);
                        financeRecordDetailRepository.InsertBatch(model.RecordDetailList, trans);
                    }
                    if (flag)//更新订单商品的财务单据
                    {
                        foreach (var item in model.RecordDetailList)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>()
                            {
                                { nameof(RB_Goods_OrderDetail.CostFinanceId),model.FinanceId}
                            };
                            List<WhereHelper> whereHelpers = new List<WhereHelper>() { new WhereHelper()
                                {
                                    FiledName=nameof(RB_Finance_Configurine_Extend.Id),
                                    FiledValue=item.OrderDetailId,
                                    OperatorEnum=OperatorEnum.Equal
                                }
                            };
                            goods_OrderDetailRepository.Update(keyValues, whereHelpers, trans);
                        }
                    }
                }
                financeRecordRepository.DBSession.Commit();
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "SetFinanceRecord");
                financeRecordRepository.DBSession.Rollback("SetFinanceRecord");
                return false;
            }
            return flag;

        }
        #endregion

    }
}
