using Mall.Common;
using Mall.Common.API;
using Mall.Common.Models;
using Mall.Common.Plugin;
using Mall.Model.Entity.Coffee;
using Mall.Model.Extend.Coffee;
using Mall.Model.Extend.Product;
using Mall.Repository.BaseSetUp;
using Mall.Repository.Coffee;
using Mall.Repository.Education;
using Mall.Repository.Product;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Mall.Module.Education
{
    public class CoffeeModule
    {
        /// <summary>
        /// 咖啡劵
        /// </summary>
        private readonly RB_Member_CoffeeCouponsRepository member_CoffeeCouponsRepository = new RB_Member_CoffeeCouponsRepository();
        /// <summary>
        /// 咖啡劵消费记录
        /// </summary>
        private readonly RB_Member_CoffeeLogRepository member_CoffeeLogRepository = new RB_Member_CoffeeLogRepository();
        /// <summary>
        /// 字典
        /// </summary>
        private readonly Rb_DictvalueRepository dictvalueRepository = new Rb_DictvalueRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_GoodsRepository goodsRepository = new RB_GoodsRepository();
        /// <summary>
        /// 商品规格
        /// </summary>
        private readonly RB_Goods_SpecificationPriceRepository goods_SpecificationPriceRepository = new RB_Goods_SpecificationPriceRepository();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly RB_Goods_OrderRepository goods_OrderRepository = new RB_Goods_OrderRepository();
        /// <summary>
        /// 订单明细
        /// </summary>
        private readonly RB_Goods_OrderDetailRepository goods_OrderDetailRepository = new RB_Goods_OrderDetailRepository();
        /// <summary>
        /// 用户关联
        /// </summary>
        private readonly RB_Education_EduSellRepository education_EduSellRepository = new RB_Education_EduSellRepository();
        /// <summary>
        /// 甲鹤用户
        /// </summary>
        private readonly Repository.User.RB_Member_UserRepository member_UserRepository = new Repository.User.RB_Member_UserRepository();
        /// <summary>
        /// 账号
        /// </summary>
        private readonly RB_AccountRepository accountRepository = new RB_AccountRepository();


        /// <summary>
        /// 获取我的咖啡劵详情
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public object GetMyCoffeeCouponsInfo(AppletUserInfo userInfo, out string msg)
        {
            msg = "";
            var esModel = education_EduSellRepository.GetEducationStuList(new Model.Extend.Education.RB_Education_EduSell_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }, true).FirstOrDefault();
            var cmodel = member_CoffeeCouponsRepository.GetList(new RB_Member_CoffeeCoupons_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId }).FirstOrDefault();
            if (cmodel == null)
            {
                //没有咖啡劵信息
                //查询关联的信息
                if (esModel != null)
                {
                    if (esModel.Type == 1)
                    {
                        //内部人员  直接初始化  内部人员的咖啡劵信息
                        int FreeNum = Convert.ToInt32(dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = userInfo.MallBaseId, DictKey = "Edu_CoffeeCoupons_EmpFree" }).FirstOrDefault()?.Content ?? "0");
                        if (FreeNum > 0)
                        {
                            cmodel = new RB_Member_CoffeeCoupons_Extend()
                            {
                                Id = 0,
                                CreateDate = DateTime.Now,
                                FreeNum = FreeNum,
                                MallBaseId = userInfo.MallBaseId,
                                SurplusBugNum = 0,
                                TotalBuyNum = 0,
                                UpdateDate = DateTime.Now,
                                UserId = userInfo.UserId
                            };
                            cmodel.Id = member_CoffeeCouponsRepository.Insert(cmodel);
                        }
                    }
                    else if (esModel.Type == 2)
                    {
                        //学生  要看是否还有正在学习的课程  有的话 可初始化免费的咖啡劵
                        int learningNum = accountRepository.GetStuLearningCourse(esModel.EduSellId);
                        if (learningNum > 0)
                        {
                            int FreeNum = Convert.ToInt32(dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = userInfo.MallBaseId, DictKey = "Edu_CoffeeCoupons_Free" }).FirstOrDefault()?.Content ?? "0");
                            if (FreeNum > 0)
                            {
                                cmodel = new RB_Member_CoffeeCoupons_Extend()
                                {
                                    Id = 0,
                                    CreateDate = DateTime.Now,
                                    FreeNum = FreeNum,
                                    MallBaseId = userInfo.MallBaseId,
                                    SurplusBugNum = 0,
                                    TotalBuyNum = 0,
                                    UpdateDate = DateTime.Now,
                                    UserId = userInfo.UserId
                                };
                                cmodel.Id = member_CoffeeCouponsRepository.Insert(cmodel);
                            }
                        }
                    }
                }
                if (cmodel == null)
                {
                    cmodel = new RB_Member_CoffeeCoupons_Extend()
                    {
                        Id = 0,
                        CreateDate = DateTime.Now,
                        FreeNum = 0,
                        MallBaseId = userInfo.MallBaseId,
                        SurplusBugNum = 0,
                        TotalBuyNum = 0,
                        UpdateDate = DateTime.Now,
                        UserId = userInfo.UserId
                    };
                    cmodel.Id = member_CoffeeCouponsRepository.Insert(cmodel);
                }
            }
            else {
                if (esModel != null && esModel.IsInitFreeCoffee == 1 && esModel.Type == 2) {
                    //该用户咖啡劵没更新赠送  验证一下  其是否还有正在学习的课程  有的话 恢复赠送咖啡劵
                    int learningNum = accountRepository.GetStuLearningCourse(esModel.EduSellId);
                    if (learningNum > 0)
                    {
                        int FreeNum = Convert.ToInt32(dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = userInfo.MallBaseId, DictKey = "Edu_CoffeeCoupons_Free" }).FirstOrDefault()?.Content ?? "0");
                        if (FreeNum > 0)
                        {
                            cmodel.FreeNum = FreeNum;
                            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                                { nameof(RB_Member_CoffeeCoupons_Extend.FreeNum), FreeNum}
                            };
                            List<WhereHelper> wheres = new List<WhereHelper>() {
                                new WhereHelper(){
                                     FiledName = nameof(RB_Member_CoffeeCoupons_Extend.Id),
                                      FiledValue = cmodel.Id,
                                       OperatorEnum =OperatorEnum.Equal
                                }
                            };
                            member_CoffeeCouponsRepository.Update(keyValues, wheres);
                        }
                    }
                }
            }
            string GiveAway = dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = userInfo.MallBaseId, DictKey = "Edu_CoffeeCoupons_GiveAway" }).FirstOrDefault()?.Content??"";
            List<object> giveAwayList = new List<object>();
            if (!string.IsNullOrEmpty(GiveAway)) {
                var glist = GiveAway.Split("/");
                foreach (var item in glist) {
                    var slist = item.Split('-');
                    giveAwayList.Add(new
                    {
                        BuyNum = slist[0],
                        GiveAwayNum = slist[1]
                    });
                }
            }
            //获取当前咖啡劵单价
            var goodsModel = goodsRepository.GetSingleList(new RB_Goods_Extend() { MallBaseId = userInfo.MallBaseId, GoodsEduType = 1, GoodsStatus = 1 }).FirstOrDefault();
            decimal SellingPrice = 0;
            string SpecificationSort = "";
            if (goodsModel != null)
            {
                var spMdoel = goods_SpecificationPriceRepository.GetList(new RB_Goods_SpecificationPrice_Extend() { MallBaseId = userInfo.MallBaseId, GoodsId = goodsModel.Id }).FirstOrDefault();
                SellingPrice = spMdoel.SellingPrice ?? 0;
                SpecificationSort = spMdoel.SpecificationSort;
            }
            string Address = dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = userInfo.MallBaseId, DictKey = "Edu_Coffee_Address" }).FirstOrDefault()?.Content ?? "";
            return new
            {
                GoodsId = goodsModel?.Id ?? 0,
                SpecificationSort,
                SellingPrice,
                SurplusBugNum = cmodel?.SurplusBugNum ?? 0,
                FreeNum = cmodel?.FreeNum ?? 0,
                GiveAwayList = giveAwayList,
                Address
            };
        }

        /// <summary>
        /// 获取我的咖啡劵消费列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Member_CoffeeLog_Extend> GetMyCoffeeCouponsPageList(int pageIndex, int pageSize, out long count, RB_Member_CoffeeLog_Extend demodel)
        {
            var list = member_CoffeeLogRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            return list;
        }

        /// <summary>
        /// 获取我的咖啡劵订单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Goods_Order_Extend> GetMyCofeeOrderPageList(int pageIndex, int pageSize, out long count, RB_Goods_Order_Extend demodel) {
            var list = goods_OrderRepository.GetOrderPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                string orderIds = string.Join(",", list.Select(x => x.OrderId));
                var dlist = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { MallBaseId = demodel.MallBaseId, OrderIds = orderIds });
                foreach (var item in list) {
                    item.DetailList = dlist.Where(x => x.OrderId == item.OrderId).ToList();
                }
            }
            return list;
        }

        /// <summary>
        /// 获取我的咖啡劵订单信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="userId"></param>
        /// <param name="mallbaseId"></param>
        /// <returns></returns>
        public RB_Goods_Order_Extend GetMyCoffeeOrderInfo(int orderId , int userId , int mallbaseId) {
            var omodel = goods_OrderRepository.GetEntity<RB_Goods_Order_Extend>(orderId);
            if (omodel == null || omodel.UserId != userId || omodel.MallBaseId != mallbaseId) { return null; }

            omodel.DetailList = goods_OrderDetailRepository.GetOrderDetailList(new RB_Goods_OrderDetail_Extend() { MallBaseId = mallbaseId, OrderId = orderId });
            //查询下地址
            string Address = dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = mallbaseId, DictKey = "Edu_Coffee_Address" }).FirstOrDefault()?.Content ?? "";
            omodel.ShoppingAddress = Address;
            return omodel;
        }

        /// <summary>
        /// 核销咖啡劵
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userInfo"></param>
        /// <param name="rmsg"></param>
        /// <returns></returns>
        public object SetAdminVerificationCoffee(int userId, string code, AppletUserInfo userInfo, out string rmsg)
        {
            rmsg = "";
            string AdminIds = dictvalueRepository.GetList(new Model.Extend.BaseSetUp.RB_Dictvalue_Extend() { MallBaseId = userInfo.MallBaseId, DictKey = "Edu_CoffeeCoupons_Verification" }).FirstOrDefault()?.Content ?? "";
            if (AdminIds == "") { rmsg = "您没有权限核销咖啡劵"; return ""; }
            var adminModel = education_EduSellRepository.GetEducationSellBaseInfo(new Model.Extend.Education.RB_Education_EduSell_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, EduSellIds = AdminIds }).FirstOrDefault();
            if (adminModel == null) { rmsg = "您没有权限核销咖啡劵"; return ""; }

            var model = member_CoffeeLogRepository.GetList(new RB_Member_CoffeeLog_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, Code = code }).FirstOrDefault();
            if (model != null) { rmsg = "已核销咖啡劵"; return ""; }

            string Name = "";
            var uModel = education_EduSellRepository.GetEducationStuList(new Model.Extend.Education.RB_Education_EduSell_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userId }).FirstOrDefault();
            int Type;
            if (uModel != null)
            {
                Type = uModel.Type;
                if (uModel.Type == 1)
                {
                    Name = accountRepository.GetEmployeeListRepository(new Model.Extend.Education.Employee_ViewModel() { Id = uModel.EduSellId }).FirstOrDefault()?.EmployeeName ?? "";
                }
                else if (uModel.Type == 2)
                {
                    Name = accountRepository.GetStudentExt(new Model.Extend.Education.RB_Account_ViewModel() { Id = uModel.EduSellId, AccountType = 4 }).FirstOrDefault()?.AccountName ?? "";
                }
            }
            else
            {
                Type = 3;//甲鹤用户
                Name = CacheManager.User.UserReidsCache.GetAppletUserLoginInfo(userId)?.Name ?? "";
            }
            //获取用户的咖啡劵明细
            var mModel = member_CoffeeCouponsRepository.GetList(new RB_Member_CoffeeCoupons_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userId }).FirstOrDefault();
            if (mModel == null || (mModel.FreeNum <= 0 && mModel.SurplusBugNum <= 0)) {
                return new
                {
                    State = 2,
                    Msg = "该用户暂无可使用的咖啡劵"
                };
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>();
            if (mModel.FreeNum > 0)
            {
                //使用免费的核销
                keyValues.Add(nameof(RB_Member_CoffeeCoupons_Extend.FreeNum), mModel.FreeNum - 1);
            }
            else if (mModel.SurplusBugNum > 0) {
                //使用购买的
                keyValues.Add(nameof(RB_Member_CoffeeCoupons_Extend.SurplusBugNum), mModel.SurplusBugNum - 1);
            }
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_Member_CoffeeCoupons_Extend.Id),
                      FiledValue = mModel.Id,
                       OperatorEnum =OperatorEnum.Equal
                }
            };
            bool flag = member_CoffeeCouponsRepository.Update(keyValues, wheres);
            if (flag) {
                //增加消费记录
                member_CoffeeLogRepository.Insert(new RB_Member_CoffeeLog()
                {
                    Id = 0,
                    BuyType = mModel.FreeNum > 0 ? 1 : 2,
                    Code = code,
                    CreateBy = userInfo.UserId,
                    UserId = userId,
                    CreateDate = DateTime.Now,
                    MallBaseId = userInfo.MallBaseId,
                    Number = 1,
                    OrderId = 0,
                    Remark = mModel.FreeNum > 0 ? "使用赠送咖啡" : "使用购买星巴克咖啡",
                    Type = 2
                });
            }
            var umodel = member_UserRepository.GetEntity(userId);
            return new
            {
                State = 1,
                Number = 1,
                Type,
                Name,
                umodel.Photo
            };
        }

        /// <summary>
        /// 获取我的咖啡劵使用
        /// </summary>
        /// <param name="code"></param>
        /// <param name="userInfo"></param>
        /// <param name="rmsg"></param>
        /// <returns></returns>
        public object GetMyCoffeeVerificatInfo(string code, AppletUserInfo userInfo, out string rmsg)
        {
            rmsg = "";
            var model = member_CoffeeLogRepository.GetList(new RB_Member_CoffeeLog_Extend() { MallBaseId = userInfo.MallBaseId, UserId = userInfo.UserId, Code = code }).FirstOrDefault();
            if (model == null) { rmsg = "未检测到消费数据"; return ""; }
            return new
            {
                model.Id,
                model.BuyType,
                model.Number
            };
        }
    }
}
