using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Edu.Common.Plugin;
using Edu.ThirdCore.QYWinXin.Model;
using Edu.Common;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.AdvancedAPIs.Media;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.Entities;
using Senparc.Weixin.MP.AdvancedAPIs.GroupMessage;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs.UserTag;

namespace Edu.ThirdCore.GZHWeChat
{
    /// <summary>
    /// 公众号处理
    /// </summary>
    public class GZHWeChatHelper
    {

        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        public static AccessTokenResult GetGZHToken(string appid, string secret)
        {
            return CommonApi.GetToken(appid, secret);
        }

        /// <summary>
        /// 新增其他类型永久素材(图片（image）、语音（voice）和缩略图（thumb）)
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="file">上传文件的绝对路径</param>
        /// <returns></returns>
        public static UploadForeverMediaResult UploadForeverMedia(string accessTokenOrAppId, string file)
        {
            return MediaApi.UploadForeverMedia(accessTokenOrAppId, file);
        }

        /// <summary>
        /// 新增永久视频素材
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="type">媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）</param>
        /// <param name="title">素材的标题</param>
        /// <param name="introduction">素材的描述</param>
        /// <param name="file">上传文件的绝对路径</param>
        /// <returns></returns>
        public static UploadForeverMediaResult UploadForeverVideo(string accessTokenOrAppId, string file, string title, string introduction, string type)
        {
            return MediaApi.UploadForeverVideo(accessTokenOrAppId, file, title, introduction, type);
        }

        /// <summary>
        /// 获取永久视频素材
        /// </summary>
        /// <param name="accessTokenOrAppId"></param>
        /// <param name="mediaId">要获取的素材的media_id</param>
        /// <returns></returns>
        public static GetForeverMediaVideoResultJson GetForeverVideo(string accessTokenOrAppId, string mediaId)
        {
            return MediaApi.GetForeverVideo(accessTokenOrAppId, mediaId);
        }

        /// <summary>
        /// 删除永久素材
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public static WxJsonResult DeleteForeverMedia(string accessTokenOrAppId, string mediaId)
        {
            return MediaApi.DeleteForeverMedia(accessTokenOrAppId, mediaId);
        }

        /// <summary>
        /// 上传图文消息内的图片获取URL
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="file">上传文件的绝对路径</param>
        /// <returns></returns>
        public static UploadImgResult UploadImg(string accessTokenOrAppId, string file)
        {
            return MediaApi.UploadImg(accessTokenOrAppId, file);
        }

        /// <summary>
        /// 新增永久图文素材
        /// </summary>
        /// <param name="accessTokenOrAppId">Token</param>
        /// <param name="news">图文消息组</param>        
        /// <returns></returns>
        public static UploadForeverMediaResult UploadNews(string accessTokenOrAppId, params NewsModel[] news)
        {
            return MediaApi.UploadNews(accessTokenOrAppId, Senparc.Weixin.Config.TIME_OUT, news);
        }

        /// <summary>
        /// 修改永久图文素材
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="mediaId">要修改的图文消息的id</param>
        /// <param name="index">要更新的文章在图文消息中的位置（多图文消息时，此字段才有意义），第一篇为0</param>
        /// <param name="news">图文素材</param>
        /// <returns></returns>
        public static WxJsonResult UpdateForeverNews(string accessTokenOrAppId, string mediaId, int? index, NewsModel news)
        {
            return MediaApi.UpdateForeverNews(accessTokenOrAppId, mediaId, index, news);
        }

        /// <summary>
        /// 获取视频群发用的MediaId
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="mediaId"></param>
        /// <param name="title"></param>
        /// <param name="description"></param>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public static VideoMediaIdResult GetVideoMediaIdResult(string accessTokenOrAppId, string mediaId, string title, string description)
        {
            return GroupMessageApi.GetVideoMediaIdResult(accessTokenOrAppId, mediaId, title, description);
        }


