using Mall.Common.Plugin;
using Mall.Model.Entity.Finance;
using Mall.Model.Entity.User;
using Mall.Model.Extend.User;
using Mall.Repository;
using Mall.Repository.Finance;
using Mall.Repository.User;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Mall.Module.User
{
    public class SupplierModule
    {
        private readonly RB_SupplierRepository supplierRepository = new RB_SupplierRepository();
        private readonly RB_SupplierCommissionRepository supplierCommissionRepository = new RB_SupplierCommissionRepository();
        private readonly RB_ClientBankAccountRepository clientBankAccountRepository = new RB_ClientBankAccountRepository();

        /// <summary>
        /// 分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="dmodel">查询条件</param>
        /// <returns></returns>
        public List<RB_Supplier_Extend> GetPageList(int pageIndex, int pageSize, out long rowCount, RB_Supplier_Extend dmodel)
        {
            var list = supplierRepository.GetPageList(pageIndex, pageSize, out rowCount, dmodel);
            if (list != null && list.Any())
            {
                string ids = string.Join(",", list.Select(x => x.BankAccountId));
                var backList = clientBankAccountRepository.GetList(new RB_ClientBankAccount(), "", ids);
                 ids = string.Join(",", list.Select(x => x.ID));
                var supplierCommissionList = supplierCommissionRepository.GetListBySupplierIds(ids);
                foreach (var item in list)
                {
                    item.ClientBankAccount = new RB_ClientBankAccount();
                    item.ClientBankAccount = backList.Where(x => x.ID == item.BankAccountId).FirstOrDefault();

                    item.SupplierCommissionList = new List<RB_SupplierCommission>();
                    item.SupplierCommissionList = supplierCommissionList.Where(x => x.SupplierId == item.ID).ToList();
                }
            }
            return list;
        }


        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="dmodel"></param>
        /// <returns></returns>
        public List<RB_Supplier_Extend> GetList(RB_Supplier_Extend dmodel)
        {
            var list = supplierRepository.GetList(dmodel);
            if (list != null && list.Any())
            {
                string ids = string.Join(",", list.Select(x => x.BankAccountId));
                var backList = clientBankAccountRepository.GetList(new RB_ClientBankAccount(), "", ids);
                ids = string.Join(",", list.Select(x => x.ID));
                var supplierCommissionList = supplierCommissionRepository.GetListBySupplierIds(ids);
                foreach (var item in list)
                {
                    item.ClientBankAccount = new RB_ClientBankAccount();
                    item.ClientBankAccount = backList.Where(x => x.ID == item.BankAccountId).FirstOrDefault();
                    item.SupplierCommissionList = new List<RB_SupplierCommission>();
                    item.SupplierCommissionList = supplierCommissionList.Where(x => x.SupplierId == item.ID).ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 添加修改供应商
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddOrUpdateSupplier(RB_Supplier_Extend model)
        {
            bool flag = false;
            try
            {

                if (model.ID > 0)
                {
                    if (model.ClientBankAccount.ID == 0)
                    {
                        model.Status = (int)Common.Enum.DateStateEnum.Normal;
                        model.ClientBankAccount.AccountHolder = model.ClientBankAccount.AccountAlias;
                        var id = clientBankAccountRepository.Insert(model.ClientBankAccount);
                        model.BankAccountId = id;
                        flag = id > 0;
                    }
                    else
                    {
                        IDictionary<string, object> fileds = new Dictionary<string, object>()
                        {
                            { nameof(RB_ClientBankAccount.Type),(int)model.ClientBankAccount.Type},
                            { nameof(RB_ClientBankAccount.ObjID),model.ClientBankAccount.ObjID},
                            { nameof(RB_ClientBankAccount.BankId),model.ClientBankAccount.BankId},
                            { nameof(RB_ClientBankAccount.OpenBankName),model.ClientBankAccount.OpenBankName},
                            { nameof(RB_ClientBankAccount.AccountHolder),model.ClientBankAccount.AccountAlias},
                            { nameof(RB_ClientBankAccount.CardNum),model.ClientBankAccount.CardNum},
                            { nameof(RB_ClientBankAccount.AccountAlias),model.ClientBankAccount.AccountAlias},
                            { nameof(RB_ClientBankAccount.Status),model.ClientBankAccount.Status},
                            { nameof(RB_ClientBankAccount.AccountClassify),model.ClientBankAccount.AccountClassify}
                        };
                        IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_ClientBankAccount.ID),FiledValue=model.BankAccountId,OperatorEnum=OperatorEnum.Equal}
                        };
                        flag = clientBankAccountRepository.Update(fileds, whereHelpers);
                    }
                    if (flag)
                    {
                        IDictionary<string, object> filedsSupplier = new Dictionary<string, object>()
                        {
                            { nameof(RB_Supplier.BankAccountId),model.BankAccountId},
                            { nameof(RB_Supplier.Name),model.Name},
                            { nameof(RB_Supplier.Mobile),model.Mobile},
                            { nameof(RB_Supplier.Address),model.Address},
                            { nameof(RB_Supplier.UpdateDate),model.UpdateDate},
                             { nameof(RB_Supplier.Introducer),model.Introducer}
                        };
                        IList<WhereHelper> whereHelpersSupplier = new List<WhereHelper>()
                        {
                            new WhereHelper (){ FiledName=nameof(RB_Supplier.ID),FiledValue=model.ID,OperatorEnum=OperatorEnum.Equal}
                        };
                        flag = supplierRepository.Update(filedsSupplier, whereHelpersSupplier);
                    }

                    var supplierCommissionList = supplierCommissionRepository.GetSupplierCommissionList(new RB_SupplierCommission { SupplierId = model.ID });
                    if (model.SupplierCommissionList != null && model.SupplierCommissionList.Any())
                    {
                        foreach (var item in model.SupplierCommissionList)
                        {
                            var commissionModel = supplierCommissionList.Where(x => x.CommissionType == item.CommissionType).FirstOrDefault();
                            if (commissionModel != null)
                            {
                                commissionModel.CommissionRate = item.CommissionRate;

                                supplierCommissionRepository.Update(commissionModel);
                            }
                            else
                            {
                                item.CreateDate = System.DateTime.Now;
                                item.UpdateDate = System.DateTime.Now;
                                item.MallBaseId = model.MallBaseId;
                                item.TenantId = model.TenantId;
                                item.SupplierId = model.ID;
                                item.Status = model.Status;
                                supplierCommissionRepository.Insert(item);
                            }
                        }
                    }
                    else
                    {
                        if (supplierCommissionList != null && supplierCommissionList.Any())
                        {
                            foreach (var item in supplierCommissionList)
                            {
                                IDictionary<string, object> filedsSupplierCommission = new Dictionary<string, object>()
                                {
                                    { nameof(RB_SupplierCommission.Status),1},
                                    { nameof(RB_SupplierCommission.UpdateDate),model.UpdateDate}
                                };
                                IList<WhereHelper> whereHelpersSupplierCommission = new List<WhereHelper>()
                                {
                                    new WhereHelper (){ FiledName=nameof(RB_SupplierCommission.ID),FiledValue=item.ID,OperatorEnum=OperatorEnum.Equal}
                                };
                                supplierCommissionRepository.Update(filedsSupplierCommission, whereHelpersSupplierCommission);
                            }
                        }
                    }
                }
                else
                {
                    model.Status = (int)Common.Enum.DateStateEnum.Normal;
                    model.ClientBankAccount.AccountHolder = model.ClientBankAccount.AccountAlias;
                    var id = clientBankAccountRepository.Insert(model.ClientBankAccount);
                    if (id > 0)
                    {
                        model.BankAccountId = id;
                        int supplierId = supplierRepository.Insert(model);
                        if (model.SupplierCommissionList != null && model.SupplierCommissionList.Any())
                        {
                            model.SupplierCommissionList.ForEach(x => x.CreateDate = model.CreateDate);
                            model.SupplierCommissionList.ForEach(x => x.UpdateDate = model.UpdateDate);
                            model.SupplierCommissionList.ForEach(x => x.MallBaseId = model.MallBaseId);
                            model.SupplierCommissionList.ForEach(x => x.TenantId = model.TenantId);
                            model.SupplierCommissionList.ForEach(x => x.SupplierId = supplierId);
                            model.SupplierCommissionList.ForEach(x => x.Status = 0);
                            supplierCommissionRepository.InsertBatch(model.SupplierCommissionList);
                        }
                        flag = supplierId > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "AddOrUpdateSupplier");
                return false;
            }
            return flag;
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="EmployeeId"></param>
        /// <returns></returns>
        public bool RemoveSupplier(int ID, int BankAccountId)
        {
            bool flag;
            try
            {
                IDictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    { nameof(RB_ClientBankAccount.Status),(int) Common.Enum.DateStateEnum.Delete}
                };
                IList<WhereHelper> whereHelpers = new List<WhereHelper>()
                {
                    new WhereHelper (){ FiledName=nameof(RB_ClientBankAccount.ID),FiledValue=BankAccountId,OperatorEnum=OperatorEnum.Equal}
                };
                flag = clientBankAccountRepository.Update(fileds, whereHelpers);

                if (flag)
                {
                    IDictionary<string, object> filedsSupplier = new Dictionary<string, object>()
                {
                    { nameof(RB_Supplier.Status),(int) Common.Enum.DateStateEnum.Delete}
                };
                    IList<WhereHelper> whereHelpersSupplier = new List<WhereHelper>()
                {
                    new WhereHelper (){ FiledName=nameof(RB_Supplier.ID),FiledValue=ID,OperatorEnum=OperatorEnum.Equal}
                };
                    flag = supplierRepository.Update(filedsSupplier, whereHelpersSupplier);

                    IDictionary<string, object> filedsSupplierCommission = new Dictionary<string, object>()
                {
                    { nameof(RB_SupplierCommission.Status),(int) Common.Enum.DateStateEnum.Delete}
                };
                    IList<WhereHelper> whereHelpersSupplierCommission = new List<WhereHelper>()
                {
                    new WhereHelper (){ FiledName=nameof(RB_SupplierCommission.SupplierId),FiledValue=ID,OperatorEnum=OperatorEnum.Equal}
                };
                    supplierCommissionRepository.Update(filedsSupplierCommission, whereHelpersSupplierCommission);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, "RemoveSupplier");
                return false;
            }
            return flag;
        }


        /// <summary>
        /// 验证重复
        /// </summary>
        /// <param name="ID"></param>
        /// <param name="Name"></param>
        /// <param name="RB_Group_Id"></param>
        /// <param name="RB_Branch_Id"></param>
        /// <returns></returns>
        public bool ExistsClientAccount(int ID, string Num, int RB_Group_Id, int RB_Branch_Id)
        {
            IList<WhereHelper> where = new List<WhereHelper>()
            {
                new WhereHelper() { FiledName = nameof(RB_ClientBankAccount.Status), FiledValue = (int)Common.Enum.DateStateEnum.Normal, OperatorEnum = OperatorEnum.Equal },
                new WhereHelper() { FiledName = nameof(RB_ClientBankAccount.CardNum), FiledValue = Num.Trim(), OperatorEnum = OperatorEnum.Equal  },
                new WhereHelper() { FiledName = nameof(RB_ClientBankAccount.RB_Group_Id), FiledValue = RB_Group_Id, OperatorEnum = OperatorEnum.Equal  },
                new WhereHelper() { FiledName = nameof(RB_ClientBankAccount.RB_Branch_Id), FiledValue = RB_Branch_Id, OperatorEnum = OperatorEnum.Equal },
            };
            if (ID > 0)
            {
                where.Add(new WhereHelper() { FiledName = nameof(RB_ClientBankAccount.ID), FiledValue = ID.ToString(), OperatorEnum = OperatorEnum.NotEqual });
            }
            return clientBankAccountRepository.Exists(where);
        }



        #region 获取财务单据付款人信息
        /// <summary>
        /// 根据查询条件获取客户账户列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public List<RB_ClientBankAccount> GetClientBankAccountList(Model.Extend.Finance.RB_ClientBankAccount_Extend model)
        {
            return clientBankAccountRepository.GetList(model);
        }
            #endregion
        }
}
