using System.Linq;
using Mall.Common.API;
using Microsoft.AspNetCore.Mvc;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Mall.Module.MarketingCenter;
using Newtonsoft.Json;
using Mall.Model.Query;
using System;
using Mall.Common.Plugin;
using System.Collections.Generic;
using Mall.Model.Extend.MarketingCenter;
using Newtonsoft.Json.Linq;
using Mall.Model.Entity.MarketingCenter;
using Mall.CacheManager.User;

namespace Mall.WebApi.Controllers.MarketingCenter
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class TemplateController : BaseController
    {
        /// <summary>
        /// 模板处理类
        /// </summary>
        private readonly Module.MarketingCenter.MiniprogramTemplateModule templateModule = new MiniprogramTemplateModule();

        /// <summary>
        /// 自定义页面处理类
        /// </summary>
        private readonly MiniprogramPageTemplModule miniprogramPageTemplModule = new MiniprogramPageTemplModule();

        /// <summary>
        /// 模板市场处理类
        /// </summary>
        private readonly TemplateMarketModule templateMarketModule = new TemplateMarketModule();

        #region 模板管理
        /// <summary>
        /// 新增修改小程序模板
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniTemplate()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Miniprogram_Template_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;
            if (extModel.ComponentDataList != null && extModel.ComponentDataList.Count > 0)
            {
                extModel.TemplateData = JsonConvert.SerializeObject(extModel.ComponentDataList);
            }
            Int32.TryParse(RequestParm.uid, out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.Status = 0;
            var flag = templateModule.SetMiniprogramTemplateModule(extModel);
            return flag ? ApiResult.Success(data: extModel.Id) : ApiResult.Failed();
        }

        /// <summary>
        /// 获取小程序模板实体
        /// </summary>
        /// <returns></returns>
        public ApiResult GetMiniTemplate()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id");
            var extModel = templateModule.GetMiniprogramTemplateModule(Id);
            if (extModel != null && extModel.Id > 0)
            {
                var obj = new
                {
                    extModel.Id,
                    extModel.TemplateName,
                    extModel.ComponentDataList,
                };
                return ApiResult.Success(data: obj);
            }
            return ApiResult.Failed(message: "参数错误");
        }

        /// <summary>
        /// 删除小程序模板
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniTemplate()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var Status = parms.GetInt("Status", 1);
            var flag = templateModule.RemoveMiniprogramTemplateModule(Id, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 小程序模板分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiniTemplatePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Miniprogram_Template_Extend>(parms.msg.ToString());
            query.TenantId = Convert.ToInt32(parms.uid);
            query.MallBaseId = parms.MallBaseId;

            var list = templateModule.GetMiniprogramTemplatePageListModule(pagelist.pageIndex, pagelist.pageSize, out long count, query);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }
        #endregion

        #region 自定义页面管理

        /// <summary>
        /// 小程序自定义页面分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiniprogramPageTemplPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Miniprogram_Page_Templ_Extend>(parms.msg.ToString());
            query.TenantId = Convert.ToInt32(parms.uid);
            query.MallBaseId = parms.MallBaseId;

            var list = miniprogramPageTemplModule.GetMiniprogramPageTemplPageListModule(pagelist.pageIndex, pagelist.pageSize, out long count, query);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 小程序自定义页面列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiniprogramPageTemplList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Miniprogram_Page_Templ_Extend>(parms.msg.ToString());
            query.TenantId = Convert.ToInt32(parms.uid);
            query.MallBaseId = parms.MallBaseId;
            var list = miniprogramPageTemplModule.GetMiniprogramPageTemplListModule(query);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 小程序自定义页面实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetMiniprogramPageTempl()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Miniprogram_Page_Templ_Extend>(RequestParm.msg.ToString());
            query.TenantId = Convert.ToInt32(RequestParm.uid);
            query.MallBaseId = RequestParm.MallBaseId;
            bool isGetHome = parms.GetBoolValue("isGetHome");
            var extModel = miniprogramPageTemplModule.GetMiniprogramPageTemplModule(query, isGetHome: isGetHome);
            return ApiResult.Success("", extModel);
        }

        /// <summary>
        /// 新增修改自定义页面
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniprogramPageTempl()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Miniprogram_Page_Templ_Extend>(RequestParm.msg.ToString());
            extModel.TenantId = RequestParm.TenantId;
            extModel.MallBaseId = RequestParm.MallBaseId;

            Int32.TryParse(RequestParm.uid, out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.Status = 0;
            var flag = miniprogramPageTemplModule.SetMiniprogramPageTemplModule(extModel);
            return flag ? ApiResult.Success(data: extModel.Id) : ApiResult.Failed();
        }

        /// <summary>
        /// 更新自定义页面状态
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniprogramPageTempl()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var Status = parms.GetInt("Status", 1);
            var flag = miniprogramPageTemplModule.RemoveMiniprogramPageTemplModule(Id, Status);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新模板禁用、启用
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniprogramPageTemplIsUse()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var IsUse = parms.GetInt("IsUse", 0);
            var flag = miniprogramPageTemplModule.SetMiniprogramPageTemplIsUseModule(Id, IsUse);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新模板是否设为首页
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniprogramPageTemplIsHome()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var IsHome = parms.GetInt("IsHome", 1);
            var flag = miniprogramPageTemplModule.SetMiniprogramPageTemplIsHomeModule(Id, IsHome, RequestParm.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }


        /// <summary>
        /// 更新模板是否设为校园版首页
        /// </summary>
        /// <returns></returns>
        public ApiResult SetMiniprogramPageSchoolIsHome()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var IsSchoolHomePage = parms.GetInt("IsSchoolHomePage", 1);
            var flag = miniprogramPageTemplModule.SetMiniprogramPageTemplSchoolIsHomeModule(Id, IsSchoolHomePage, RequestParm.MallBaseId);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新自定义页面状态
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveMiniprogramPageTemplDetails()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var flag = miniprogramPageTemplModule.RemoveMiniprogramPageTemplDetailsModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }
        #endregion

        #region 模板市场

        /// <summary>
        /// 模板市场分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTemplateMarketPageListModule()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            var query = JsonConvert.DeserializeObject<RB_Template_Market_Extend>(parms.msg.ToString());
            var list = templateMarketModule.GetTemplateMarketPageListModule(pagelist.pageIndex, pagelist.pageSize, out long count, query);
            if (list != null && list.Count > 0)
            {
                foreach (var item in list)
                {
                    if (item.CreateBy > 0)
                    {
                        item.CreateByName = UserReidsCache.GetUserLoginInfo(item.CreateBy)?.Account ?? "";
                    }
                }
            }
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 模板市场列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTemplateMarketList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Template_Market_Extend>(parms.msg.ToString());
            var list = templateMarketModule.GetTemplateMarketListModule(query);
            return ApiResult.Success("", list);
        }

        /// <summary>
        /// 根据编号获取模板市场实体
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetTemplateMarket()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var extModel = templateMarketModule.GetTemplateMarketModule(Id);
            return ApiResult.Success("", extModel);
        }

        /// <summary>
        /// 添加修改模板市场
        /// </summary>
        /// <returns></returns>
        public ApiResult SetTemplateMarket()
        {
            var extModel = JsonConvert.DeserializeObject<RB_Template_Market_Extend>(RequestParm.msg.ToString());
            Int32.TryParse(RequestParm.uid, out int Uid);
            extModel.CreateBy = Uid;
            extModel.CreateDate = DateTime.Now;
            extModel.Status = 0;
            var flag = templateMarketModule.SetTemplateMarketModule(extModel);
            return flag ? ApiResult.Success(data: extModel.Id) : ApiResult.Failed();
        }

        /// <summary>
        /// 删除模板市场
        /// </summary>
        /// <returns></returns>
        public ApiResult RemoveTemplateMarket()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var flag = templateMarketModule.RemoveTemplateMarketModule(Id);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新模板市场是否显示
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateTemplateMarketIsShow()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var IsShow = parms.GetInt("IsShow", 0);
            var flag = templateMarketModule.UpdateTemplateMarketIsShowModule(Id, IsShow);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 更新模板市场是否显示
        /// </summary>
        /// <returns></returns>
        public ApiResult UpdateTemplateMarketIsUse()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            var IsUse = parms.GetInt("IsUse", 0);
            var flag = templateMarketModule.UpdateTemplateMarketIsUseModule(Id, IsUse);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 加载模板
        /// </summary>
        /// <returns></returns>
        public ApiResult LoadTemplateMarket()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var Id = parms.GetInt("Id", 0);
            Int32.TryParse(RequestParm.uid, out int Uid);
            var extModel = new RB_Miniprogram_Template_Extend()
            {
                Id = 0,
                ComponentDataList = new List<ComponentItem>(),
                CreateBy = Uid,
                TenantId = RequestParm.TenantId,
                MallBaseId = RequestParm.MallBaseId,
                CreateDate = DateTime.Now,
                Status = 0
            };
            var flag = templateMarketModule.LoadTemplateMarketIsUseModule(Id, extModel);
            return flag ? ApiResult.Success(data: extModel) : ApiResult.Failed();
        }

        /// <summary>
        /// 重新设置图片
        /// </summary>
        /// <returns></returns>
        public ApiResult SetTemplateImg()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Template_Market_Extend>(parms.msg.ToString());
            var list = templateMarketModule.GetTemplateMarketListModule(query);
            string message = "";
            if (list != null && list.Count > 0)
            {
                foreach (var rootItem in list)
                {
                    if (rootItem.Pics != null && !string.IsNullOrEmpty(rootItem.Pics))
                    {
                        try
                        {
                            Common.Plugin.FileHelper.CreateImage(rootItem.Pics);
                            rootItem.Pics = Common.Plugin.FileHelper.GetFileUrl(rootItem.Pics);
                            rootItem.Pics = Common.Config.GetFileUrl(rootItem.Pics);
                        }
                        catch (Exception ex)
                        {
                            message += ex.Message + "   ";
                        }
                    }
                    List<ComponentItem> items = new List<ComponentItem>();
                    if (rootItem.TemplateData != null && !string.IsNullOrWhiteSpace(rootItem.TemplateData))
                    {
                        items = Common.Plugin.JsonHelper.DeserializeObject<List<ComponentItem>>(rootItem.TemplateData.Replace("\r\n", "").Replace(@"\", "").Trim());
                    }

                    if (items != null && items.Count > 0)
                    {
                        try
                        {
                            foreach (var item in items)
                            {
                                switch (item.Id)
                                {
                                    //背景组件
                                    case "background":
                                        var backgroundData = Common.Plugin.JsonHelper.DeserializeObject<backgroundItem>(item.data.ToString());
                                        if (!string.IsNullOrWhiteSpace(backgroundData.backgroundPicUrl))
                                        {
                                            Common.Plugin.FileHelper.CreateImage(backgroundData.backgroundPicUrl);
                                            backgroundData.backgroundPicUrl = Common.Plugin.FileHelper.GetFileUrl(backgroundData.backgroundPicUrl);
                                            backgroundData.backgroundPicUrl = Common.Config.GetFileUrl(backgroundData.backgroundPicUrl);
                                        }
                                        item.data = backgroundData;
                                        break;
                                    //查找组件
                                    case "search":
                                        break;
                                    //导航组件
                                    case "nav":
                                        var navData = Common.Plugin.JsonHelper.DeserializeObject<navItem>(item.data.ToString());
                                        if (navData.navs != null && navData.navs.Count > 0)
                                        {
                                            foreach (var subItem in navData.navs)
                                            {
                                                if (!string.IsNullOrWhiteSpace(subItem.icon))
                                                {
                                                    Common.Plugin.FileHelper.CreateImage(subItem.icon);
                                                    subItem.icon = Common.Plugin.FileHelper.GetFileUrl(subItem.icon);
                                                    subItem.icon = Common.Config.GetFileUrl(subItem.icon);
                                                }

                                            }
                                        }
                                        item.data = navData;
                                        break;
                                    //轮播广告插件
                                    case "banner":
                                        var bannerData = Common.Plugin.JsonHelper.DeserializeObject<bannerItem>(item.data.ToString());
                                        if (bannerData.banners != null && bannerData.banners.Count > 0)
                                        {
                                            foreach (var subItem in bannerData.banners)
                                            {
                                                if (!string.IsNullOrWhiteSpace(subItem.picUrl))
                                                {
                                                    Common.Plugin.FileHelper.CreateImage(subItem.picUrl);
                                                    subItem.picUrl = Common.Plugin.FileHelper.GetFileUrl(subItem.picUrl);
                                                    subItem.picUrl = Common.Config.GetFileUrl(subItem.picUrl);
                                                }

                                            }
                                        }
                                        item.data = bannerData;
                                        break;
                                    //图片广告插件
                                    case "rubik":
                                        try
                                        {
                                            var rubikData = Common.Plugin.JsonHelper.DeserializeObject<rubikItem>(item.data.ToString());
                                            if (rubikData.list != null && rubikData.list.Count > 0)
                                            {
                                                foreach (var subItem in rubikData.list)
                                                {
                                                    if (!string.IsNullOrWhiteSpace(subItem.pic_url))
                                                    {
                                                        Common.Plugin.FileHelper.CreateImage(subItem.pic_url);
                                                        subItem.pic_url = Common.Plugin.FileHelper.GetFileUrl(subItem.pic_url);
                                                        subItem.pic_url = Common.Config.GetFileUrl(subItem.pic_url);
                                                    }
                                                    if (!string.IsNullOrWhiteSpace(subItem.backgroundImage))
                                                    {
                                                        var newUrl = subItem.backgroundImage.Replace("url('", "").Replace("')", "");
                                                        Common.Plugin.FileHelper.CreateImage(newUrl);
                                                        subItem.backgroundImage = Common.Plugin.FileHelper.GetFileUrl(newUrl);
                                                        subItem.backgroundImage = "url('" + Common.Config.GetFileUrl(subItem.backgroundImage) + "')";
                                                    }
                                                }
                                            }
                                            item.data = rubikData;
                                        }
                                        catch
                                        {

                                        }
                                        break;

                                    //商品插件
                                    case "goods":
                                        var goodData = Common.Plugin.JsonHelper.DeserializeObject<goodsItem>(item.data.ToString());
                                        if (!string.IsNullOrWhiteSpace(goodData.goodsTagPicUrl))
                                        {
                                            Common.Plugin.FileHelper.CreateImage(goodData.goodsTagPicUrl);
                                            goodData.goodsTagPicUrl = Common.Plugin.FileHelper.GetFileUrl(goodData.goodsTagPicUrl);
                                            goodData.goodsTagPicUrl = Common.Config.GetFileUrl(goodData.goodsTagPicUrl);
                                        }
                                        item.data = goodData;
                                        break;
                                    //公告组件
                                    case "notice":
                                        var noticeData = Common.Plugin.JsonHelper.DeserializeObject<noticeItem>(item.data.ToString());
                                        if (!string.IsNullOrWhiteSpace(noticeData.icon))
                                        {
                                            Common.Plugin.FileHelper.CreateImage(noticeData.icon);
                                            noticeData.icon = Common.Plugin.FileHelper.GetFileUrl(noticeData.icon);
                                            noticeData.icon = Common.Config.GetFileUrl(noticeData.icon);
                                        }
                                        if (!string.IsNullOrWhiteSpace(noticeData.headerUrl))
                                        {
                                            Common.Plugin.FileHelper.CreateImage(noticeData.headerUrl);
                                            noticeData.headerUrl = Common.Plugin.FileHelper.GetFileUrl(noticeData.headerUrl);
                                            noticeData.headerUrl = Common.Config.GetFileUrl(noticeData.headerUrl);
                                        }
                                        item.data = noticeData;
                                        break;
                                    //商品插件
                                    case "storeGoods":
                                        var storeGoodData = Common.Plugin.JsonHelper.DeserializeObject<StoreGoodsItem>(item.data.ToString());
                                        if (!string.IsNullOrWhiteSpace(storeGoodData.goodsTagPicUrl))
                                        {
                                            Common.Plugin.FileHelper.CreateImage(storeGoodData.goodsTagPicUrl);
                                            storeGoodData.goodsTagPicUrl = Common.Plugin.FileHelper.GetFileUrl(storeGoodData.goodsTagPicUrl);
                                            storeGoodData.goodsTagPicUrl = Common.Config.GetFileUrl(storeGoodData.goodsTagPicUrl);
                                        }
                                        item.data = storeGoodData;
                                        break;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            message += rootItem.Id + "  " + ex.Message + "   ";
                        }
                    }
                    rootItem.TemplateData = Common.Plugin.JsonHelper.Serialize(items);
                    templateMarketModule.SetTemplateMarketModule(rootItem);
                }
            }
            return ApiResult.Success(message: message);
        }
        #endregion
    }
}