using Edu.Common;
using Edu.Common.Enum.Course;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Customer;
using Edu.Model.ViewModel.Finance;
using Edu.Repository.Customer;
using Edu.Repository.Finance;
using Edu.Repository.User;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Edu.Module.Customer
{
    /// <summary>
    /// 客户提现处理类
    /// </summary>
    public class CustomerRemitModule
    {
        /// <summary>
        /// 同业
        /// </summary>
        private readonly RB_CustomerRepository customerRepository = new RB_CustomerRepository();
        /// <summary>
        /// 提现账号
        /// </summary>
        private readonly RB_Customer_AccountRepository customer_AccountRepository = new RB_Customer_AccountRepository();
        /// <summary>
        /// 提现
        /// </summary>
        private readonly RB_Customer_RemitRepository customer_RemitRepository = new RB_Customer_RemitRepository();
        /// <summary>
        /// 财务配置
        /// </summary>
        private readonly RB_Finance_ConfigRepository finance_ConfigRepository = new RB_Finance_ConfigRepository();
        /// <summary>
        /// 财务账户
        /// </summary>
        private readonly RB_ClientBankAccountRepository clientBankAccountRepository = new RB_ClientBankAccountRepository();
        /// <summary>
        /// 幻灯片
        /// </summary>
        private readonly RB_B2B_SlideShowRepository b2B_SlideShowRepository = new RB_B2B_SlideShowRepository();
        /// <summary>
        /// 用户返佣
        /// </summary>
        private readonly RB_User_ReturnComissionRepository user_ReturnComissionRepository = new RB_User_ReturnComissionRepository();
        /// <summary>
        /// 订单返佣
        /// </summary>
        private readonly Repository.Sell.RB_Order_ReturnComissionRepository order_ReturnComissionRepository = new Repository.Sell.RB_Order_ReturnComissionRepository();

        /// <summary>
        /// 员工信息仓储层对象
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();


        #region 提现管理

        /// <summary>
        /// 获取提现分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Customer_Remit_Extend> GetCustomerRemitPageList(int pageIndex, int pageSize, out long count, RB_Customer_Remit_Extend demodel)
        {
            var list = customer_RemitRepository.GetRemitPageRepository(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                string bankIds = string.Join(",", list.Select(x => x.BankAccountId).Distinct());
                var blist = customer_AccountRepository.GetAccountListRepository(new RB_Customer_Account_Extend() { Group_Id = demodel.GroupId, BankIds = bankIds });
                foreach (var item in list)
                {
                    var bmodel = blist.Where(x => x.Id == item.BankAccountId).FirstOrDefault();
                    item.BankName = bmodel.BankName;
                    item.BankCardNo = bmodel.BankCardNo;
                    item.BankIcon = bmodel.Logo;
                    item.AccountHolder = bmodel.AccountHolder;
                }
            }
            return list;
        }

        /// <summary>
        /// 设置同业提现状态
        /// </summary>
        /// <param name="remitId"></param>
        /// <param name="state"></param>
        /// <param name="remark"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string SetCustomerRemitState(int remitId, int state, string remark, UserInfo userInfo)
        {
            var rmodel = customer_RemitRepository.GetEntity(remitId);
            if (rmodel == null) { return "提现不存在"; }
            if (rmodel.AuditStatus != 1) { return "提现状态不正确"; }
            Dictionary<string, object> keyValues = new Dictionary<string, object>()
            {
                {nameof(RB_Customer_Remit_Extend.AuditRemark), remark} ,
                {nameof(RB_Customer_Remit_Extend.AuditDate), DateTime.Now}
            };
            //审核通过
            if (state == 1)
            {
                keyValues.Add(nameof(RB_Customer_Remit_Extend.AuditStatus), 2);
            }
            //审核驳回
            else if (state == 2)
            {
                keyValues.Add(nameof(RB_Customer_Remit_Extend.AuditStatus), 4);
            }
            else
            {
                return "状态有误,请核实后再试";
            }
            List<WhereHelper> wheres = new List<WhereHelper>() 
            {
                new WhereHelper()
                {
                     FiledName = nameof(RB_Customer_Remit_Extend.Id),
                     FiledValue = remitId,
                     OperatorEnum =OperatorEnum.Equal
                }
            };
            bool flag = customer_RemitRepository.Update(keyValues, wheres);
            if (flag)
            {
                if (state == 1)
                {
                    var cmodel = customerRepository.GetEntity(rmodel.CustomerId);
                    var amodel = customer_AccountRepository.GetEntity(rmodel.BankAccountId);
                    var employeeModel = accountRepository.GetEmployeeInfo(cmodel.CreateBy);
                    //同意需要制财务单据
                    #region 新增财务单据
                    var fcmodel = new RB_Finance_Config_ViewModel();
                    if (rmodel.Type == 1)
                    {
                        fcmodel = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = FinanceConfigTypeEnum.B2BCommission }).FirstOrDefault();
                    }
                    else
                    {
                        fcmodel = finance_ConfigRepository.GetList(new RB_Finance_Config_ViewModel() { Group_Id = userInfo.Group_Id, Type = FinanceConfigTypeEnum.HappinessPassbook }).FirstOrDefault();
                    }
                    if (fcmodel == null) { return "未配置制单流程"; }
                    //银行账户
                    var clientModel = clientBankAccountRepository.GetList(new RB_ClientBankAccount_Extend() { RB_Group_Id = userInfo.Group_Id, Type = Common.Enum.Finance.ClientTypeEnum.Other, EduRemitAccountId = rmodel.BankAccountId }).FirstOrDefault();
                    if (clientModel == null)
                    {
                        //新增付款对象
                        clientModel = new Model.Entity.Finance.RB_ClientBankAccount()
                        {
                            ID = 0,
                            Status = Common.Enum.DateStateEnum.Normal,
                            AccountAlias = amodel.BankName,
                            CardNum = amodel.BankCardNo,
                            AccountHolder = amodel.AccountHolder,
                            OpenBankName = amodel.AccountBank,
                            AccountClassify = 2,
                            AccountType = 2,
                            BankId = 0,
                            CreateBy = 0,
                            CreateDate = DateTime.Now,
                            EduRemitAccountId = rmodel.BankAccountId,
                            RB_BranchName = "",
                            RB_Branch_Id = 0,
                            RB_CreateByName = "",
                            RB_Group_Id = userInfo.Group_Id,
                            Type = Common.Enum.Finance.ClientTypeEnum.Other
                        };
                        clientModel.ID = clientBankAccountRepository.Insert(clientModel);
                    }
                    else
                    {
                        if (amodel.BankName != clientModel.AccountAlias || amodel.BankCardNo != clientModel.CardNum
                            || amodel.AccountHolder != clientModel.AccountHolder || amodel.AccountBank != clientModel.OpenBankName)
                        {
                            //修改付款对象
                            Dictionary<string, object> keyValues1 = new Dictionary<string, object>() {
                                { nameof(RB_ClientBankAccount_Extend.AccountAlias), amodel.BankName},
                                { nameof(RB_ClientBankAccount_Extend.CardNum), amodel.BankCardNo},
                                { nameof(RB_ClientBankAccount_Extend.AccountHolder), amodel.AccountHolder},
                                { nameof(RB_ClientBankAccount_Extend.OpenBankName), amodel.AccountBank},
                            };
                            List<WhereHelper> wheres1 = new List<WhereHelper>() 
                            {
                                new WhereHelper()
                                {
                                     FiledName = nameof(RB_ClientBankAccount_Extend.ID),
                                     FiledValue = clientModel.ID,
                                     OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            clientBankAccountRepository.Update(keyValues1, wheres1);
                        }
                    }
                   
                    decimal TotalMoney = rmodel.AppliedMoney;
                    var detailList = new List<object>
                    {
                        new
                        {
                            fcmodel.CostTypeId,
                            Number = 1,
                            OriginalMoney = rmodel.AppliedMoney,
                            UnitPrice =rmodel.AppliedMoney,
                            Remark = "同业" + (rmodel.Type == 1 ? "佣金" : "幸福存折") + "提现:" + cmodel.CustomerName + "(" + cmodel.ContactNumber + ")"
                        }
                    };
                    string Remark = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "自动生成财务单据";
                    var financeObj = new
                    {
                        IsPublic = 0,
                        ClientType = (int)Common.Enum.Finance.ClientTypeEnum.Other,
                        ClientID = clientModel.ID,
                        fcmodel.CurrencyId,
                        WBMoney = TotalMoney,
                        PayDate = DateTime.Now.ToString("yyyy-MM-dd"),
                        TemplateId = fcmodel.TempleteId,
                        OrderSource = 17,
                        OtherType = 49,
                        ReFinanceId = rmodel.Id,
                        Remark,
                        detailList,
                        CreateBy = employeeModel.Id,
                        RB_Branch_Id = employeeModel.School_Id,
                        RB_Depart_Id = employeeModel.Dept_Id,
                        RB_Group_Id = employeeModel.Group_Id,
                        RB_CreateByName = employeeModel.EmployeeName,
                        RB_DepartName = employeeModel.DeptName,
                        RB_BranchName = employeeModel.SchoolName,
                        RB_GroupName = employeeModel.GroupName,
                        FinanceType = 2
                    };
                    string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.ReadConfigKey("FinanceKey"));
                    var resultInfo = new
                    {
                        msg = sign
                    };

                    string apiResult = HttpHelper.HttpPost(Config.ReadConfigKey("PaymentFinanceApi"), JsonHelper.Serialize(resultInfo), "");
                    JObject parmsJob = JObject.Parse(apiResult);
                    string resultCode = parmsJob.GetStringValue("resultCode");
                    int frid = parmsJob.GetInt("data", 0);

                    if (resultCode == "1" && frid > 0)
                    {
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>()
                        {
                            { nameof(RB_Customer_Remit_Extend.FinanceId), frid},
                            { nameof(RB_Customer_Remit_Extend.AuditRemark), remark +" 自动生成财务单据:"+frid}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() 
                        {
                            new WhereHelper()
                            {
                                 FiledName = nameof(RB_Customer_Remit_Extend.Id),
                                 FiledValue = rmodel.Id,
                                 OperatorEnum =OperatorEnum.Equal
                            }
                        };
                        customer_RemitRepository.Update(keyValues1, wheres1);
                    }
                    else
                    {
                        string message = parmsJob.GetStringValue("message");
                        LogHelper.Write("SetCustomerRemitState:" + message);
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>()
                        {
                            { nameof(RB_Customer_Remit_Extend.FinanceId), frid},
                            { nameof(RB_Customer_Remit_Extend.AuditRemark), remark +" 自动生成财务单据失败,请联系管理员"}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>() {
                            new WhereHelper()
                            {
                                 FiledName = nameof(RB_Customer_Remit_Extend.Id),
                                 FiledValue = rmodel.Id,
                                 OperatorEnum =OperatorEnum.Equal
                            }
                        };
                        customer_RemitRepository.Update(keyValues1, wheres1);
                    }
                    #endregion
                }
                else if (state == 2)
                {
                    //驳回的话 需要修改已提现状态 
                    var urmodel = user_ReturnComissionRepository.GetList(new Model.ViewModel.User.RB_User_ReturnComission_ViewModel() { GroupId = userInfo.Group_Id, UserId = rmodel.CustomerId, UserType = Common.Enum.User.StuCreateTypeEnum.CustomerInput, CommissionType = rmodel.Type }).FirstOrDefault();
                    if (urmodel != null)
                    {
                        Dictionary<string, object> keyValues1 = new Dictionary<string, object>() 
                        {
                            { nameof(Model.ViewModel.User.RB_User_ReturnComission_ViewModel.CanCashOutMoney), urmodel.CanCashOutMoney + rmodel.AppliedMoney},
                            { nameof(Model.ViewModel.User.RB_User_ReturnComission_ViewModel.CashOutMoney), urmodel.CashOutMoney - rmodel.AppliedMoney}
                        };
                        List<WhereHelper> wheres1 = new List<WhereHelper>()
                        {
                            new WhereHelper()
                            {
                                 FiledName = nameof(Model.ViewModel.User.RB_User_ReturnComission_ViewModel.UserId),
                                 FiledValue = urmodel.UserId,
                                 OperatorEnum =OperatorEnum.Equal
                            },
                            new WhereHelper()
                            {
                                 FiledName = nameof(Model.ViewModel.User.RB_User_ReturnComission_ViewModel.UserType),
                                 FiledValue = urmodel.UserType,
                                 OperatorEnum =OperatorEnum.Equal
                            },
                            new WhereHelper()
                            {
                                 FiledName = nameof(Model.ViewModel.User.RB_User_ReturnComission_ViewModel.CommissionType),
                                 FiledValue = urmodel.CommissionType,
                                 OperatorEnum =OperatorEnum.Equal
                            },
                        };
                        user_ReturnComissionRepository.Update(keyValues1, wheres1);
                        //更新所有订单返佣为可提现
                        order_ReturnComissionRepository.UpdateOrderReturnComission(userInfo.Group_Id, remitId);
                    }
                }
            }
            return flag ? "" : "出错了,请联系管理员";
        }

        #endregion

        #region 幻灯片
        /// <summary>
        /// 获取幻灯片配置
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetB2BSlideShowInfo(UserInfo userInfo)
        {
            var smodel = b2B_SlideShowRepository.GetList(new RB_B2B_SlideShow_Extend() { Group_Id = userInfo.Group_Id }).FirstOrDefault();
            if (smodel != null)
            {
                var list = JsonHelper.DeserializeObject<List<B2BSlideShowModel>>(smodel.Content);
                return new
                {
                    smodel.Title,
                    smodel.SubTitle,
                    List = list.OrderBy(x => x.Sort).ToList()
                };
            }
            else
            {
                return new
                {
                    Title = "",
                    SubTitle = "",
                    List = new List<B2BSlideShowModel>()
                };
            }
        }

        /// <summary>
        /// 保存幻灯片配置
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetB2BSlideShowInfo(RB_B2B_SlideShow_Extend demodel)
        {
            var smodel = b2B_SlideShowRepository.GetList(new RB_B2B_SlideShow_Extend() { Group_Id = demodel.Group_Id }).FirstOrDefault();
            if (smodel == null)
            {
                bool flag = b2B_SlideShowRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了,请联系管理员";
            }
            else
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_B2B_SlideShow_Extend.Title), demodel.Title},
                    { nameof(RB_B2B_SlideShow_Extend.SubTitle), demodel.SubTitle},
                    { nameof(RB_B2B_SlideShow_Extend.Content), demodel.Content},
                    { nameof(RB_B2B_SlideShow_Extend.UpdateBy), demodel.UpdateBy},
                    { nameof(RB_B2B_SlideShow_Extend.UpdateTime), demodel.UpdateTime},
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_B2B_SlideShow_Extend.Id),
                          FiledValue = smodel.Id,
                           OperatorEnum =OperatorEnum.Equal
                    }
                };
                bool flag = b2B_SlideShowRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了,请联系管理员";
            }
        }

        #endregion

    }
}