using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Entity.BaseSetUp;
using Mall.Model.Entity.MarketingCenter;
using Mall.Model.Entity.User;
using Mall.Model.Extend.BaseSetUp;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Extend.User;
using Mall.Module.BaseSetUp;
using Mall.Module.MarketingCenter;
using Mall.Module.Product;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


namespace Mall.WebApi.Controllers.MallBase
{
    /// <summary>
    /// 小程序商城控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]

    public class MallController : BaseController
    {
        /// <summary>
        /// 商户账号处理类
        /// </summary>
        private readonly Module.User.TenantModule TenantModule = new Module.User.TenantModule();

        /// <summary>
        /// 商户小程序处理类
        /// </summary>
        private readonly Module.User.MiniProgramModule programModule = new Module.User.MiniProgramModule();


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

        /// <summary>
        /// 自定义模板处理类
        /// </summary>
        private readonly MiniprogramTemplateModule miniprogramTemplateModule = new MiniprogramTemplateModule();

        /// <summary>
        /// 产品处理类
        /// </summary>
        private readonly ProductModule productModule = new ProductModule();


        /// <summary>
        /// 用户处理类
        /// </summary>
        private readonly UserModule userModule = new UserModule();

        private readonly Module.MarketingCenter.CouponModule couponModule = new Module.MarketingCenter.CouponModule();

        /// <summary>
        /// 小程序页面处理类
        /// </summary>
        private Module.User.MiniProgramPageModule programPageModule = new Module.User.MiniProgramPageModule();

        /// <summary>
        /// 小程序首页
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetHome()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string MiniAppId = "";
            try
            {
                //小程序Id
                MiniAppId = RequestParm.MiniAppId;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex,"MallController_GetHome");
            }

            int page_id = parms.GetInt("page_id");
            //是否开启校园版【1-是】
            int isOpenSchool = parms.GetInt("open_school",0);
            //首页数据
            var homePage = new object();
            //底部导航
            var navbar = new object();
            //基础配置
            var setting = new object();
            //分销基础信息
            var share_setting = new object();
            //分销设置
            var share_setting_custom = new object();
            //商品分类样式
            var cat_style = new object();
            //授权页面
            var auth_page = new object();
            //用户信息
            var user_info = new object();
            //小程序
            var mall = new object();

            //直播海报配置
            var liveConfig = new object();

            //获取小程序信息
            var miniProgram = new RB_MiniProgram_Extend();
            if (MiniAppId != null && !string.IsNullOrEmpty(MiniAppId))
            {
                miniProgram = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend() { MiniAppId = MiniAppId }, isGetHomeData: true, isGetNav: 1);
                //基础配置
                setting = MallHelper.GetBasicSetting(miniProgram);

