package com.tzy.s.wx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tzy.s.wx.common.Common;
import com.tzy.s.wx.service.WeixinApi;
import com.tzy.s.wx.util.HttpClient;
import com.tzy.s.wx.dto.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.MessageFormat;
import java.util.*;

/**
 * TCP
 * HTTPS
 * 微信基础接口
 */
@Slf4j
@Service
public class WeixinApiImpl implements WeixinApi {
    private Common common = new Common();
    /**
     * 获取基础ACCESSTOKEN 地址 ->GET
     */
    private static String ACCESSTOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}";
    /**
     * 获取 web token 地址 ->GET
     */
    private static String WEB_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code";
    /**
     * 获取 用户基础信息 sns-》GET
     */
    private static String SNSAPI_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={0}&openid={1}&lang=zh_CN";
    /**
     * 獲取用戶信息 unionID 機制
     */
    private static String UNIONID_USERINFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={0}&openid={1}&lang=zh_CN";

    /** 創建用戶標籤  機制》POST*/
    private static String TAGS_USERINFO_URL = "https://api.weixin.qq.com/cgi-bin/tags/create?access_token={0}&lang=zh_CN";
    /** 獲取用戶標籤  機制》GET*/
    private static String TAGS_GET_URL =" https://api.weixin.qq.com/cgi-bin/tags/get?access_token={0}&lang=zh_CN";
    /**删除用戶標籤  機制》POST*/
    private static String TAGS_DELETE_URL = " https://api.weixin.qq.com/cgi-bin/tags/delete?access_token={0}&id={1}&lang=zh_CN";
    /**更新用戶標籤  機制》POST*/
    private  static String TAGS_UPDATE_POST ="https://api.weixin.qq.com/cgi-bin/tags/update?access_token={0}&jsonObject={1}&lang=zh_CN";
    /**批量为粉丝打標籤  機制》POST*/
    private static String TAGS_BATCHTAG_URL = " https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?access_token={0}&openid_list={1}&tagid={2}&lang=zh_CN";
    /**批量为粉丝取消標籤  機制》POST*/
    private static String TAGS_BATCHUNTAG_URL="https://api.weixin.qq.com/cgi-bin/tags/members/batchuntagging?access_token={0}&openid_list={1}&tagid={2}&lang=zh_CN";
    /**獲取openID列表  機制》GET*/
    private  static String USER_OPENID_GET ="https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}&lang=zh_CN";
    /**獲取粉絲身上的標籤  機制》POST*/
    private  static String TAGS_GETIDLIST_GET ="https://api.weixin.qq.com/cgi-bin/tags/getidlist?access_token={0}&lang=zh_CN";
    /**獲取標籤下的粉絲列表  機制》POST*/
    private  static String TAGS_GETUSER_POST ="https://api.weixin.qq.com/cgi-bin/user/tag/get?access_token={0}&tagid={1}&next_openid={2}&lang=zh_CN";

    /**
     * 获取图文素材
     */
    private static String NEWSITEM_URL = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}&lang=zh_CN";
    /**
     * 获取图文素材总数
     */
    private static String NEWSITEM_COUNT_URL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token={0}&lang=zh_CN";
    /**
     * 获取图文素材列表
     */
    private static String NEWSITEM_LIST_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={0}&lang=zh_CN";

    /**
     * 新增永久图文素材
     */
    private static String ADD_NEWSITEM_URL = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}";
    /**
     * 修改永久图文素材
     */
    private static String UPDATE_NEWSITEM_URL = "https://api.weixin.qq.com/cgi-bin/material/update_news?access_token={0}";
    /**
     * 刪除永久图文素材
     */
    private static String DEL_NEWSITEM_URL = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token={0}";

    /**
     * 获取ticket
     */
    private static String TICKET_URL="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type={1}&lang=zh_CN";

    /**
     * 新增媒体文件类型的文件（image）、语音（voice）、视频（video）和缩略图（thumb）
     */
    private static String ADD_MATERIAL="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
    /**
     * 上传图文消息内的图片获取URL
     */
    private static String ADD_PIC="https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}";
    /**
     * 新增临时素材
     */
    private static String UPLOAD_MEDIA = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";

    /**
     * 获取基础access token
     * @param appid
     * @param appsecret
     * @return
     */
    @Override
    public Result getAccessToken(String appid, String appsecret) {
        if (StringUtils.isEmpty(appid)) return Result.error(-1, "appid不能为空");
        if (StringUtils.isEmpty(appsecret)) return Result.error(-1, "appsecret不能为空");
        String url = MessageFormat.format(ACCESSTOKEN_URL, appid, appsecret);
        return common.getAccesstoken(url);
    }

    /**
     * 获取 web token 网页授权专用
     *
     * @param appid
     * @param appsecret
     * @param code
     * @return
     */
    @Override
    public Result<?> getWebToken(String appid, String appsecret, String code) {
        if (StringUtils.isEmpty(appid)) return WebAccesstoken.error(-1, "appid不能为空");
        if (StringUtils.isEmpty(appsecret)) return WebAccesstoken.error(-1, "accsecret不能为空");
        if (StringUtils.isEmpty(code)) return WebAccesstoken.error(-1, "code不能为空");
        String url = MessageFormat.format(WEB_TOKEN_URL, appid, appsecret, code);
        String ret = HttpClient.httpsRequest(url, "POST", null);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            WebAccesstoken accesstoken = JSONObject.toJavaObject(retJson, WebAccesstoken.class);
            return accesstoken;
        } catch (Exception e) {
            e.printStackTrace();
            return WebAccesstoken.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * @param token  web授权token
     * @param openid
     * @return
     */
    @Override
    public Result getSnsapiUserInfo(String token, String openid) {
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        if (StringUtils.isEmpty(openid)) return Result.error(-1, "openid不能为空");
        String url = MessageFormat.format(SNSAPI_USERINFO_URL, token, openid);
        String ret = HttpClient.httpsRequest(url, "POST", null);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            SnsapiUserInfo userInfo = JSONObject.toJavaObject(retJson, SnsapiUserInfo.class);
            return userInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 獲取用戶信息（unionID機制）
     *
     * @param accesstoken
     * @param openid
     * @return
     */
    @Override
    public Result getUserinfo(String accesstoken, String openid) {
        if (StringUtils.isEmpty(accesstoken)) return Result.error(-1, "accesstoken不能为空");
        if (StringUtils.isEmpty(openid)) return Result.error(-1, "openid不能为空");
        String url = MessageFormat.format(UNIONID_USERINFO_URL, accesstoken, openid);
        String ret = HttpClient.httpsRequest(url, "POST", null);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            UserInfo userInfo = JSONObject.toJavaObject(retJson, UserInfo.class);
            return userInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 获取图文素材
     * @param token
     * @return
     */
    @Override
    public Result getNewitems(String token, String mediaId) {
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        String url = MessageFormat.format(NEWSITEM_URL, token);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("media_id",mediaId);
        String param = jsonObject.toString();
        String ret = HttpClient.httpsRequest(url, "POST", param);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            NewsitemInfo newsitemInfo = JSONObject.toJavaObject(retJson, NewsitemInfo.class);
            return newsitemInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return NewsitemInfo.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 获取图文素材数目
     * @return
     */
    @Override
    public Result getNewitemsCount(String token) {
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        String url = MessageFormat.format(NEWSITEM_COUNT_URL, token);
        String ret = HttpClient.httpsRequest(url, "GET", null);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            NewsitemCountInfo newsitemCountInfo = JSONObject.toJavaObject(retJson, NewsitemCountInfo.class);
            return newsitemCountInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return NewsitemCountInfo.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 获取图文素材列表
     * @param token
     * @param type
     * @param offset
     * @param count
     * @return
     */
    @Override
    public Result getNewitemsList(String token, String type, Integer offset, Integer count) {
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        if (StringUtils.isEmpty(type)) return Result.error(-1, "type不能为空");
        if (offset == null) offset = 0;
        if (count == null) count = 10;
        String url = MessageFormat.format(NEWSITEM_LIST_URL, token);
        /** 封装参数*/
        JSONObject json = new JSONObject();
        json.put("type",type);
        json.put("offset",offset);
        json.put("count",count);
        String param = json.toString();
        String ret = HttpClient.httpsRequest(url, "POST", param);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            NewsTypeInfo newsTypeInfo = JSONObject.toJavaObject(retJson,NewsTypeInfo.class);
            return newsTypeInfo;
        }catch (Exception e){
            e.printStackTrace();
            return NewsTypeInfo.error(-1,"请求异常，请联系开发人员");
        }
    }


    @Override
    public Result setTag(String accesstoken, String name) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(name))return Result.error(-1,"name不能为空");
        String url = MessageFormat.format(TAGS_USERINFO_URL, accesstoken);
        JSONObject object = new JSONObject();
        object.put("name",name);
        JSONObject tag = new JSONObject();
        tag.put("tag",object);
        String s = tag.toString();
        String ret = HttpClient.httpsRequest(url, "POST",s);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Tag tagg = JSONObject.toJavaObject(retJson,Tag.class);
            return  tagg;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");

        }
    }
    /**
     * 獲取已經創建的標籤
     * @param accesstoken
     * @return
     */
    @Override
    public Result getTag(String accesstoken) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        String url = MessageFormat.format(TAGS_GET_URL,accesstoken);
        String ret = HttpClient.httpsRequest(url,"GET",null);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Tags tags = JSONObject.toJavaObject(retJson,Tags.class);
            return tags;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }


    @Override
    public Result getTicket(String token, String type){
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        if (StringUtils.isEmpty(type)) return Result.error(-1, "type不能为空");
        String url = MessageFormat.format(TICKET_URL, token, type);
        String ret = HttpClient.httpsRequest(url, "GET", null);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            TicketInfo ticketInfo = JSONObject.toJavaObject(retJson, TicketInfo.class);
            return ticketInfo;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    @Override
    public Result addMaterial(String filePath, String type, String token){
        if (StringUtils.isEmpty(filePath)) return Result.error(-1, "filePath不能为空");
        if (StringUtils.isEmpty(type)) return Result.error(-1, "type不能为空");
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        File file = new File(filePath);
        String url = MessageFormat.format(ADD_MATERIAL, token, type);
        try {
            String result = HttpClient.connectHttpsByPost(url, null, file);
            JSONObject retJson = JSONObject.parseObject(result);
            Material material = JSONObject.toJavaObject(retJson, Material.class);
            return material;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 上传图文消息内的图片获取URL
     * @param filePath
     * @param token
     * @return
     */
    @Override
    public Result addPic(String filePath, String token){
        if (StringUtils.isEmpty(filePath)) return Result.error(-1, "filePath不能为空");
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        File file = new File(filePath);
        String url = MessageFormat.format(ADD_PIC, token);
        try {
            String result = HttpClient.connectHttpsByPost(url, null, file);
            JSONObject retJson = JSONObject.parseObject(result);
            Material material = JSONObject.toJavaObject(retJson, Material.class);
            return material;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    @Override
    public Result addMaterial(String filePath, String token,String title,String introduction){
        if (StringUtils.isEmpty(filePath)) return Result.error(-1, "filePath不能为空");
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        String type = "video";
        JSONObject jsonObject = null;
        String param = null;
        if(StringUtils.isEmpty(title) || StringUtils.isEmpty(introduction)){
            return Result.error(-1, "title,introduction不能为空");
        }
        String url = MessageFormat.format(ADD_MATERIAL, token, type);
        try {
            String result = HttpClient.connectHttpsByPost(url, filePath, title,introduction);
            JSONObject retJson = JSONObject.parseObject(result);
            Material material = JSONObject.toJavaObject(retJson, Material.class);
            return material;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 刪除標籤
     * @param accesstoken
     * @param id
     * @return
     */
    @Override
    public Result deleteTag(String accesstoken, String id) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(id))return Result.error(-1,"id不能为空");
        String url = MessageFormat.format(TAGS_DELETE_URL,accesstoken);
        JSONObject object = new JSONObject();
        object.put("id",id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tag",object);
        String s = jsonObject.toString();
        String ret = HttpClient.httpsRequest(url,"POST",s);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Result result = JSONObject.toJavaObject(retJson,Result.class);
            return  result;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 編輯標籤
     * @param accesstoken
     * @param jsonObject
     * @return
     */
    @Override
    public Result updateTag(String accesstoken, JSONObject jsonObject) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(jsonObject.isEmpty())return Result.error(-1,"jsonObject不能为空");
        String url = MessageFormat.format(TAGS_UPDATE_POST, accesstoken);
        String s = jsonObject.toString();
        String ret = HttpClient.httpsRequest(url, "POST",s);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Result result = JSONObject.toJavaObject(retJson,Result.class);
            return  result;
        } catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 獲取openID列表 第一次拉取的時候  next_openid可以不填
     * @param accesstoken
     * @param next_openid
     * @return
     */
    @Override
    public Result getOpenid(String accesstoken,String next_openid) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        String url = null;
        if(StringUtils.isEmpty(next_openid) || "0".equals(next_openid)){
            USER_OPENID_GET = USER_OPENID_GET.replace("&next_openid={1}","");
            url = MessageFormat.format(USER_OPENID_GET,accesstoken);
        }else{
            url = MessageFormat.format(USER_OPENID_GET,accesstoken,next_openid);
        }

        String ret = HttpClient.httpsRequest(url,"GET",null);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            GetOpenId getOpenId = JSONObject.toJavaObject(retJson,GetOpenId.class);
            return getOpenId;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 批量為粉絲打標籤
     * @param accesstoken
     * @param openid_list
     * @param tagid
     * @return
     */
    @Override
    public Result batchTag(String accesstoken, List openid_list, String tagid) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(tagid))return Result.error(-1,"tagid不能为空");
        if(openid_list.isEmpty())return Result.error(-1,"accesstoken不能为空");
        String url = MessageFormat.format(TAGS_BATCHTAG_URL,accesstoken);
        JSONObject object = new JSONObject();
        object.put("openid_list",openid_list);
        object.put("tagid",tagid);
        String s = object.toString();
        String ret = HttpClient.httpsRequest(url,"POST",s);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Result result = JSONObject.toJavaObject(retJson,Result.class);
            return  result;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 批量為用戶取消標籤
     * @param accesstoken
     * @param openid_list
     * @param tagid
     * @return
     */
    @Override
    public Result batchuntagging(String accesstoken, List openid_list, String tagid) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(tagid))return Result.error(-1,"tagid不能为空");
        if(openid_list.isEmpty())return Result.error(-1,"accesstoken不能为空");
        String url = MessageFormat.format(TAGS_BATCHUNTAG_URL,accesstoken);
        JSONObject object = new JSONObject();
        object.put("openid_list",openid_list);
        object.put("tagid",tagid);
        String s = object.toString();
        String ret = HttpClient.httpsRequest(url,"POST",s);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Result result = JSONObject.toJavaObject(retJson,Result.class);
            return  result;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 獲取粉絲身上的標籤
     * @param accesstoken
     * @param openid
     * @return
     */
    @Override
    public Result getidList(String accesstoken, String openid) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(openid))return Result.error(-1,"openid不能为空");
        String url = MessageFormat.format(TAGS_GETIDLIST_GET,accesstoken);
        JSONObject object = new JSONObject();
        object.put("openid",openid);
        String s = object.toString();
        String ret = HttpClient.httpsRequest(url,"POST",s);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            TagidList tagid_list = JSONObject.toJavaObject(retJson,TagidList.class);
            return  tagid_list;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }

    }

    /**
     * 獲取標籤下的粉絲列表
     * @param accesstoken
     * @return
     */
    @Override
    public Result getUserList(String accesstoken,String tagid ,String next_openid) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(tagid))return Result.error(-1,"tagid不能为空");
        String url = MessageFormat.format(TAGS_GETUSER_POST, accesstoken);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tagid",tagid);
        jsonObject.put("next_openid",next_openid);
        String param = jsonObject.toString();
        String ret = HttpClient.httpsRequest(url, "POST",param);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            TagsUserList tagsUserList = JSONObject.toJavaObject(retJson,TagsUserList.class);
            return tagsUserList;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 新增圖文素材
     * @param weixinNewsitemsParam
     * @param accesstoken
     * @return
     */
    public Result addNewsitem(WeixinNewsitemsParam weixinNewsitemsParam,String accesstoken){
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(weixinNewsitemsParam == null || weixinNewsitemsParam.getArticles() == null ||
                weixinNewsitemsParam.getArticles().size() == 0){
            return Result.error(-1,"参数為空");
        }
        List<WeixinNewsitemParam> articles = weixinNewsitemsParam.getArticles();
        for(WeixinNewsitemParam map:articles){
            if (StringUtils.isEmpty(map.getTitle())) return Result.error(-1,"title不能为空");
            if (StringUtils.isEmpty(map.getThumb_media_id())) return Result.error(-1,"thumb_media_id不能为空");
            if (StringUtils.isEmpty(map.getShow_cover_pic())) return Result.error(-1,"show_cover_pic不能为空");
            if (StringUtils.isEmpty(map.getContent())) return Result.error(-1,"content不能为空");
            if (StringUtils.isEmpty(map.getContent_source_url())) return Result.error(-1,"content_source_url不能为空");
        }
        String url = MessageFormat.format(ADD_NEWSITEM_URL, accesstoken);
        String json = JSON.toJSONString(weixinNewsitemsParam);
        String ret = HttpClient.httpsRequest(url, "POST",json);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            NewItemMedia newItemMedia = JSONObject.toJavaObject(retJson,NewItemMedia.class);
            return newItemMedia;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    /**
     * 刪除永久素材
     * @param accesstoken
     * @param mediaId
     * @return
     */
    @Override
    public Result deleteNewsitem(String accesstoken, String mediaId) {
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        if(StringUtils.isEmpty(mediaId))return Result.error(-1,"mediaId不能为空");
        String url = MessageFormat.format(DEL_NEWSITEM_URL, accesstoken);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("media_id",mediaId);
        String param = jsonObject.toString();
        String ret = HttpClient.httpsRequest(url, "POST",param);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Result Result = JSONObject.toJavaObject(retJson,Result.class);
            return Result;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    @Override
    public Result updateNewsitem(String accesstoken, WeixinUpdateParam weixinUpdateParam) {
        //判空
        if(StringUtils.isEmpty(accesstoken))return Result.error(-1,"accesstoken不能为空");
        String url = MessageFormat.format(UPDATE_NEWSITEM_URL, accesstoken);
        String param = JSON.toJSONString(weixinUpdateParam);
        String ret = HttpClient.httpsRequest(url, "POST",param);
        try{
            JSONObject retJson = JSONObject.parseObject(ret);
            Result Result = JSONObject.toJavaObject(retJson,Result.class);
            return Result;
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(-1,"请求异常，请联系开发人员");
        }
    }

    @Override
    public Result uploadMedia(String filePath, String token,String type){
        if (StringUtils.isEmpty(filePath)) return Result.error(-1, "filePath不能为空");
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        String url = MessageFormat.format(UPLOAD_MEDIA, token, type);
        try {
            File file = new File(filePath);
            String result = HttpClient.connectHttpsByPost(url,null, file);
            log.info(" 获取临时素材 result>> "+result);
            JSONObject retJson = JSONObject.parseObject(result);
            log.info(" 获取临时素材 retJson>> "+retJson);
            Material material = JSONObject.toJavaObject(retJson, Material.class);
            return material;
        } catch (Exception e) {
            e.printStackTrace();
            log.info(" 获取临时素材 exception "+e.getMessage());
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    @Override
    public Result uploadMediaByNetUrl(String fileUrl, String token,String type){
        if (StringUtils.isEmpty(fileUrl)) return Result.error(-1, "fileUrl不能为空");
        if (StringUtils.isEmpty(token)) return Result.error(-1, "token不能为空");
        String url = MessageFormat.format(UPLOAD_MEDIA, token, type);
        try {
            File file = downloadWxImage(fileUrl);
            String result = HttpClient.connectHttpsByPost(url,null, file);
            log.info(" 获取临时素材 result>> "+result);
            JSONObject retJson = JSONObject.parseObject(result);
            log.info(" 获取临时素材 retJson>> "+retJson);
            Material material = JSONObject.toJavaObject(retJson, Material.class);
            return material;
        } catch (Exception e) {
            e.printStackTrace();
            log.info(" 获取临时素材 exception "+e.getMessage());
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    public static File downloadWxImage(String url) {
        File file = null;
        URL urlfile;
        InputStream inputStream = null;
        OutputStream outputStream= null;
        try {
            file = File.createTempFile("wx_image", ".png");
            //下载
            urlfile = new URL(url);
            inputStream = urlfile.openStream();
            outputStream= new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

}
