using Edu.Cache.User;
using Edu.Common.Enum;
using Edu.Common.Enum.Customer;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Customer;
using Edu.Repository.Customer;
using Edu.Repository.Log;
using Edu.Repository.System;
using Edu.Repository.User;
using System;
using System.Collections.Generic;
using System.Linq;
using VT.FW.DB;

namespace Edu.Module.Customer
{
    /// <summary>
    /// 同业客户管理处理类
    /// </summary>
    public class CustomerModule
    {
        /// <summary>
        /// 同业客户管理仓储层对象
        /// </summary>
        private readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();
        /// <summary>
        /// 同业佣金/幸福存折
        /// </summary>
        private readonly RB_Customer_BalanceDetailRepository customer_BalanceDetailRepository = new RB_Customer_BalanceDetailRepository();
        /// <summary>
        /// 同业提现
        /// </summary>
        private readonly RB_Customer_RemitRepository customer_RemitRepository = new RB_Customer_RemitRepository();
        /// <summary>
        /// 学生
        /// </summary>
        private readonly RB_StudentRepository studentRepository = new RB_StudentRepository();
        /// <summary>
        /// 用户信息修改日志仓储层对象
        /// </summary>
        private readonly RB_User_ChangeLogRepository changeLogRepository = new RB_User_ChangeLogRepository();

        /// <summary>
        /// 客户阶段仓储层对象
        /// </summary>
        private readonly RB_StageRepository stageRepository = new RB_StageRepository();

        /// <summary>
        /// 企业信息仓储层对象
        /// </summary>
        private readonly RB_EnterpriseRepository enterpriseRepository = new RB_EnterpriseRepository();


        /// <summary>
        /// 获取客户分页列表..
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Customer_Extend> GetCustomerPageModule(int pageIndex, int pageSize, out long rowsCount, RB_Customer_Extend query)
        {
            var list = customerRepository.GetCustomerPageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }

