using Mall.Common.Plugin;
using Mall.Model.Entity.MarketingCenter;
using Mall.Model.Entity.User;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Extend.User;
using Mall.Model.Query;
using Mall.Repository;
using Mall.Repository.MarketingCenter;
using MySqlX.XDevAPI.Relational;
using Newtonsoft.Json.Linq;
using Org.BouncyCastle.Crypto.Tls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VT.FW.DB;

namespace Mall.Module.MarketingCenter
{
    /// <summary>
    /// 小程序模板处理类
    /// </summary>
    public class MiniprogramTemplateModule
    {
        /// <summary>
        /// 小程序模板仓储层对象
        /// </summary>
        private readonly RB_Miniprogram_TemplateRepository miniprogram_TemplateRepository = new RB_Miniprogram_TemplateRepository();

        /// <summary>
        /// 小程序模板分页列表
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页显示条数</param>
        /// <param name="rowCount">总条数</param>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public List<RB_Miniprogram_Template_Extend> GetMiniprogramTemplatePageListModule(int pageIndex, int pageSize, out long rowCount, RB_Miniprogram_Template_Extend query)
        {
            return miniprogram_TemplateRepository.GetMiniprogramTemplatePageListRepository(pageIndex, pageSize, out rowCount, query);
        }


        /// <summary>
        /// 小程序模板列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <param name="IsAnalyzePlus">是否解析插件</param>
        /// <returns></returns>
        public List<RB_Miniprogram_Template_Extend> GetMiniprogramTemplateListModule(RB_Miniprogram_Template_Extend query, bool IsAnalyzePlus = false)
        {
            var list = miniprogram_TemplateRepository.GetMiniprogramTemplateListRepository(query);
            if (IsAnalyzePlus)
            {
                foreach (var item in list)
                {
                    if (item.TemplateData != null && !string.IsNullOrEmpty(item.TemplateData))
                    {
                        item.ComponentDataList = JsonHelper.DeserializeObject<List<ComponentItem>>(Mall.Common.ConvertHelper.JsonReplaceSign(item.TemplateData));
                        if (item.ComponentDataList != null && item.ComponentDataList.Count > 0)
                        {
                            foreach (var subItem in item.ComponentDataList)
                            {
                                AnalyzePlusModule(subItem);
                            }
                        }
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 新增修改小程序模板
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        public bool SetMiniprogramTemplateModule(RB_Miniprogram_Template_Extend extModel)
        {
            bool flag = false;
            if (extModel.Id > 0)
            {
                Dictionary<string, object> fileds = new Dictionary<string, object>()
                {
                    {nameof(RB_Miniprogram_Template_Extend.Id),extModel.Id }
                };
                fileds.Add(nameof(RB_Miniprogram_Template_Extend.TemplateName), extModel.TemplateName);
                fileds.Add(nameof(RB_Miniprogram_Template_Extend.TemplateData), extModel.TemplateData);
                flag = miniprogram_TemplateRepository.Update(fileds, new WhereHelper(nameof(RB_Miniprogram_Template_Extend.Id), extModel.Id));
            }
            else
            {
                var newId = miniprogram_TemplateRepository.Insert(extModel);
                extModel.Id = newId;
                flag = newId > 0;
            }
            return flag;
        }

        /// <summary>
        /// 获取小程序模板实体
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public RB_Miniprogram_Template_Extend GetMiniprogramTemplateModule(object Id)
        {
            RB_Miniprogram_Template_Extend extModel = miniprogram_TemplateRepository.GetEntity<RB_Miniprogram_Template_Extend>(Id);
            if (extModel == null)
            {
                extModel = new RB_Miniprogram_Template_Extend();
            }
            if (extModel.TemplateData != null && !string.IsNullOrEmpty(extModel.TemplateData))
            {
                extModel.ComponentDataList = JsonHelper.DeserializeObject<List<ComponentItem>>(Common.ConvertHelper.JsonReplaceSign(extModel.TemplateData));
                if (extModel.ComponentDataList != null && extModel.ComponentDataList.Count > 0)
                {
                    foreach (var item in extModel.ComponentDataList)
                    {
                        AnalyzePlusModule(item);
                    }
                }
            }
            return extModel;
        }

        /// <summary>
        /// 解析插件
        /// </summary>
        /// <param name="item"></param>
        public void AnalyzePlusModule(ComponentItem item)
        {
            switch (item.Id)
            {
                //背景组件
                case "background": item.data = JsonHelper.DeserializeObject<backgroundItem>(item.data.ToString()); break;
                //查找组件
                case "search": item.data = JsonHelper.DeserializeObject<searchItem>(item.data.ToString()); break;
                //导航组件
                case "nav": item.data = JsonHelper.DeserializeObject<navItem>(item.data.ToString()); break;
                //轮播广告插件
                case "banner": item.data = JsonHelper.DeserializeObject<bannerItem>(item.data.ToString()); break;
                //公告组件
                case "notice": item.data = JsonHelper.DeserializeObject<noticeItem>(item.data.ToString()); break;
                //专题
                case "topic": item.data = JsonHelper.DeserializeObject<topicItem>(item.data.ToString()); break;
                //标题组件
                case "link": item.data = JsonHelper.DeserializeObject<linkItem>(item.data.ToString()); break;
                //图片广告插件
                case "rubik":
                    JObject jObj = JObject.Parse(item.data.ToString());
                    Int32.TryParse(jObj["style"].ToString(), out int style);
                    Int32.TryParse(jObj["space"].ToString(), out int space);
                    Int32.TryParse(jObj["h"].ToString(), out int h_root);
                    Int32.TryParse(jObj["w"].ToString(), out int w_root);
                    var subData = new rubikItem()
                    {
                        style = style,
                        space = space,
                        height = jObj["height"].ToString(),
                        w = w_root.ToString(),
                        h = h_root,
                        hotspot = new List<hotspotItem>(),
                        list = new List<rubikDetailItem>(),
                        left=jObj.ContainsKey("left")? jObj["left"].ToString():"0",
                        right = jObj.ContainsKey("right") ? jObj["right"].ToString():"0",
                        top = jObj.ContainsKey("top") ? jObj["top"].ToString():"0",
                        bottom = jObj.ContainsKey("bottom") ? jObj["bottom"].ToString():"0",
                        background= jObj.ContainsKey("background") ? jObj["background"].ToString():"",
                    };

                    if (!string.IsNullOrWhiteSpace(jObj["hotspot"].ToString()))
                    {
                        subData.hotspot = Common.Plugin.JsonHelper.DeserializeObject<List<hotspotItem>>(jObj["hotspot"].ToString());
                    }
                    if (!string.IsNullOrWhiteSpace(jObj["list"].ToString()))
                    {
                        JArray jArray = JArray.Parse(jObj["list"].ToString());
                        if (jArray != null && jArray.Count > 0)
                        {
                            foreach (var subItem in jArray)
                            {
                                Int32.TryParse(subItem["w"].ToString(), out int w);
                                Int32.TryParse(subItem["h"].ToString(), out int h2);
                                Int32.TryParse(subItem["x"].ToString(), out int x);
                                Int32.TryParse(subItem["y"].ToString(), out int y);
                                int zIndex = 0;
                                if (subItem["zIndex"] != null && !string.IsNullOrWhiteSpace(subItem["zIndex"].ToString()))
                                {
                                    Int32.TryParse(subItem["zIndex"].ToString(), out  zIndex);
                                }
                                var links = new List<rubikLinkItem>();
                                if (subItem["link"] != null && !string.IsNullOrWhiteSpace(subItem["link"].ToString()))
                                {
                                    try
                                    {
                                        var linkObj = JObject.Parse(subItem["link"].ToString());
                                        links.Add(new rubikLinkItem()
                                        {
                                            PageName = linkObj["name"].ToString(),
                                            PageUrl = linkObj["value"].ToString(),
                                            new_link_url = linkObj["new_link_url"].ToString(),
                                            IsParameter = 0,
                                            ParameterValue = linkObj["name"].ToString(),
                                        });
                                    }
                                    catch
                                    {

                                    }
                                    try
                                    {
                                        var linkArray = JArray.Parse(subItem["link"].ToString());
                                        if (linkArray != null && linkArray.Count > 0)
                                        {
                                            foreach (var linkItem in linkArray)
                                            {
                                                var linkModel = new rubikLinkItem() { IsParameter = 0 };
                                                if (linkItem["name"] != null && !string.IsNullOrWhiteSpace(linkItem["name"].ToString()))
                                                {
                                                    linkModel.PageName = linkItem["name"].ToString();
                                                }
                                                if (string.IsNullOrWhiteSpace(linkModel.PageName))
                                                {
                                                    linkModel.PageName = linkItem["PageName"].ToString();
                                                }
                                                if (linkItem["value"] != null && !string.IsNullOrWhiteSpace(linkItem["value"].ToString()))
                                                {
                                                    linkModel.PageUrl = linkItem["value"].ToString();
                                                }
                                                if (string.IsNullOrWhiteSpace(linkModel.PageUrl))
                                                {
                                                    linkModel.PageUrl = linkItem["PageUrl"].ToString();
                                                }
                                                if (linkItem["new_link_url"] != null && !string.IsNullOrWhiteSpace(linkItem["new_link_url"].ToString()))
                                                {
                                                    linkModel.new_link_url = linkItem["new_link_url"].ToString();
                                                }
                                                if (string.IsNullOrWhiteSpace(linkModel.new_link_url))
                                                {
                                                    linkModel.new_link_url = linkItem["PageUrl"].ToString();
                                                }
                                                if (linkItem["name"] != null && !string.IsNullOrWhiteSpace(linkItem["name"].ToString()))
                                                {
                                                    linkModel.ParameterValue = linkItem["name"].ToString();
                                                }
                                                if (string.IsNullOrWhiteSpace(linkModel.ParameterValue))
                                                {
                                                    linkModel.ParameterValue = linkItem["ParameterValue"].ToString();
                                                }
                                                links.Add(linkModel);
                                            }
                                        }
                                    }
                                    catch
                                    {
                                       
                                    }
                                }
                                subData.list.Add(new rubikDetailItem()
                                {
                                    w = w,
                                    h = h2,
                                    x = x,
                                    y = y,
                                    link = links,
                                    width = subItem["width"].ToString(),
                                    height = subItem["height"].ToString(),
                                    left = subItem["left"].ToString(),
                                    top = subItem["top"].ToString(),
                                    pic_url = Common.Config.GetFileUrl(subItem["pic_url"].ToString()) ,
                                    backgroundImage = subItem["backgroundImage"].ToString(),
                                    backgroundRepeat = subItem["backgroundRepeat"].ToString(),
                                    backgroundSize = subItem["backgroundSize"].ToString(),
                                    backgroundPosition = subItem["backgroundPosition"].ToString(),
                                    zIndex = zIndex
                                }); ;
                            }
                        }
                    }
                    item.data = subData;
                    break;
                //视频插件
                case "video": item.data = JsonHelper.DeserializeObject<videoItem>(item.data.ToString()); break;
                //商品插件
                case "goods": item.data = JsonHelper.DeserializeObject<goodsItem>(item.data.ToString()); break;
                //门店插件
                case "store": item.data = JsonHelper.DeserializeObject<storeItem>(item.data.ToString()); break;
                //版权插件
                case "copyright": item.data = JsonHelper.DeserializeObject<copyrightItem>(item.data.ToString()); break;
                //签到插件
                case "check-in": item.data = JsonHelper.DeserializeObject<checkinItem>(item.data.ToString()); break;
                //用户信息插件
                case "user-info": item.data = JsonHelper.DeserializeObject<userinfoItem>(item.data.ToString()); break;
                //用户订单插件
                case "user-order": item.data = JsonHelper.DeserializeObject<userorderItem>(item.data.ToString()); break;
                //地图插件
                case "map": item.data = JsonHelper.DeserializeObject<mapItem>(item.data.ToString()); break;
                //微信公众号插件
                case "mp-link": item.data = JsonHelper.DeserializeObject<mplinkItem>(item.data.ToString()); break;
                //图文插件
                case "image-text": item.data = JsonHelper.DeserializeObject<imagetextItem>(item.data.ToString()); break;
                //优惠券插件
                case "coupon": item.data = JsonHelper.DeserializeObject<couponItem>(item.data.ToString()); break;
                //倒计时插件
                case "timer": item.data = JsonHelper.DeserializeObject<timerItem>(item.data.ToString()); break;
                //拼团插件
                case "pintuan": item.data = JsonHelper.DeserializeObject<pintuanItem>(item.data.ToString()); break;
                //预约插件
                case "booking": item.data = JsonHelper.DeserializeObject<bookingItem>(item.data.ToString()); break;
                //砍价插件
                case "bargain": item.data = JsonHelper.DeserializeObject<bargainItem>(item.data.ToString()); break;
                //积分商城插件
                case "integral-mall": item.data = JsonHelper.DeserializeObject<integralmallItem>(item.data.ToString()); break;
                //抽奖插件
                case "lottery": item.data = JsonHelper.DeserializeObject<lotteryItem>(item.data.ToString()); break;
                //预售
                case "advance": item.data = JsonHelper.DeserializeObject<advanceItem>(item.data.ToString()); break;
                //超级会员卡
                case "vip-card": item.data = JsonHelper.DeserializeObject<vipcardItem>(item.data.ToString()); break;
                //直播组件
                case "live": item.data = JsonHelper.DeserializeObject<liveItem>(item.data.ToString()); break;
                //空白块组件
                case "empty": item.data = JsonHelper.DeserializeObject<emptyItem>(item.data.ToString()); break;
                //流量主广告
                case "ad": item.data = JsonHelper.DeserializeObject<adItem>(item.data.ToString()); break;
                //弹窗广告
                case "modal": item.data = JsonHelper.DeserializeObject<modalItem>(item.data.ToString()); break;
                //快捷导航
                case "quick-nav": item.data = JsonHelper.DeserializeObject<quicknavItem>(item.data.ToString()); break;
            }
        }

        /// <summary>
        /// 删除小程序模板
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        public bool RemoveMiniprogramTemplateModule(object Id, int Status)
        {
            bool flag = false;
            Dictionary<string, object> fileds = new Dictionary<string, object>()
            {
                {nameof(RB_Miniprogram_Template_Extend.Status),Status }
            };
            flag = miniprogram_TemplateRepository.Update(fileds, new WhereHelper(nameof(RB_Miniprogram_Template_Extend.Id), Id));
            return flag;
        }
    }
}
