using System;
using System.Collections.Generic;
using System.Linq;
using Mall.Common;
using Mall.Common.Plugin;
using Newtonsoft.Json;
using VT.FW.DB;
using Mall.Repository.Assess;
using Mall.Model.Extend.Assess;
using Mall.Model.Entity.Assess;
using Mall.Repository.User;
using Mall.Module.User;

namespace Mall.Module.Miai
{
    /// <summary>
    /// 估价处理层
    /// </summary>
    public class AssessModule
    {
        

        /// <summary>
        /// 用户管理
        /// </summary>
        private readonly RB_Member_UserRepository member_UserRepository = new RB_Member_UserRepository();
        /// <summary>
        /// 分类
        /// </summary>
        private readonly RB_Assess_CategoryRepository assess_CategoryRepository = new RB_Assess_CategoryRepository();
        /// <summary>
        /// 品牌
        /// </summary>
        private readonly RB_Assess_BrandRepository assess_BrandRepository = new RB_Assess_BrandRepository();
        /// <summary>
        /// 商品
        /// </summary>
        private readonly RB_Assess_GoodsRepository assess_GoodsRepository = new RB_Assess_GoodsRepository();
        /// <summary>
        /// 消息订阅
        /// </summary>
        private readonly MiniProgramMsgModule appletWeChatModule = new MiniProgramMsgModule();


        #region 估价分类