                //分销基础信息
                share_setting = MallHelper.GetDistributorBasicsInfo(miniProgram);
                //分销商设置
                share_setting_custom = MallHelper.GetDistributorCustomInfo(miniProgram);
            }

            #region 首页页面数据解析
            
            if (page_id > 0)
            {
                var targetPage = miniprogramPageTemplModule.GetMiniprogramPageTemplModule(new RB_Miniprogram_Page_Templ_Extend()
                {
                    MallBaseId = miniProgram.MallBaseId,
                    TenantId = miniProgram.TenantId,
                    Id = page_id
                }, isGetHome: false,isGetSchoolPage:false);
                List<object> list = new List<object>();
                //自定义首页
                if (targetPage != null && targetPage.Id > 0)
                {
                    //获取模板编号
                    string templateIds = string.Join(",", targetPage.DetailsList.Select(qitem => qitem.TemplateId));
                    var templateList = miniprogramTemplateModule.GetMiniprogramTemplateListModule(new Model.Extend.MarketingCenter.RB_Miniprogram_Template_Extend()
                    {
                        MallBaseId = miniProgram.MallBaseId,
                        TenantId = miniProgram.TenantId,
                        QIds = templateIds
                    }, IsAnalyzePlus: true);
                    //解析模板
                    foreach (var item in targetPage.DetailsList)
                    {
                        var templateData = new
                        {
                            id = item?.Id ?? 0,
                            name = item?.NavName ?? "",
                            data = new List<object>()
                        };
                        var templateModel = templateList?.Where(qitem => qitem.Id == item.TemplateId)?.FirstOrDefault();
                        if (templateModel != null && templateModel.ComponentDataList != null && templateModel.ComponentDataList.Count() > 0)
                        {
                            foreach (var subItem in templateModel.ComponentDataList)
                            {
                                templateData.data.Add(MallHelper.PlusDataToObject(subItem, (miniProgram?.TenantId ?? 0), miniProgram.MallBaseId, RequestParm.SmallShopsId));
                            }
                        }
                        var tempObj = new
                        {
                            id = item.Id,
                            name = item.NavName,
                            page_id = 0,
                            template_id = item.Id,
                            template = templateData
                        };
                        list.Add(tempObj);
                    }

                    homePage = new
                    {
                        id = miniProgram.MallBaseId,
                        title = miniProgram.MallName,
                        show_navs = targetPage.IsShowNav,
                        is_home_page = targetPage.IsHome,
                        navs = list
                    };
                }
            }
            else
            {
                if (miniProgram != null && miniProgram.MallBaseId > 0)
                {
                    RB_Miniprogram_Page_Templ_Extend selfHomePage = new RB_Miniprogram_Page_Templ_Extend();
                    if (isOpenSchool == 1)
                    {
                        selfHomePage = miniprogramPageTemplModule.GetMiniprogramPageTemplModule(new RB_Miniprogram_Page_Templ_Extend()
                        {
                            MallBaseId = miniProgram.MallBaseId,
                            TenantId = miniProgram.TenantId,
                        }, isGetHome: false,isGetSchoolPage:true);
                    }
                    //判断是否存在校园版首页
                    if (selfHomePage == null||(selfHomePage!=null && selfHomePage.Id<=0))
                    {
                        selfHomePage = miniprogramPageTemplModule.GetMiniprogramPageTemplModule(new RB_Miniprogram_Page_Templ_Extend()
                        {
                            MallBaseId = miniProgram.MallBaseId,
                            TenantId = miniProgram.TenantId,
                        }, isGetHome: true, isGetSchoolPage: false);
                    }
                    List<object> list = new List<object>();
                    //自定义首页
                    if (selfHomePage != null && selfHomePage.Id > 0)
                    {
                        //获取模板编号
                        string templateIds = string.Join(",", selfHomePage.DetailsList.Select(qitem => qitem.TemplateId));
                        var templateList = miniprogramTemplateModule.GetMiniprogramTemplateListModule(new Model.Extend.MarketingCenter.RB_Miniprogram_Template_Extend()
                        {
                            MallBaseId = miniProgram.MallBaseId,
                            TenantId = miniProgram.TenantId,
                            QIds = templateIds
                        }, IsAnalyzePlus: true);
                        //解析模板
                        int index = 0;
                        foreach (var item in selfHomePage.DetailsList)
                        {
                            var templateData = new
                            {
                                id = item?.Id ?? 0,
                                name = item?.NavName ?? "",
                                data = new List<object>()
                            };
                            var templateModel = templateList?.Where(qitem => qitem.Id == item.TemplateId)?.FirstOrDefault();
                            if (templateModel != null && templateModel.ComponentDataList != null && templateModel.ComponentDataList.Count() > 0)
                            {
                                foreach (var subItem in templateModel.ComponentDataList)
                                {
                                    templateData.data.Add(MallHelper.PlusDataToObject(subItem, (miniProgram?.TenantId ?? 0), miniProgram.MallBaseId, RequestParm.SmallShopsId));
                                }
                            }
                            var tempObj = new
                            {
                                id = item.Id,
                                name = (index == 0 ? "首页" : item.NavName),
                                page_id = 0,
                                template_id = item.Id,
                                template = templateData
                            };
                            list.Add(tempObj);
                            index++;
                        }

                        homePage = new
                        {
                            id = miniProgram.MallBaseId,
                            title = miniProgram.MallName,
                            show_navs = selfHomePage.IsShowNav,
                            is_home_page = selfHomePage.IsHome,
                            navs = list
                        };
                    }
                    //默认首页布局
                    else
                    {
                        //配置了首页
                        if (miniProgram.HomeDataList != null && miniProgram.HomeDataList.Count > 0)
                        {
                            var tempObj = MallHelper.DefaultHomepage(miniProgram);
                            list.Add(tempObj);
                            homePage = new
                            {
                                id = 0,
                                title = miniProgram.MallName,
                                show_navs = 0,
                                is_home_page = 0,
                                navs = list
                            };
                        }
                        //未配置自定义页面
                        else
                        {
                            homePage = new
                            {
                                id = miniProgram.MallBaseId,
                                title = miniProgram.MallName,
                                show_navs = 1,
                                is_home_page = 1,
                                navs = list
                            };
                        }
                    }
                }
            }
           
            #endregion

            #region 底部导航
            if (miniProgram != null && miniProgram.MallBaseId > 0)
            {
                //底部导航
                navbar = new
                {
                    //底部导航背景颜色
                    bottom_background_color = miniProgram.BottomNavBgColor,
                    //顶部导航背景颜色
                    top_background_color = miniProgram.TopNavBgColor,
                    //顶部标题文字颜色
                    top_text_color = miniProgram.TopNavWordColor,
                    //导航底部是否开启阴影效果(0-未开启，1-开启)
                    shadow = miniProgram.BottomNavIsShadow,
                    //导航栏
                    navs = miniProgram.BottomTagList.Select(qitem => new
                    {
                        active_color = qitem.CheckedColor,
                        active_icon = qitem.CheckedIcon,
                        color = qitem.DefaultColor,
                        text = qitem.TagName,
                        icon = qitem.DefaultIcon,
                        url = qitem.TagLink,
                        open_type = "redirect",
                        key = qitem.TagLink == "/pages/live/index" ? "live" : "",
                    }),
                };
            }
            #endregion

            #region 用户信息

            if (RequestParm.OpenId != null && !string.IsNullOrWhiteSpace(RequestParm.OpenId))
            {
                var memberModel = userModule.GetAppletUserCenterStatistics(RequestParm.OpenId);
                user_info = memberModel;
            }

            #endregion

            #region 商品分类样式
            var productCategoryStyle = productModule.GetProductCategoryStyleInfo(miniProgram.TenantId ?? 0, miniProgram.MallBaseId);
            cat_style = new
            {
                cat_style = productCategoryStyle?.Type,
                recommend_count = productCategoryStyle?.Style,
                cat_goods_count = productCategoryStyle?.CategoryNum,
                cat_goods_cols = productCategoryStyle?.RowNum
            };
            #endregion


            mall = new
            {
                id = miniProgram.MallBaseId,
                name = miniProgram.MallName,
                user_id = 0,
                created_at = miniProgram.CreateDate.HasValue ? miniProgram.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                updated_at = miniProgram.CreateDate.HasValue ? miniProgram.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                deleted_at = "0000-00-00 00:00:00",
                is_delete = miniProgram.Status,
                is_recycle = 0,
                is_disable = miniProgram.Status,
                expired_at = "0000-00-00 00:00:00",
                option = new List<object>(),
                setting,
            };

            #region 授权页面热区
            //授权页面热区
            var hotspotCancel = new object();
            var hotspotLogin = new object();
            if (miniProgram.AuthDataList != null && miniProgram.AuthDataList.Count > 0 && miniProgram.AuthDataList.Count == 2)
            {
                var first = miniProgram.AuthDataList[0];
                var second = miniProgram.AuthDataList[1];
                if (first.open_type == "login")
                {
                    hotspotLogin = first;
                    hotspotCancel = second;
                }
                else
                {
                    hotspotLogin = second;
                    hotspotCancel = first;
                }
            }
            else
            {
                hotspotLogin = new AuthItem()
                {
                    width = 224,
                    height = 80,
                    left = 340,
                    top = 566,
                    defaultX = 340,
                    defaultY = 566,
                    link = "",
                    open_type = "login"
                };
                hotspotCancel = new AuthItem()
                {
                    width = 224,
                    height = 80,
                    left = 84,
                    top = 566,
                    defaultX = 84,
                    defaultY = 566,
                    link = "",
                    open_type = "cancel"
                };
            }

            auth_page = new
            {
                pic_url = miniProgram.AuthUrl,
                hotspot = hotspotLogin,
                hotspot_cancel = hotspotCancel
            };
            #endregion

            var liveConfigModel = programModule.GetLiveConfigModule(new Model.Extend.AppletWeChat.RB_Live_Config_Extend() { MallBaseId = miniProgram.MallBaseId, TenantId = miniProgram.TenantId });
            liveConfig = new
            {
                liveConfigModel?.LiveQrCodeSize,
                liveConfigModel?.LiveBgImg,
                liveConfigModel?.LiveQrCodePaddingLeft,
                liveConfigModel?.LiveQrCodePaddingTop,
                liveConfigModel?.LiveQrCodeType,
            };
            var miniPageList = programPageModule.GetMiniprogram_Page_ListExtModule(new RB_MiniProgram_Page_Extend() { MallBaseId = RequestParm.MallBaseId });
            var objResult = new
            {
                mall,
                home_pages = homePage,
                navbar,
                user_info,
                share_setting,
                share_setting_custom,
                cat_style,
                auth_page,//授权页面
                liveConfig,
                bar_title = miniPageList?.Select(qitem => new { name = qitem.PageName, value = qitem.PageUrl, new_name = qitem.SelfPageName }),//导航标题
            };
            return ApiResult.Success(data: objResult);
        }

        /// <summary>
        /// 用户中心
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetUserCenter()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string MiniAppId = "";
            try
            {
                //小程序Id
                MiniAppId = RequestParm.MiniAppId;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "MallController_GetUserCenter");
            }
            //获取小程序信息
            var miniProgram = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend() { MiniAppId = MiniAppId }, isGetUserCenterMenu: true);
            var user_info = new object();
            if (RequestParm.OpenId != null && !string.IsNullOrWhiteSpace(RequestParm.OpenId))
            {
                var memberModel = userModule.GetAppletUserCenterStatistics(RequestParm.OpenId);
                user_info = memberModel;
              
            }

            var data = new object();
            if (miniProgram != null && miniProgram.MallBaseId > 0)
            {
                var config = new
                {
                    //顶部导航
                    title_bar = new
                    {
                        //顶部背景颜色
                        background = miniProgram.TopNavBgColor,
                        //顶部文字颜色
                        color = miniProgram.TopNavWordColor,
                    },
                    //用户中心
                    user_center = new
                    {
                        //是否显示账户栏
                        is_account_status = (miniProgram.IsShowAccountNav == 0 ? 1 : 0),
                        //是否显示菜单栏
                        is_menu_status = (miniProgram.IsShowMenuNav == 0 ? 1 : 0),
                        //是否显示菜单栏
                        is_order_bar_status = (miniProgram.IsShowOrderNav == 0 ? 1 : 0),
                        //是否显示收藏夹
                        is_foot_bar_status = (miniProgram.IsShowFavorite == 0 ? 1 : 0),
                        //菜单样式
                        menu_style = (miniProgram.MenuNavStyle == 0 ? 1 : 2),
                        //头像样式
                        top_style = (miniProgram.HeadStyle),
                        //顶部默认背景图
                        top_pic_url = miniProgram.DefaultBgImg,
                        //普通用户背景图
                        member_pic_url = miniProgram.MemberBgImg,
                        //会员中心背景图
                        member_bg_pic_url = miniProgram.VipBgImg,
                        //头像内嵌背景图[暂无]
                        style_bg_pic_url = "",

                        //账户相关菜单
                        account = miniProgram?.AccountMenuList?.Select(qitem => new
                        {
                            icon_url = qitem.MenuIcon,
                            name = qitem.MenuName.Replace("我的", "").Replace("明细", "").Replace("记录", ""),
                            is_show = 1,
                            link_url = qitem.MenuUrl.Trim(),
                        }),
                        //自定义菜单
                        menus = miniProgram?.SelfMenuList?.Select(qitem => new
                        {
                            icon_url = qitem.MenuIcon,
                            name = qitem.MenuName,
                            link_url = qitem.MenuUrl.Trim(),
                            open_type = "navigate",
                            @params = "",

                        }),
                        //订单菜单列表
                        order_bar = miniProgram?.OrderMenuList?.Select(qitem => new
                        {
                            icon_url = qitem.MenuIcon,
                            name = qitem.MenuName,
                            link_url = qitem.MenuUrl.Trim(),
                            open_type = "navigate",
                            text = "",
                        }),
                        //收藏足迹
                        foot_bar = miniProgram?.FavoriteFootMenuList?.Select(qitem => new
                        {
                            icon_url = qitem.MenuIcon,
                            name = qitem.MenuName,
                            link_url = qitem.MenuUrl.Trim(),
                            open_type = "navigate",
                        }),
                        //版权设置
                        copyright = new
                        {
                            pic_url = miniProgram.CopyRightImg,
                            description = miniProgram.CopyRightWord,
                            link_url =!string.IsNullOrWhiteSpace(miniProgram.CopyRightLink) ? miniProgram.CopyRightLink.Trim():"",
                        }
                    }
                };

                data = new
                {
                    mall = new
                    {
                        //商城编号
                        id = miniProgram.MallBaseId,
                        //商城名称
                        name = miniProgram.MallName,
                        //是否删除
                        is_delete = miniProgram.Status,
                        //是否回收
                        is_recycle = miniProgram.Is_Recycle,
                        //是否禁用
                        is_disable = miniProgram.Status
                    },
                    //配置信息
                    config,
                    //用户信息
                    user_info,
                };
            }
            return ApiResult.Success(data: data);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetUserInfo()
        {
            if (RequestParm.OpenId != null && !string.IsNullOrWhiteSpace(RequestParm.OpenId))
            {
                var memberModel = userModule.GetAppletUserCenterStatistics(RequestParm.OpenId);
                return ApiResult.Success(data: new { user_info = memberModel });
            }
            else
            {
                return ApiResult.Failed(message: "请获取用户OpenId");
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetWeChatOpenId()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string code = parms.GetStringValue("Code");
            string openId = "";
            if (RequestParm.MiniAppId != null && !string.IsNullOrWhiteSpace(RequestParm.MiniAppId))
            {
                var miniProgram = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend() { MiniAppId = RequestParm.MiniAppId });
                if (miniProgram != null && miniProgram.MallBaseId > 0)
                {
                    openId = Common.Plugin.WeiXinHelper.GetWeChatOpenId(miniProgram.MiniAppId, miniProgram.MiniAppSecret, code);
                }
            }
            return ApiResult.Success(data: openId);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetMessageTemplate()
        {
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            var result = new object();
            if (RequestParm.MiniAppId != null && !string.IsNullOrWhiteSpace(RequestParm.MiniAppId))
            {
                var miniProgram = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend() { MiniAppId = RequestParm.MiniAppId });
                if (miniProgram != null && miniProgram.MallBaseId > 0)
                {
                    result = Common.Plugin.WeiXinHelper.GetWeChatTemplateMessage(miniProgram.MiniAppId, miniProgram.MiniAppSecret);
                }
            }
            return ApiResult.Success(data: result);
        }



        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetGoosPoster()
        {
            string MiniAppId = "";
            try
            {
                //小程序Id
                MiniAppId = RequestParm.MiniAppId;
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetGoosPoster");
            }
            //获取小程序信息
            var miniProgram = new RB_MiniProgram_Extend();
            if (MiniAppId != null && !string.IsNullOrEmpty(MiniAppId))
            {
                miniProgram = programModule.GetMiniProgramModule(new Model.Extend.User.RB_MiniProgram_Extend() { MiniAppId = MiniAppId }, isGetHomeData: true, isGetNav: 1);
            }
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            int goodsId = parms.GetInt("goodsId");
            string path = parms.GetStringValue("path");
            //HK 2020-09-22新增【是否开启校园版分享-(1-开启)】
            int IsOpenSchool = parms.GetInt("IsOpenSchool",0);
            var obj = productModule.GetAppletGoodsShareInfo(goodsId, RequestParm.UserId, path, (miniProgram?.MallBaseId ?? 0),IsOpenSchool:IsOpenSchool);
            return ApiResult.Success(data: obj);
        }
    }
}