using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Extend.AppletWeChat;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Mall.WebApi.Controllers.AppletWeChat
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class PublishController : BaseController
    {

        private readonly MiniProgramModule appletWeChatModule = new MiniProgramModule();
        readonly string projectUrl = Mall.Common.Config.ProjectUrl;
        readonly string developerKitsPort = Mall.Common.Config.DeveloperKitsPort;
        readonly string FirstPage = Mall.Common.Config.FirstPage;

        public ApiResult UpdateSetting()
        {
            var parms = RequestParm;
            var query = new RB_MiniProgram_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };
            //读取小程序的配置文件
            string path = projectUrl + "/miniProject/common/vendor.js";
            string jsonpath = projectUrl + "/miniProject/project.config.json";


            string basePath = projectUrl + "/vendorbase.js";
            string jsonbasePath = projectUrl + "/project.configbase.json";
            var model = appletWeChatModule.GetTenantListModule(query).FirstOrDefault();
            if (System.IO.File.Exists(path) && System.IO.File.Exists(jsonpath))
            {
                try
                {
                    if (model.LivePlayerPlugin == 1)
                    {
                        path = projectUrl + "/miniProjectLive/common/vendor.js";
                        jsonpath = projectUrl + "/miniProjectLive/project.config.json";
                    }
                    string txtStr = System.IO.File.ReadAllText(basePath);
                    string newStr = txtStr.Replace("$MallBaseId$", query.MallBaseId.ToString()).Replace("$TenantId$", query.TenantId.ToString()).Replace("$MiniAppId$", model.MiniAppId);
                    System.IO.File.WriteAllText(path, newStr);

                    string txtStrjson = System.IO.File.ReadAllText(jsonbasePath);
                    string newStrjson = txtStrjson.Replace("$MiniAppId$", model.MiniAppId);
                    System.IO.File.WriteAllText(jsonpath, newStrjson);

                    return ApiResult.Success("基础信息配置成功");
                }
                catch (Exception ex)
                {

                    return ApiResult.Failed(ex.ToString());
                }
            }
            else
            {
                return ApiResult.Failed("配置文件不存在，请先确认");
            }
        }



        /// <summary>
        /// 发布微信小程序获取登录二维码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLoginAppletWeChat()
        {
            var parms = RequestParm;
            var query = new RB_MiniProgram_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };
            var model = appletWeChatModule.GetTenantListModule(query).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("您还未配置微信小程序基础信息");
            }

            try
            {
                string URL = $"http://127.0.0.1:{developerKitsPort}/v2/login?qr-format=base64&project=&appid={model.MiniAppId}&ext-appid=";
                string result = Mall.Common.Plugin.HttpHelper.HttpGet(URL, Encoding.UTF8, "");
                JObject parmsJob = JObject.Parse(result);
                string imgUrl = parmsJob.GetValue("qrcode").ToString();
                if (parmsJob.ContainsKey("code"))
                {
                    return ApiResult.Failed(parmsJob.GetValue("message").ToString());
                }
                return ApiResult.Success("获取成功", imgUrl);
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetLoginAppletWeChat");
                return ApiResult.Failed("获取登录二维码识别");
            }
        }

        /// <summary>
        /// 获取项目预览二维码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPreviewAppletWeChat()
        {

            var parms = RequestParm;
            var query = new RB_MiniProgram_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };
            var model = appletWeChatModule.GetTenantListModule(query).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("您还未配置微信小程序基础信息");
            }

            try
            {
                string path = projectUrl + "/miniProject";
                if (string.IsNullOrWhiteSpace(model.Version))
                {
                    query.Version = "1.0.00";
                }
                if (model.LivePlayerPlugin == 1)
                {
                    path = projectUrl + "/miniProjectLive";
                }
                string URL = $"http://127.0.0.1:{developerKitsPort}/v2/preview?project={Mall.Common.Plugin.StringHelper.UrlEncode(path)}&qr-format=base64";
                // string URL = $"http://127.0.0.1:{developerKitsPort}/v2/preview?project={Mall.Common.Plugin.StringHelper.UrlEncode(projectUrl + "/miniProject")}&qr-format=base64";
                string result = Mall.Common.Plugin.HttpHelper.HttpGet(URL, Encoding.UTF8, "");
                if (result.Length > 200 && !result.Contains("data:image/png;base64,"))
                {
                    result = "data:image/png;base64," + result;
                }
                else
                {
                    JObject parmsJob = JObject.Parse(result);
                    if (parmsJob.ContainsKey("code"))
                    {
                        return ApiResult.Failed(parmsJob.GetValue("message").ToString());
                    }
                }
                return ApiResult.Success("获取成功", result);
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetPreviewAppletWeChat");
                return ApiResult.Failed("获取登录二维码识别");
            }
        }


        /// <summary>
        /// 发布小程序
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPuploadAppletWeChat()
        {
            var parms = RequestParm;
            var query = new RB_MiniProgram_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };
            var model = appletWeChatModule.GetTenantListModule(query).FirstOrDefault();
            if (model == null)
            {
                return ApiResult.Failed("您还未配置微信小程序基础信息");
            }

            try
            {
                string path = projectUrl + "/miniProject";
                if (string.IsNullOrWhiteSpace(model.Version))
                {
                    query.Version = "1.0.00";//1111
                }
                if (model.LivePlayerPlugin == 1)
                {
                    path = projectUrl + "/miniProjectLive";
                }
                int version = Convert.ToInt32(model.Version.Replace(".", ""));
                version += 1;
                model.Version = version.ToString().Substring(0, version.ToString().Length - 3) + "." + version.ToString().Substring(version.ToString().Length - 3, 1) + "." + version.ToString().Substring(version.ToString().Length - 2, 2);
                string URL = $"http://127.0.0.1:{developerKitsPort}/v2/upload?project={Mall.Common.Plugin.StringHelper.UrlEncode(path)}&version=V{model.Version}&desc=微信开发者工具HTTP上传&appid={model.MiniAppId}";
                //string URL = $"http://127.0.0.1:{developerKitsPort}/v2/upload?project={Mall.Common.Plugin.StringHelper.UrlEncode(projectUrl + "/miniProject")}&version=V{model.Version}&desc=微信开发者工具HTTP上传&appid={model.MiniAppId}";
                string result = Mall.Common.Plugin.HttpHelper.HttpGet(URL, Encoding.UTF8, "");
                JObject parmsJob = JObject.Parse(result);
                if (parmsJob.ContainsKey("code"))
                {
                    return ApiResult.Failed(parmsJob.GetValue("message").ToString());
                }
                //更新版本
                appletWeChatModule.UpdateVersion(model);

                return ApiResult.Success("上传成功", new { result, URL });
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, "GetPuploadAppletWeChat");
                return ApiResult.Failed("上传失败");
            }
        }





        /// <summary>
        /// 获取微信小程序分享
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual ApiResult GetWeiXinShare()
        {
            var parms = RequestParm;
            var query = new RB_MiniProgram_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };

            var appletWeChatModel = appletWeChatModule.GetTenantListModule(query).FirstOrDefault();
            string imgBase64 = appletWeChatModule.GetWeiXinShare(appletWeChatModel, FirstPage);
            return ApiResult.Success("", imgBase64);
        }




        /// <summary>
        /// 当面付页面调转
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual ApiResult GetNativeOrder()
        {
            var parms = RequestParm;
            var query = new RB_MiniProgram_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };

            var appletWeChatModel = appletWeChatModule.GetTenantListModule(query).FirstOrDefault();
            string imgBase64 = appletWeChatModule.GetWeiXinShare(appletWeChatModel, "");//页面暂时还未确定，确定后填入20200604 Add  By:W
            return ApiResult.Success("", imgBase64);
        }




        /// <summary>
        ///  订阅消息推送
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetLXYSubscribeSend()
        {
            var parmsInfo = RequestParm;
            JObject parms = JObject.Parse(RequestParm.msg.ToString());
            string code = parms.GetStringValue("code");
            if (string.IsNullOrWhiteSpace(code))
            {
                return ApiResult.Failed("请传递code参数");
            }
            var appletWeChatModel = appletWeChatModule.GetTenantListModule(new RB_MiniProgram_Extend { TenantId = Convert.ToInt32(parmsInfo.uid), MallBaseId = parmsInfo.MallBaseId }).FirstOrDefault();
            string OpenId = "ow_7I5XC1-RGwwk8QANBmWKYKmOc"; //GetHelpByWx(code, appletWeChatModel);
            bool flag = appletWeChatModule.SendOrderDeliverMsg(Convert.ToInt32(parmsInfo.uid), parmsInfo.MallBaseId, OpenId, "发货拉拉了", "SNO215445555", "中通", "测试商品请勿购买");
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 设置客户订阅信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetGuestSubscribe()
        {
            RB_Member_Subscription_Extend demodel = JsonConvert.DeserializeObject<RB_Member_Subscription_Extend>(RequestParm.msg.ToString());
            if ((demodel.UserId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递会员id");
            }
            if (string.IsNullOrEmpty(demodel.OpenId))
            {
                return ApiResult.ParamIsNull("请传递微信openid");
            }
            if (demodel.TempleteIdList == null || !demodel.TempleteIdList.Any())
            {
                return ApiResult.ParamIsNull("请传递会员订阅的模板id");
            }

            bool flag = appletWeChatModule.SetMemberSubscribe(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 获取订阅模块列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSubscribeTempleteList(RequestParm request)
        {
            List<object> tlist = GetTempleteList();
            return ApiResult.Success("", tlist);
        }

        /// <summary>
        /// 获取templete
        /// </summary>
        /// <returns></returns>
        private static List<object> GetTempleteList()
        {
            return new List<object>() {
                new {
                    TempleteId="WPELErDfYO3JnizA5Zikta6Y8qrBBAgecuj2aLoucuY",
                    Name="下单成功提醒"
                }, new {
                    TempleteId="pCmTJwvTqNpyRREo7vvqIYBcrATNWoitfbLS61fLhzU",
                    Name="订单取消通知"
                }, new {
                    TempleteId="i6QPsaOHgfNwlIRMwmvFGSCqX28g0cRa8XaLZ5_gpgc",
                    Name="订单发货通知"
                }, new {
                    TempleteId="o_zwbbXqC5nJLEzXVVvgCT3LUHnBCkxWxkT6D1HhQXU",
                    Name="退款通知"
                }, new {
                    TempleteId="nwYnuXeMF-XuUHkf_MgJFdfy9Gic1jnj6lYR6W9KOnQ",
                    Name="活动状态通知"
                }, new {
                    TempleteId="mUcV9nOOZ-MrcUmXH157YRdnFEh8_Tcz8lWhjgeHhHE",
                    Name="审核结果通知"
                }, new {
                    TempleteId="STLsTw3R86aMtVbcYgU_UZbxj_Tn0h3rIJwZRSrLmGQ",
                    Name="提现成功通知"
                }, new {
                    TempleteId="fqwGB0769qgJYQOaqqE1uKC6PS3Vp47J3jGMW3BXBrw",
                    Name="提现失败通知"
                }, new {
                    TempleteId="8QhIQmzdDXDxKWMnE6aa_t3VPxah0EGTmLhA-JQcSwc",
                    Name="会员等级变更通知"
                }
            };
        }

        /// <summary>
        ///  订阅剩余次数
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSubscribeCountList()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            string OpenId = parmsJob.GetStringValue("OpenId");

            var query = new RB_Member_Subscription_Extend
            {
                TenantId = UserInfo.TenantId,
                MallBaseId = parms.MallBaseId
            };

            if (string.IsNullOrEmpty(OpenId))
            {
                return ApiResult.Failed();
            }
            var tlist = GetTempleteList();
            var list = appletWeChatModule.GetLXYSubscribeCountList(OpenId, query.MallBaseId, query.TenantId);
            List<object> robj = new List<object>();
            foreach (var item in tlist)
            {
                JObject parm = JObject.Parse(JsonConvert.SerializeObject(item));
                string TempleteId = parm.GetStringValue("TempleteId");
                string Name = parm.GetStringValue("Name");
                var model = list.Where(x => x.TempleteId == TempleteId).FirstOrDefault();
                robj.Add(new
                {
                    Name,
                    TempleteId,
                    Count = model?.Count ?? 0,
                });
            }

            return ApiResult.Success("", robj);
        }



        #region 微信获取openid
        //微信也不给个c#调用的例子 
        /// <summary>
        /// 根据code 获取微信信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetHelpByWx(string code, RB_MiniProgram_Extend model)
        {

            string Appid = model.MiniAppId;
            string Secret = model.MiniAppSecret;
            string grant_type = "authorization_code";
            //向微信服务端 使用登录凭证 code 获取 session_key 和 openid  
            string url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + Appid + "&secret=" + Secret + "&js_code=" + code + "&grant_type=" + grant_type;
            string type = "utf-8";
            GetUsersHelper GetUsersHelper = new GetUsersHelper();
            string wenXinResult = string.Empty;
            JObject jo = null;
            result res = new result();
            try
            {
                wenXinResult = GetUsersHelper.GetUrltoHtml(url, type);//获取微信服务器返回字符串              
                jo = (JObject)JsonConvert.DeserializeObject(wenXinResult);//将字符串转换为json格式 
                //微信服务器验证成功 
                res.openid = jo["openid"].ToString();
                res.session_key = jo["session_key"].ToString();
            }
            catch (Exception ex)
            {
                Common.Plugin.LogHelper.Write(ex, string.Format("GetWx:wenXinResult:{0},code:{1}", wenXinResult, code));
                //微信服务器验证失败 
                res.errcode = jo["errcode"].ToString();
                res.errmsg = jo["errmsg"].ToString();
            }
            return res.openid;
        }


        #endregion




        #region 获取微信直播房间信息

        /// <summary>
        ///  获取直播房间列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLiveInfo()
        {
            var parmsInfo = RequestParm;

            var appletWeChatModel = appletWeChatModule.GetTenantListModule(new RB_MiniProgram_Extend { TenantId = Convert.ToInt32(parmsInfo.uid), MallBaseId = parmsInfo.MallBaseId }).FirstOrDefault();

            bool flag = appletWeChatModule.GetLiveInfo(appletWeChatModel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }


        /// <summary>
        /// 获取直播房间回放信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetLiveReplayInfo()
        {
            var parmsInfo = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int roomId = parmsJob.GetInt("roomId");
            var appletWeChatModel = appletWeChatModule.GetTenantListModule(new RB_MiniProgram_Extend { TenantId = Convert.ToInt32(parmsInfo.uid), MallBaseId = parmsInfo.MallBaseId }).FirstOrDefault();

            var model = appletWeChatModule.GetLiveReplayInfo(appletWeChatModel, roomId);
            if (model.errcode == "0")
            {
                return ApiResult.Success("", model);
            }
            else
            {
                return ApiResult.Failed();
            }
        }




       



        [HttpPost]
        [Obsolete]
        public ApiResult GetLiveHousePageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            Model.Extend.AppletWeChat.RB_Live_HouseExtension_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.AppletWeChat.RB_Live_HouseExtension_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = appletWeChatModule.GetLiveHouseExtensionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.roomid,
                x.name,
                x.anchor_img,
                x.anchor_name,
                x.cover_img,
                x.live_status,
                x.ExtensionImg,
                x.HouseImgID,
                x.LiveQrCodePaddingLeft,
                x.LiveQrCodePaddingTop,
                x.LiveQrCodeSize,
                x.LiveQrCodeType,
                start_time = GetTime(x.start_time),
                end_time = GetTime(x.end_time),
            });
            return ApiResult.Success("", pagelist);
        }




        /// <summary>
        /// 保存直播推广图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult AddOrUpdateHouseImg()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<Model.Entity.AppletWeChat.RB_Live_HouseImg>(RequestParm.msg.ToString());

            if (query == null)
            {
                return ApiResult.Failed("请传入推广图片信息");
            }
            else
            {
                if (string.IsNullOrWhiteSpace(query.ExtensionImg))
                {
                    return ApiResult.Failed("请传入推广图片信息");
                }
                if (string.IsNullOrWhiteSpace(query.roomid))
                {
                    return ApiResult.Failed("请传入直播房间id");

                }
                query.TenantId = UserInfo.TenantId;
                query.MallBaseId = parms.MallBaseId;
                bool result = appletWeChatModule.AddOrUpdateHouseImg(query);
                if (result)
                {
                    return ApiResult.Success("推广图片保存成功");
                }
                else
                {
                    return ApiResult.Failed("推广图片保存失败");
                }
            }
        }

        /// <summary>
        /// 设置直播海报二维码样式
        /// </summary>
        /// <param name="extModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetLiveQrCode()
        {
            var parms = RequestParm;
            var extModel = JsonConvert.DeserializeObject<RB_Live_HouseExtension_Extend>(RequestParm.msg.ToString());
            bool flag = appletWeChatModule.SetLiveQrCodeModule(extModel);
            return flag ? ApiResult.Success() : ApiResult.Failed();
        }

        /// <summary>
        /// 删除图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelHouseImg()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = appletWeChatModule.DelLiveHouseImg(Id, UserInfo.TenantId, parms.MallBaseId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 时间戳转为C#格式时间
        /// </summary>
        /// <param name="timeStamp">Unix时间戳格式</param>
        /// <returns>C#格式时间</returns>
        [Obsolete]
        public static string GetTime(string timeStamp)
        {
            try
            {
                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                long lTime = long.Parse(timeStamp + "0000000");
                TimeSpan toNow = new TimeSpan(lTime);
                return dtStart.Add(toNow).ToString("yyyy-MM-dd HH:mm:ss");
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion
    }
}