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

import com.alibaba.fastjson.JSONObject;
import com.tzy.s.wx.applet.dto.*;
import com.tzy.s.wx.dto.Result;
import com.tzy.s.wx.applet.service.WxAppletBroadcastApi;
import com.tzy.s.wx.util.HttpClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序直播
 */
@Slf4j
@Service
public class WxAppletBroadcastApiImpl implements WxAppletBroadcastApi {

    //create
    private static String ADD_LIVES = "https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token={0}";
    //删除直播间
    private static String DEL_LIVES = "https://api.weixin.qq.com/wxaapi/broadcast/room/deleteroom?access_token={0}";
    //编辑直播间
    private static String EDIT_LIVES = "https://api.weixin.qq.com/wxaapi/broadcast/room/editroom?access_token={0}";
    //获取直播间推流地址
    private static String GET_PUSH_URL = "https://api.weixin.qq.com/wxaapi/broadcast/room/getpushurl?access_token={0}";
    //获取直播间分享二维码
    private static String GET_SHARED_CODE = "https://api.weixin.qq.com/wxaapi/broadcast/room/getsharedcode?access_token={0}";
    //直播间列表- 直播回放
    private static String LIVES_INFO = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token={0}";
    //导入商品
    private static String ADD_GOODS = "https://api.weixin.qq.com/wxaapi/broadcast/room/addgoods?access_token={0}";
    //添加主播副号
    private static String ADD_SUBANCHOR = "https://api.weixin.qq.com/wxaapi/broadcast/room/addsubanchor?access_token={0}";
    //修改主播副号
    private static String EDIT_SUBANCHOr = "https://api.weixin.qq.com/wxaapi/broadcast/room/modifysubanchor?access_token=";
    //删除主播副号
    private static String DEL_SUBANCHOR = "https://api.weixin.qq.com/wxaapi/broadcast/room/deletesubanchor?access_token={0}";
    //获取主播副号
    private static String GET_SUBANCHOR = "https://api.weixin.qq.com/wxaapi/broadcast/room/getsubanchor?access_token={0}";
    //-----------------
    //设置成员角色
    private static String ADD_ROLE = "https://api.weixin.qq.com/wxaapi/broadcast/role/addrole?access_token={0}";
    //接触成员角色
    private static String DEL_ROLE = "https://api.weixin.qq.com/wxaapi/broadcast/role/deleterole?access_token={0}";
    //查询成员角色
    private static String GET_ROLE = "https://api.weixin.qq.com/wxaapi/broadcast/role/getrolelist?access_token={0}";

    //------------------------------
    //获取长期订阅用户
    private static String GET_WXA_FOLLOWERS = "https://api.weixin.qq.com/wxa/business/get_wxa_followers?access_token={0}";
    //向长期订阅用户群发直播间开始事件
    private static String PUSH_MESSAGE = "https://api.weixin.qq.com/wxa/business/push_message?access_token={0}";

    /**
     * 小程序直播-直播间操作
     * @param token
     * @param jsonObject
     * @return
     */
    @Override
    public Result holdRoom(String method,String token, JSONObject jsonObject){
        if(StringUtils.isEmpty(method)) return Result.error(-1,"操作类型不明确！");
        String url = "";
        if("delete".equals(method)){
            url = MessageFormat.format(DEL_LIVES, token);
        }else if("edit".equals(method)){
            url = MessageFormat.format(EDIT_LIVES, token);
        }else if("add".equals(method)){
            url = MessageFormat.format(ADD_LIVES, token);
        }
        System.out.println("url>>"+url);
        return getRoomsInfo(url,jsonObject);
    }

    /**
     * 获取直播间推流地址
     * @param token
     * @param jsonObject
     * @return
     */
    @Override
    public Result getPushUrl(String token,JSONObject jsonObject){
        String url = MessageFormat.format(GET_PUSH_URL, token);
        System.out.println("url>>"+url);
        return getRoomsInfo(url,jsonObject);
    }
    /**
     * 获取直播间分享二维码
     * @param token
     * @param jsonObject
     * @return
     */
    @Override
    public Result getSharedCode(String token,JSONObject jsonObject){
        String url = MessageFormat.format(GET_SHARED_CODE, token);
        System.out.println("url>>"+url);
        return getRoomsInfo(url,jsonObject);
    }