        /// <summary>
        /// 新增修改客户资料
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetCustomerModule(RB_Customer_Extend model)
        {
            bool flag;
            if (model.CustomerId > 0)
            {
                var oldModel = customerRepository.GetEntity(model.CustomerId);
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Customer_Extend.CustomerName),model.CustomerName },
                    {nameof(RB_Customer_Extend.ContactNumber),model.ContactNumber },
                    {nameof(RB_Customer_Extend.Fax),model.Fax },
                    {nameof(RB_Customer_Extend.QQ),model.QQ },
                    {nameof(RB_Customer_Extend.Email),model.Email },
                    {nameof(RB_Customer_Extend.Address),model.Address },
                    {nameof(RB_Customer_Extend.Sex),model.Sex },
                    {nameof(RB_Customer_Extend.CustomerSourceType),model.CustomerSourceType },
                    {nameof(RB_Customer_Extend.CustomerSource),model.CustomerSource },
                    {nameof(RB_Customer_Extend.CountryId),model.CountryId },
                    {nameof(RB_Customer_Extend.ProvinceId),model.ProvinceId },
                    {nameof(RB_Customer_Extend.CityId),model.CityId },
                    {nameof(RB_Customer_Extend.DistrictId),model.DistrictId },
                    {nameof(RB_Customer_Extend.LngLat),model.LngLat },
                    {nameof(RB_Customer_Extend.Account),model.Account },
                    {nameof(RB_Customer_Extend.Remark),model.Remark },
                    {nameof(RB_Customer_Extend.EnterpriseName),model.EnterpriseName },
                    {nameof(RB_Customer_Extend.CustomerType),model.CustomerType },
                    {nameof(RB_Customer_Extend.UpdateTime),model.UpdateTime },
                    {nameof(RB_Customer_Extend.WeChatNo),model.WeChatNo },
                };
                flag = customerRepository.Update(fileds, new WhereHelper(nameof(RB_Customer_Extend.CustomerId), model.CustomerId));
                if (flag) 
                {
                    #region 操作记录
                    string LogContent = "后台修改同业信息:";                
                    if (oldModel.CustomerName != model.CustomerName)
                    {
                        LogContent += "名称由'" + oldModel.CustomerName + "'修改为'" + model.CustomerName + "';";
                    }
                    if (oldModel.ContactNumber != model.ContactNumber)
                    {
                        LogContent += "电话由'" + oldModel.ContactNumber + "'修改为'" + model.ContactNumber + "';";
                    }
                    if (oldModel.Fax != model.Fax)
                    {
                        LogContent += "传真由'" + oldModel.Fax + "'修改为'" + model.Fax + "';";
                    }
                    if (oldModel.QQ != model.QQ)
                    {
                        LogContent += "QQ由'" + oldModel.QQ + "'修改为'" + model.QQ + "';";
                    }
                    if (oldModel.Email != model.Email)
                    {
                        LogContent += "邮箱由'" + oldModel.Email + "'修改为'" + model.Email + "';";
                    }
          
                    if (oldModel.Address != model.Address)
                    {
                        LogContent += "地址由'" + oldModel.Address + "'修改为'" + model.Address + "';";
                    }
                    if (oldModel.Sex != model.Sex)
                    {
                        LogContent += "性别由'" + (oldModel.Sex == 1 ? "男" : "女") + "'修改为'" + (model.Sex == 1 ? "男" : "女") + "';";
                    }
                    if (oldModel.EnterpriseName != model.EnterpriseName)
                    {
                        LogContent += "企业/学校名称由'" + oldModel.EnterpriseName + "'修改为'" + model.EnterpriseName + "';";
                    }
                    if (oldModel.CustomerType != model.CustomerType)
                    {
                        LogContent += "类型由'" + (oldModel.CustomerType == 1 ? "企业" : "学校") + "'修改为'" + (model.CustomerType == 1 ? "企业" : "学校") + "';";
                    }
                    if (oldModel.WeChatNo != model.WeChatNo)
                    {
                        LogContent += "微信号由'" + oldModel.WeChatNo + "'修改为'" + model.WeChatNo + "';";
                    }
                    //记录操作日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 4,
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = model.Group_Id,
                        LogContent = LogContent,
                        School_Id = 0,
                        SourceId = model.CustomerId
                    });
                    #endregion
                }
            }
            else
            {
                model.CustomerState = Common.Enum.Customer.CustomerStateEnum.Normal;
                model.ApproveState = 1;
                model.ApproveId = 1;
                model.ApproveTime = DateTime.Now;
                model.Password  = Common.DES.Encrypt(Common.Config.DefaultPwd);
                var newId = customerRepository.Insert(model);
                model.CustomerId = newId;
                flag = newId > 0;
                if (flag) {
                    //记录操作日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 4,
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        Group_Id = model.Group_Id,
                        LogContent = "后台录入同业信息",
                        School_Id = 0,
                        SourceId = model.CustomerId
                    });
                }
            }
            return flag;
        }


        /// <summary>
        /// 根据编号删除客户信息
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public bool RemoveCustomerModule(object CustomerId)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
              {nameof(RB_Customer_Extend.Status),(int)DateStateEnum.Delete},
            };
            var flag = customerRepository.Update(fileds, new WhereHelper(nameof(RB_Customer_Extend.CustomerId), CustomerId));
            return flag;
        }


        /// <summary>
        /// 根据客户编号获取客户实体类
        /// </summary>
        /// <param name="CustomerId"></param>
        /// <returns></returns>
        public RB_Customer_Extend GetCustomerModule(object CustomerId)
        {
            var extModel = customerRepository.GetEntity<RB_Customer_Extend>(CustomerId);
            if (extModel != null)
            {
                if (extModel.ApproveId > 0)
                {
                    extModel.ApproveName = UserReidsCache.GetUserLoginInfo(extModel.ApproveId)?.AccountName ?? "";
                }
            }
            return extModel;
        }

        /// <summary>
        /// 客户审批
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AuditCustomerModule(RB_Customer_Extend model)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                  {nameof(RB_Customer_Extend.ApproveState),model.ApproveState},
                  {nameof(RB_Customer_Extend.ApproveContent),model.ApproveContent},
                  {nameof(RB_Customer_Extend.ApproveId),model.ApproveId},
                  {nameof(RB_Customer_Extend.ApproveTime),model.ApproveTime},
                  {nameof(RB_Customer_Extend.CustomerState),(int)CustomerStateEnum.Normal},
            };
            var flag = customerRepository.Update(fileds, new WhereHelper(nameof(RB_Customer_Extend.CustomerId), model.CustomerId));
            return flag;
        }

        /// <summary>
        /// 获取客户分页列表..
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Customer_Extend> GetCustomerPageModule_V2(int pageIndex, int pageSize, out long rowsCount, RB_Customer_Extend query)
        {
            var list = customerRepository.GetCustomerPageRepository(pageIndex, pageSize, out rowsCount, query);
            if (list.Any()) {
                string customerIds = string.Join(",", list.Select(x => x.CustomerId));
                //查询客户数量
                var StuNumList = customerRepository.GetCustomerStuNum(customerIds, query.Group_Id);
                //查询订单数量  及 交易额
                var OrderNumList = customerRepository.GetCustomerOrderNum(customerIds, query.Group_Id);

                foreach (var item in list) {
                    var stuModel = StuNumList.Where(x => x.CustomerId == item.CustomerId).FirstOrDefault();
                    var orderModel = OrderNumList.Where(x => x.CustomerId == item.CustomerId).FirstOrDefault();
                    item.StuNum = stuModel?.StuNum ?? 0;
                    item.OrderNum = orderModel?.OrderNum ?? 0;
                    item.OrderSales = orderModel?.OrderSales ?? 0;
                }
            }
            return list;
        }

        /// <summary>
        /// 获取同业佣金/幸福存折
        /// </summary>
        /// <param name="customerId"></param>
        /// <returns></returns>
        public object GetCustomerCommissionPassbook(int customerId, int type, int group_Id)
        {
            var cmodel = customerRepository.GetEntity(customerId);
            //获取提现金额
            decimal RemitMoney = customer_RemitRepository.GetMyWithdrawCommission(customerId, type, group_Id);
            //获取未结算金额
            decimal NotSettlementMoney = customer_BalanceDetailRepository.GetMyNoSettlementCommission(customerId, type, group_Id);
            decimal TotalMoney = cmodel.TotalCommission;
            decimal SurplusMoney = cmodel.CommissionWithdrawal;
            if (type == 2) {
                //幸福存折
                TotalMoney = cmodel.Client_Balance + RemitMoney;
                SurplusMoney = cmodel.Client_Balance;
            }

            return new
            {
                TotalMoney,
                RemitMoney,
                SurplusMoney,
                NotSettlementMoney
            };
        }

        /// <summary>
        /// 设置同业转交
        /// </summary>
        /// <param name="customerIds"></param>
        /// <param name="empId"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerCareOf(string customerIds, int empId, UserInfo userInfo)
        {
            var clist =  customerRepository.GetCustomerListRepository(new RB_Customer_Extend() { Group_Id = userInfo.Group_Id, CustomerIds = customerIds });
            foreach (var item in clist) {
                if (item.CreateBy == empId) {
                    return item.CustomerName + "的原跟进人员与接收人相同,无法转交";
                }
            }
            var empName = UserReidsCache.GetUserLoginInfo(empId)?.AccountName ?? "";
            foreach (var item in clist) {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Customer_Extend.CreateBy), empId},
                    { nameof(RB_Customer_Extend.UpdateTime), DateTime.Now},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Customer_Extend.CustomerId),
                          FiledValue = item.CustomerId,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                bool flag = customerRepository.Update(keyValues, wheres);
                if (flag)
                {
                    string OldName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.AccountName ?? "";
                    //记录操作日志
                    changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                    {
                        Id = 0,
                        Type = 4,
                        CreateBy = userInfo.Id,
                        CreateTime = DateTime.Now,
                        Group_Id = userInfo.Group_Id,
                        LogContent = "转交:由" + OldName + "转交给" + empName,
                        School_Id = 0,
                        SourceId = item.CustomerId
                    });
                }
                else {
                    return item.CustomerName + "转交失败,请联系管理员";
                }
            }
            return "";
        }

        /// <summary>
        /// 获取同业下所有学生阶段人数统计
        /// </summary>
        /// <param name="customerId"></param>
        /// <param name="group_Id"></param>
        /// <returns></returns>
        public object GetCustomerStuStageStatistics(int customerId, int group_Id)
        {
            List<object> RList = new List<object>();
            var list = studentRepository.GetCustomerStuStageStatistics(customerId, group_Id);
            var elist = stageRepository.GetStageListRepostory(new Model.Entity.System.RB_Stage()
            {
                Group_Id = group_Id
            });
            elist = elist.OrderBy(x => x.Id).ToList();
            foreach (var item in elist)
            {
                int Num = list.Where(x => x.StuStage == item.Id).FirstOrDefault()?.OrderCount ?? 0;
                RList.Add(new
                {
                    StuStage = item.Id,
                    StuStageName = item.StageName,
                    StuNum = Num
                });
            }
            return RList;
        }

        /// <summary>
        /// 获取同行列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Customer_Extend> GetCustomerListModule(RB_Customer_Extend query)
        {
            return customerRepository.GetCustomerListRepository(query);
        }

        /// <summary>
        /// 获取企业分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="rowsCount"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Enterprise_Extend> GetEnterprisePageModule(int pageIndex, int pageSize, out long rowsCount, RB_Enterprise_Extend query)
        {
            var list = enterpriseRepository.GetEnterprisePageRepository(pageIndex, pageSize, out rowsCount, query);
            return list;
        }


        /// <summary>
        /// 获取企业列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public List<RB_Enterprise_Extend> GetEnterpriseListModule(RB_Enterprise_Extend query)
        {
            var list = enterpriseRepository.GetEnterpriseListRepository(query);
            return list;
        }

        /// <summary>
        /// 新增修改企业信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SetEnterpriseModule(RB_Enterprise_Extend model)
        {
            bool flag = false;
            if (model.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Enterprise_Extend.EnterpriseName),model.EnterpriseName },
                    {nameof(RB_Enterprise_Extend.UpdateBy),model.UpdateBy },
                    {nameof(RB_Enterprise_Extend.UpdateTime),model.UpdateTime },
                };
                flag = enterpriseRepository.Update(fileds, new WhereHelper(nameof(RB_Enterprise_Extend.Id), model.Id));
            }
            else
            {
                var newId = enterpriseRepository.Insert(model);
                model.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 根据编号获取企业信息实体类
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Enterprise_Extend GetEnterpriseModule(int Id)
        {
            var extModel = enterpriseRepository.GetEntity<RB_Enterprise_Extend>(Id);
            return extModel;
        }

        /// <summary>
        /// 根据编号删除企业信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public bool RemoveEnterpriseModule(int Id)
        {
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
               {nameof(RB_Enterprise_Extend.Status),(int)DateStateEnum.Delete },
            };
            bool flag = enterpriseRepository.Update(fileds, new WhereHelper(nameof(RB_Enterprise_Extend.Id), Id));
            return flag;
        }
    }
}