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

namespace Edu.Module.Course
{
    /// <summary>
    /// 教育同业订单处理类
    /// </summary>
    public class EduB2BOrderModule
    {
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_OrderRepository orderRepository = new RB_OrderRepository();        
        /// <summary>
        /// 用户日志
        /// </summary>
        private readonly RB_User_ChangeLogRepository changeLogRepository = new RB_User_ChangeLogRepository();
        /// <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_GroupRepository groupRepository = new RB_GroupRepository();



        /// <summary>
        /// 更新教育同业订单超时取消
        /// </summary>
        /// <returns></returns>
        public bool SetEduB2BOrderCancel() {
            var glist = groupRepository.GetGroupListRepository(new Model.ViewModel.User.RB_Group_ViewModel() { });
            foreach (var group in glist) {
                int GroupId = group.GId;
                //查询此集团下所有超时未付款的教育同业订单
                var olist = orderRepository.GetEduB2BTimeoutOrderList(GroupId);
                foreach (var item in olist) {
                    //取消订单
                    Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                        { nameof(RB_Order_ViewModel.OrderState), Common.Enum.Course.OrderStateEnum.Cancel}
                    };
                    List<WhereHelper> wheres = new List<WhereHelper>() {
                        new WhereHelper(){
                             FiledName = nameof(RB_Order_ViewModel.OrderId),
                              FiledValue = item.OrderId,
                               OperatorEnum =OperatorEnum.Equal
                        }
                    };
                    bool flag = orderRepository.Update(keyValues, wheres);
                    if (flag)
                    {
                        //记录日志
                        changeLogRepository.Insert(new Model.Entity.Log.RB_User_ChangeLog()
                        {
                            Id = 0,
                            Type = 2,
                            CreateBy = item.EnterID,
                            CreateTime = DateTime.Now,
                            Group_Id = GroupId,
                            LogContent = $"同业付款超时自动取消订单【{item.OrderId}】",
                            School_Id = 0,
                            SourceId = item.OrderId
                        });
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 更新教育同业订单返佣
        /// </summary>
        /// <returns></returns>
        public bool SetEduB2BOrderCommission()
        {
            if (DateTime.Now.Day != 25) { return false; }
            var glist = groupRepository.GetGroupListRepository(new Model.ViewModel.User.RB_Group_ViewModel() { });
            var trans = customerRepository.DbTransaction;
            try
            {
                foreach (var group in glist)
                {
                    int GroupId = group.GId;
                    string dateStr = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM") + "-01").AddDays(-1).ToString("yyyy-MM-dd");
                    //获取可发放返佣的订单+返佣列表                
                    var blist = customer_BalanceDetailRepository.GetEduB2BOrderCanSendCommissionList(GroupId, dateStr);
                    if (blist.Any())
                    {
                        var clist = customerRepository.GetCustomerListRepository(new RB_Customer_Extend() { Group_Id = GroupId, CustomerIds = string.Join(",", blist.Select(x => x.CustomerId).Distinct()) });
                        var olist = orderRepository.GetOrderListRepository(new RB_Order_ViewModel() { Group_Id = GroupId, QOrderIds = string.Join(",", blist.Select(x => x.OrderId).Distinct()) });
                        //查询需要课耗返的订单  在查询其课耗信息
                        //再查询学生信息


                        //查询所有的同业
                        foreach (var item in olist.OrderBy(x => x.OrderId))
                        {
                            var bclist = blist.Where(x => x.OrderId == item.OrderId).ToList();
                            if (bclist.Any())
                            {
                                foreach (var qitem in bclist.OrderBy(x => x.Id))
                                {
                                    var cmodel = clist.Where(x => x.CustomerId == qitem.CustomerId).FirstOrDefault();
                                    if (item.CommissionReType == 1)
                                    {
                                        //课耗返佣

                                    }
                                    else if (item.CommissionReType == 2)
                                    {
                                        Dictionary<string, object> keyValues = new Dictionary<string, object>();
                                        if (qitem.RebateType == 1)
                                        {
                                            //返佣                                            
                                            cmodel.TotalCommission += qitem.Money;
                                            cmodel.CommissionWithdrawal += qitem.Money;
                                            keyValues.Add(nameof(RB_Customer_BalanceDetail_ViewModel.BalanceState), 1);
                                            keyValues.Add(nameof(RB_Customer_BalanceDetail_ViewModel.GiveOutMoney), qitem.Money);
                                            keyValues.Add(nameof(RB_Customer_BalanceDetail_ViewModel.AccountMoney), cmodel.CommissionWithdrawal);
                                        }
                                        else {
                                            //幸福存折
                                            cmodel.Client_Balance += qitem.Money;
                                            keyValues.Add(nameof(RB_Customer_BalanceDetail_ViewModel.BalanceState), 1);
                                            keyValues.Add(nameof(RB_Customer_BalanceDetail_ViewModel.GiveOutMoney), qitem.Money);
                                            keyValues.Add(nameof(RB_Customer_BalanceDetail_ViewModel.AccountMoney), cmodel.Client_Balance);
                                        }
                                        List<WhereHelper> wheres = new List<WhereHelper>() {
                                            new WhereHelper(){
                                                    FiledName = nameof(RB_Customer_BalanceDetail_ViewModel.Id),
                                                    FiledValue = qitem.Id,
                                                    OperatorEnum =OperatorEnum.Equal
                                            }
                                        };
                                        customer_BalanceDetailRepository.Update(keyValues, wheres, trans);
                                    }
                                }
                            }
                        }
                        //更新所有的同业佣金
                        foreach (var item in clist)
                        {
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Customer_Extend.TotalCommission), item.TotalCommission},
                                { nameof(RB_Customer_Extend.CommissionWithdrawal), item.CommissionWithdrawal},
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_Customer_Extend.CustomerId),
                                      FiledValue = item.CustomerId,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            customerRepository.Update(keyValues, wheres, trans);
                        }
                    }
                }
                //(后面应该调整为  单同行遍历更新  不然课耗订单太多  效率肯定非常的慢-------------)
                customerRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                customerRepository.DBSession.Rollback();
                LogHelper.Write(ex, "SetEduB2BOrderCommission 定时更新 更新教育同业订单返佣");
                return false;
            }
        }

        /// <summary>
        /// 发放教育同业每月佣金/幸福存折
        /// </summary>
        /// <returns></returns>
        public bool SetEduB2BCustomerCommission() {
            if (DateTime.Now.Day != 25) { return false; }
            var glist = groupRepository.GetGroupListRepository(new Model.ViewModel.User.RB_Group_ViewModel() { });
            var trans = customerRepository.DbTransaction;
            try
            {
                foreach (var group in glist)
                {
                    int GroupId = group.GId;
                    string dateStr = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM") + "-01").AddDays(-1).ToString("yyyy-MM-dd");
                    //获取可发放返佣列表                
                    var blist = customer_BalanceDetailRepository.SetEduB2BCustomerCommissionCanSendList(GroupId, dateStr);
                    if (blist.Any())
                    {
                        //获取所有的同业
                        customerRepository.GetCustomerListRepository(new RB_Customer_Extend() { });
                        //获取所有的订单列表

                        //获取所有的学生列表

                        //获取所有学生已上课课时

                        //获取已发放记录

                        //根据当月已上课时  计算当月应返佣金额

                    }
                }
                customerRepository.DBSession.Commit();
                return true;
            }
            catch (Exception ex)
            {
                customerRepository.DBSession.Rollback();
                LogHelper.Write(ex, "SetEduB2BOrderCommission 定时更新 更新教育同业订单返佣");
                return false;
            }
        }
    }
}