        /// <summary>
        /// 获取分类分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Assess_Category_Extend> GetCategoryPageList(int pageIndex, int pageSize, out long count, RB_Assess_Category_Extend demodel)
        {
            return assess_CategoryRepository.GetPageList(pageIndex, pageSize, out count, demodel);
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Assess_Category_Extend> GetCategoryList(RB_Assess_Category_Extend demodel)
        {
            return assess_CategoryRepository.GetList(demodel);
        }

        /// <summary>
        /// 保存修改分类
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetCategoryInfo(RB_Assess_Category_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                var dmodel = assess_CategoryRepository.GetEntity(demodel.Id);
                dmodel.Name = demodel.Name;
                dmodel.Image = demodel.Image;
                dmodel.Enable = demodel.Enable;
                dmodel.Sort = demodel.Sort;
                dmodel.UpdateBy = demodel.UpdateBy;
                dmodel.UpdateDate = demodel.UpdateDate;
                bool flag = assess_CategoryRepository.Update(dmodel);
                return flag ? "" : "出错了，请联系管理员";
            }
            else {
                bool flag = assess_CategoryRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }        

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="categoryId"></param>
        /// <returns></returns>
        public bool DelCategoryInfo(int categoryId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Assess_Category_Extend.Status),1},
                { nameof(RB_Assess_Category_Extend.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_Assess_Category_Extend.Id),
                      FiledValue = categoryId,
                       OperatorEnum =OperatorEnum.Equal
                }
            };
            return assess_CategoryRepository.Update(keyValues, wheres);
        }

        #endregion

        #region 品牌

        /// <summary>
        /// 获取品牌分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Assess_Brand_Extend> GetBrandPageList(int pageIndex, int pageSize, out long count, RB_Assess_Brand_Extend demodel)
        {
            var list = assess_BrandRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any()) {
                foreach (var item in list)
                {
                    item.BrandImgList = new List<AssessBrandImg>();
                    if (!string.IsNullOrEmpty(item.BrandImg))
                    {
                        item.BrandImgList = JsonHelper.DeserializeObject<List<AssessBrandImg>>(item.BrandImg);
                        item.BrandImgList = item.BrandImgList.Where(x => !string.IsNullOrEmpty(x.Name)).ToList();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取品牌列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Assess_Brand_Extend> GetBrandList(RB_Assess_Brand_Extend demodel)
        {
            var list = assess_BrandRepository.GetList(demodel);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.BrandImgList = new List<AssessBrandImg>();
                    if (!string.IsNullOrEmpty(item.BrandImg))
                    {
                        item.BrandImgList = JsonHelper.DeserializeObject<List<AssessBrandImg>>(item.BrandImg);
                        item.BrandImgList = item.BrandImgList.Where(x => !string.IsNullOrEmpty(x.Name)).ToList();
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 获取品牌分组列表
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public object GetBrandGroupList(RB_Assess_Brand_Extend demodel)
        {
            List<object> RList = new List<object>();
            var list = assess_BrandRepository.GetList(demodel);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.BrandImgList = new List<AssessBrandImg>();
                    if (!string.IsNullOrEmpty(item.BrandImg))
                    {
                        item.BrandImgList = JsonHelper.DeserializeObject<List<AssessBrandImg>>(item.BrandImg);
                        item.BrandImgList = item.BrandImgList.Where(x => !string.IsNullOrEmpty(x.Name)).ToList();
                    }
                }

                RList.Add(
                new
                {
                    letter = "*",
                    data = list.Where(x => x.IsHot == 1).Take(9).Select(x => new
                    {

                        x.Id,
                        x.Name,
                        x.PinYin,
                        x.Logo,
                        x.IsHot,
                        x.BrandImgList,
                        x.MoreDesc,
                        x.RemarkDesc
                    })
                });
                list.Where(x => !string.IsNullOrEmpty(x.PinYin)).GroupBy(x => x.PinYin).OrderBy(x => x.Key).ToList().ForEach(item =>
                 {
                     RList.Add(new
                     {
                         letter = item.Key,
                         data = item.Select(x => new
                         {

                             x.Id,
                             x.Name,
                             x.PinYin,
                             x.Logo,
                             x.IsHot,
                             x.BrandImgList,
                             x.MoreDesc,
                             x.RemarkDesc
                         })
                     });
                 });
                if (list.Where(x => string.IsNullOrEmpty(x.PinYin)).Any())
                {
                    RList.Add(new
                    {
                        letter = "#",
                        data = list.Where(x => string.IsNullOrEmpty(x.PinYin)).Select(x => new
                        {

                            x.Id,
                            x.Name,
                            x.PinYin,
                            x.Logo,
                            x.IsHot,
                            x.BrandImgList,
                            x.MoreDesc,
                            x.RemarkDesc
                        })
                    });
                }
            }
            return RList;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="brandId"></param>
        /// <returns></returns>
        public RB_Assess_Brand_Extend GetBrandInfo(int brandId)
        {
            var model = assess_BrandRepository.GetEntity<RB_Assess_Brand_Extend>(brandId);
            if (model != null) {
                if (!string.IsNullOrEmpty(model.BrandImg))
                {
                    model.BrandImgList = JsonHelper.DeserializeObject<List<AssessBrandImg>>(model.BrandImg);
                    model.BrandImgList = model.BrandImgList.Where(x => !string.IsNullOrEmpty(x.Name)).ToList();
                }
                model.CategoryName = assess_CategoryRepository.GetEntity(model.CategoryId)?.Name ?? "";
            }
            return model;
        }

        /// <summary>
        /// 新增修改品牌
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetBrandInfo(RB_Assess_Brand_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                var dmodel = assess_BrandRepository.GetEntity(demodel.Id);
                if (dmodel.Name != demodel.Name) {
                    dmodel.PinYin = StringHelper.GetPinyin(demodel.Name);
                    if (!string.IsNullOrEmpty(dmodel.PinYin))
                    {
                        dmodel.PinYin = dmodel.PinYin.Substring(0, 1).ToUpper();
                    }
                }
                dmodel.Name = demodel.Name;
                dmodel.CategoryId = demodel.CategoryId;
                dmodel.Logo = demodel.Logo;

                dmodel.IsHot = demodel.IsHot;
                dmodel.BrandImg = demodel.BrandImg;
                dmodel.MoreDesc = demodel.MoreDesc;
                dmodel.RemarkDesc = demodel.RemarkDesc;
                dmodel.UpdateBy = demodel.UpdateBy;
                dmodel.UpdateDate = demodel.UpdateDate;
                bool flag = assess_BrandRepository.Update(dmodel);
                return flag ? "" : "出错了，请联系管理员";
            }
            else
            {
                demodel.PinYin = StringHelper.GetPinyin(demodel.Name);
                if (!string.IsNullOrEmpty(demodel.PinYin))
                {
                    demodel.PinYin = demodel.PinYin.Substring(0, 1);
                }
                bool flag = assess_BrandRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 删除品牌
        /// </summary>
        /// <param name="BrandId"></param>
        /// <returns></returns>
        public bool DelBrandInfo(int BrandId)
        {
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Assess_Brand_Extend.Status),1},
                { nameof(RB_Assess_Brand_Extend.UpdateDate),DateTime.Now},
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                     FiledName = nameof(RB_Assess_Brand_Extend.Id),
                      FiledValue = BrandId,
                       OperatorEnum =OperatorEnum.Equal
                }
            };
            return assess_BrandRepository.Update(keyValues, wheres);
        }
        #endregion

        #region 我的估价

        /// <summary>
        /// 获取估价商品分页列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public List<RB_Assess_Goods_Extend> GetGoodsPageList(int pageIndex, int pageSize, out long count, RB_Assess_Goods_Extend demodel)
        {
            var list = assess_GoodsRepository.GetPageList(pageIndex, pageSize, out count, demodel);
            if (list.Any())
            {
                foreach (var item in list)
                {
                    item.GoodsImgList = new List<AssessBrandImg>();
                    item.MoreImgList = new List<AssessBrandImg>();
                    if (!string.IsNullOrEmpty(item.GoodsImg))
                    {
                        item.GoodsImgList = JsonHelper.DeserializeObject<List<AssessBrandImg>>(item.GoodsImg);
                    }
                    if (!string.IsNullOrEmpty(item.MoreImg))
                    {
                        item.MoreImgList = JsonHelper.DeserializeObject<List<AssessBrandImg>>(item.MoreImg);
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 保存估价
        /// </summary>
        /// <param name="demodel"></param>
        /// <returns></returns>
        public string SetGoodsInfo(RB_Assess_Goods_Extend demodel)
        {
            if (demodel.Id > 0)
            {
                Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                    { nameof(RB_Assess_Goods_Extend.GoodsImg), demodel.GoodsImg},
                    { nameof(RB_Assess_Goods_Extend.MoreImg), demodel.MoreImg},
                    { nameof(RB_Assess_Goods_Extend.Remark), demodel.Remark}
                };
                List<WhereHelper> wheres = new List<WhereHelper>() {
                    new WhereHelper(){
                         FiledName = nameof(RB_Assess_Goods_Extend.Id),
                          FiledValue = demodel.Id,
                           OperatorEnum=OperatorEnum.Equal
                    }
                };
                bool flag = assess_GoodsRepository.Update(keyValues, wheres);
                return flag ? "" : "出错了，请联系管理员";
            }
            else
            {
                bool flag = assess_GoodsRepository.Insert(demodel) > 0;
                return flag ? "" : "出错了，请联系管理员";
            }
        }

        /// <summary>
        /// 设置回复
        /// </summary>
        /// <param name="goodsId"></param>
        /// <param name="replyContent"></param>
        /// <returns></returns>
        public bool SetGoodsReply(int goodsId, string replyContent, UserInfo userInfo)
        {
            var goodsModel = assess_GoodsRepository.GetEntity(goodsId);
            if (goodsModel == null) {
                return false;
            }
            Dictionary<string, object> keyValues = new Dictionary<string, object>() {
                { nameof(RB_Assess_Goods_Extend.ReplyContent), replyContent},
                { nameof(RB_Assess_Goods_Extend.ReplyDate), DateTime.Now}
            };
            List<WhereHelper> wheres = new List<WhereHelper>() {
                new WhereHelper(){
                        FiledName = nameof(RB_Assess_Goods_Extend.Id),
                        FiledValue = goodsId,
                        OperatorEnum=OperatorEnum.Equal
                }
            };
            bool flag = assess_GoodsRepository.Update(keyValues, wheres);
            if (flag) {

                //获取用户信息
                var umodel = member_UserRepository.GetEntity(goodsModel.UserId);
                var categoryModel = assess_CategoryRepository.GetEntity(goodsModel.CategoryId);
                var brandModel = assess_BrandRepository.GetEntity(goodsModel.BrandId);
                string Title = categoryModel.Name + "-" + brandModel.Name;
                if (Title.Length > 20)
                {
                    Title = Title.Substring(0, 18) + "..";
                }
                string Remark = "您的商品估价已完成、点击可查看详情";
                //推送订阅消息
                appletWeChatModule.SendAssessSucceedMsg(userInfo.TenantId, userInfo.MallBaseId, umodel.OpenId, Title, DateTime.Now.ToString("yyyy-MM-dd HH:mm"), Remark);
            }
            return flag;
        }

        #endregion
    }
}