    private Result getRoomsInfo (String url ,JSONObject jsonObject ){
        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println("jsonObject>>"+jsonObject);
        Map header = new HashMap<>();
        header.put("Content-Type","application/json");
        String ret = HttpClient.httpsRequest(url, "POST", jsonStr,header);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            JSONObject retJson = JSONObject.parseObject(ret);
            Rooms rooms = JSONObject.toJavaObject(retJson, Rooms.class);
            log.info(" 创建直播间》》》 "+retJson);
            return rooms;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 获取直播间列表
     * @param token
     * @param jsonObject
     * @return
     */
    @Override
    public Result<?> getLiveInfo(String token, JSONObject jsonObject){
        String url = MessageFormat.format(LIVES_INFO, token);
        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println("jsonObject>>"+jsonObject);
        Map header = new HashMap<>();
        header.put("Content-Type","application/json");
        String ret = HttpClient.httpsRequest(url, "GET", jsonStr,header);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            net.sf.json.JSONObject retJson = net.sf.json.JSONObject.fromObject(ret);
            Map clazzMap= new HashMap();
            clazzMap.put("room_info",RoomInfo.class);
            clazzMap.put("goods",Goods.class);
            RoomInfos rooms = (RoomInfos) net.sf.json.JSONObject.toBean(retJson, RoomInfos.class,clazzMap);
            return rooms;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 直播间回放
     * @param token
     * @param jsonObject
     * @return
     */
    @Override
    public Result getLiveReplays(String token,JSONObject jsonObject){
        String url = MessageFormat.format(LIVES_INFO, token);
        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println("jsonObject>>"+jsonObject);
        Map header = new HashMap<>();
        header.put("Content-Type","application/json");
        String ret = HttpClient.httpsRequest(url, "POST", jsonStr,header);
        if (StringUtils.isEmpty(ret)) return Result.error(-1, "请求失败");
        try {
            net.sf.json.JSONObject retJson = net.sf.json.JSONObject.fromObject(ret);
            log.info("直播间回放>> "+retJson);
            Map clazzMap= new HashMap();
            clazzMap.put("live_replay",LiveReplay.class);
            clazzMap.put("room_info",RoomInfo.class);
            clazzMap.put("goods", Goods.class);
            LiveReplays liveReplays = (LiveReplays) net.sf.json.JSONObject.toBean(retJson, LiveReplays.class,clazzMap);
            return liveReplays;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

    /**
     * 小程序直播-角色管理
     * @return
     */
    @Override
    public Result holdLiveRole(String method,String token,JSONObject jsonObject){
        if(StringUtils.isEmpty(method)) return Result.error(-1,"操作类型不明确！");
        String url = "";
        if("delete".equals(method)){
            url = MessageFormat.format(DEL_ROLE, token);
        }else if("get".equals(method)){
            url = MessageFormat.format(GET_ROLE, token);
            url = url+jsonObject.getString("urlParam");
        }else if("add".equals(method)){
            url = MessageFormat.format(ADD_ROLE, token);
        }
        String jsonStr = JSONObject.toJSONString(jsonObject);
        System.out.println("jsonObject>>"+jsonObject);
        Map header = new HashMap<>();
        header.put("Content-Type","application/json");
        String ret = HttpClient.httpsRequest(url, "get".equals(method) ? "GET":"POST","get".equals(method) ? null: jsonStr,header);
        if (StringUtils.isEmpty(ret)){ return Result.error(-1, "请求失败");}
        try {
            net.sf.json.JSONObject retJson = net.sf.json.JSONObject.fromObject(ret);
            Map clazzMap= new HashMap();
            clazzMap.put("list",Role.class);
            RoleInfos liveReplays = (RoleInfos) net.sf.json.JSONObject.toBean(retJson, RoleInfos.class,clazzMap);
            /**
             * 400001: 微信号不合规
             * 400002: 微信号需要实名认证，仅设置主播角色时可能出现
             * 400003: 添加角色达到上限（管理员10个，运营者500个，主播500个）
             * 400004: 重复添加角色
             * 400005: 主播角色删除失败，该主播存在未开播的直播间
             */
            if(liveReplays.getErrcode() == 400001){
                liveReplays.setErrmsg("微信号不合规");
            }
            if(liveReplays.getErrcode() == 400002){
                liveReplays.setErrmsg("微信号需要实名认证");
            }
            if(liveReplays.getErrcode() == 400003){
                liveReplays.setErrmsg("添加角色达到上限[500个]");
            }
            if(liveReplays.getErrcode() == 400004){
                liveReplays.setErrmsg("重复添加角色");
            }
            return liveReplays;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(-1, "请求异常，请联系开发人员");
        }
    }

}