        /// <summary>
        /// 根据[标签]进行群发【订阅号与服务号认证后均可用】
        /// 
        /// 请注意：
        /// 1、该接口暂时仅提供给已微信认证的服务号
        /// 2、虽然开发者使用高级群发接口的每日调用限制为100次，但是用户每月只能接收4条，请小心测试
        /// 3、无论在公众平台网站上，还是使用接口群发，用户每月只能接收4条群发消息，多于4条的群发将对该用户发送失败。
        /// 4、群发视频时需要先调用GetVideoMediaIdResult接口获取专用的MediaId然后进行群发
        /// 
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="tagId">群发到的标签的tag_id，若is_to_all值为true，可不填写tag_id</param>
        /// <param name="value">群发媒体文件时传入mediaId,群发文本消息时传入content,群发卡券时传入cardId</param>
        /// <param name="type"></param>
        /// <param name="isToAll">用于设定是否向全部用户发送，值为true或false，选择true该消息群发给所有用户，选择false可根据group_id发送给指定群组的用户</param>
        /// <param name="sendIgnoreReprint">待群发的文章被判定为转载时，是否继续群发</param>
        /// <param name="clientmsgid">开发者侧群发msgid，长度限制64字节，如不填，则后台默认以群发范围和群发内容的摘要值做为clientmsgid</param>
        /// <returns></returns>
        public static SendResult SendGroupMessageByTagId(string accessTokenOrAppId, string tagId, string value, GroupMessageType type, bool isToAll = false, bool sendIgnoreReprint = false, string clientmsgid = null)
        {
            return GroupMessageApi.SendGroupMessageByTagId(accessTokenOrAppId, tagId, value, type, isToAll, sendIgnoreReprint, clientmsgid);
        }

        /// <summary>
        /// 预览接口【订阅号与服务号认证后均可用】
        /// 注意：openId与wxName两者任选其一，同时传入以wxName优先
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <param name="value">群发媒体消息时为media_id，群发文本信息为content</param>
        /// <param name="type"></param>
        /// <param name="openId">接收消息用户对应该公众号的openid</param>
        /// <param name="wxName">接收消息用户的微信号</param>
        /// <returns></returns>
        public static SendResult SendGroupMessagePreview(string accessTokenOrAppId, GroupMessageType type, string value, string openId, string wxName = null)
        {
            return GroupMessageApi.SendGroupMessagePreview(accessTokenOrAppId, type, value, openId, wxName);
        }

        /// <summary>
        /// 群发图片 （预览）
        /// </summary>
        /// <param name="accessTokenOrAppId"></param>
        /// <param name="wxName"></param>
        /// <param name="media_ids"></param>
        /// <param name="recommend"></param>
        /// <returns></returns>
        public static SendResult SendImageMessagePreview(string accessTokenOrAppId, string wxName, string media_id, string recommend)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=" + accessTokenOrAppId;

            var SendDate = new
            {
                towxname = wxName,
                image = new {
                    media_id
                },
                msgtype = "image"
            };

            var Rmsg = HttpHelper.HttpPost(url, JsonHelper.Serialize(SendDate), "");
            if (!string.IsNullOrEmpty(Rmsg))
            {
                var rmodel = JsonHelper.DeserializeObject<SendResult>(Rmsg);
                return rmodel;
            }
            return null;
        }

        /// <summary>
        /// 群发图片正式
        /// </summary>
        /// <param name="accessTokenOrAppId"></param>
        /// <param name="wxName"></param>
        /// <param name="media_ids"></param>
        /// <param name="recommend"></param>
        /// <returns></returns>
        public static SendResult SendImageMessageByTagId(string accessTokenOrAppId, string tagId, List<string> media_ids, string recommend, bool isToAll = false)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=" + accessTokenOrAppId;

            var SendDate = new
            {
                filter = new {
                    is_to_all = isToAll,
                    tag_id = tagId
                },
                images = new
                {
                    media_ids,
                    recommend,
                    need_open_comment = 1,
                    only_fans_can_comment = 0
                },
                msgtype = "image"
            };

            var Rmsg = HttpHelper.HttpPost(url, JsonHelper.Serialize(SendDate), "");
            if (!string.IsNullOrEmpty(Rmsg))
            {
                var rmodel = JsonHelper.DeserializeObject<SendResult>(Rmsg);
                return rmodel;
            }
            return null;
        }


        /// <summary>
        /// 上传本地文件至企业微信
        /// </summary>
        /// <param name="accessTokenOrAppKey"></param>
        /// <param name="filepath"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string UploadMultimedia(string accessTokenOrAppKey, string filepath, UploadMediaFileType type)
        {
            string result = "";
            string wxurl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=" + accessTokenOrAppKey + "&type=" + type.ToString();
            WebClient myWebClient = new WebClient
            {
                Credentials = CredentialCache.DefaultCredentials,
            };
            try
            {
                byte[] responseArray = myWebClient.UploadFile(wxurl, "POST", filepath);
                result = Encoding.Default.GetString(responseArray, 0, responseArray.Length);
                return result;
            }
            catch (Exception ex)
            {
                result = "Error:" + ex.Message;
            }
            finally
            {
                myWebClient.Dispose();
            }
            return result;
        }


        /// <summary>
        /// 获取公众号已创建的标签
        /// </summary>
        /// <param name="accessTokenOrAppId">AccessToken或AppId（推荐使用AppId，需要先注册）</param>
        /// <returns></returns>
        public static TagJson GetUserTagList(string accessTokenOrAppId)
        {
            return UserTagApi.Get(accessTokenOrAppId);
        }
    }
}
