package com.slodon.b2b2c.controller.live;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.core.controller.BaseController;
import com.slodon.b2b2c.core.response.JsonResult;
import com.slodon.b2b2c.core.response.PageVO;
import com.slodon.b2b2c.core.response.PagerInfo;
import com.slodon.b2b2c.core.response.SldResponse;
import com.slodon.b2b2c.core.util.AssertUtil;
import com.slodon.b2b2c.core.util.HttpClientUtil;
import com.slodon.b2b2c.core.util.WebUtil;
import com.slodon.b2b2c.enums.WxLiveUrlEnum;
import com.slodon.b2b2c.live.dto.LiveBroadcastDto;
import com.slodon.b2b2c.live.dto.LiveBroadcastEditDto;
import com.slodon.b2b2c.live.example.LiveBroadcastExample;
import com.slodon.b2b2c.live.pojo.LiveBroadcast;
import com.slodon.b2b2c.live.vo.LivesVO;
import com.slodon.b2b2c.model.live.LiveBroadModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "admin-微信直播管理")
@RestController
@Slf4j
@RequestMapping("v3/live/broad")
public class LiveBroadController extends BaseController {
    private final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=";//获取access_token地址

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private LiveBroadModel liveBroadModel;

    private String getToken() throws Exception {
        String appId = stringRedisTemplate.opsForValue().get("login_wx_mini_appid");
        String secret = stringRedisTemplate.opsForValue().get("login_wx_mini_appsecret");
        String access_token_resp = HttpClientUtil.httpGet(ACCESS_TOKEN_URL + appId + "&secret=" + secret);
        String access_token = JSON.parseObject(access_token_resp).getString("access_token");
        AssertUtil.notEmpty(access_token, "微信认证失败");
        System.out.println("结果access_token: "+access_token);
        return access_token;
    }

//    @ApiOperation("添加临时素材")
//    @PostMapping("/mediaUpload")
//    public JsonResult mediaUpload(HttpServletRequest request, @RequestBody LiveBroadcastDto liveBroadcastDto) {
//        try {
//            String access_token = getToken();
//            //校验
//            String url = "https://api.weixin.qq.com/wxaapi/broadcast/room/create?access_token="+access_token;
//            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(liveBroadcastDto));
//            JSONObject jsonObject = JSONObject.parseObject(reStr);
//            String errCode = jsonObject.getString("errcode");
//            if (!"0".equals(errCode)){
//                log.warn("直播间添加失败原因："+reStr);
//                return SldResponse.success("添加失败");
//            }
//            liveBroadcastDto.setRoomId(String.valueOf(jsonObject.get("roomId")));
//            liveBroadModel.broadcastRoomCreate(liveBroadcastDto);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return SldResponse.success("添加成功");
//    }

    @ApiOperation("添加直播间")
    @PostMapping("/wxBroadcastRoomCreate")
    public JsonResult wxBroadcastRoomCreate(HttpServletRequest request, @RequestBody LiveBroadcastDto liveBroadcastDto) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.ADD_LIVE.getUrl()+access_token;
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(liveBroadcastDto));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                log.warn("直播间添加失败原因："+reStr);
                return SldResponse.success("添加失败");
            }
            liveBroadcastDto.setRoomId(String.valueOf(jsonObject.get("roomId")));
            liveBroadModel.broadcastRoomCreate(liveBroadcastDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("添加成功");
    }

    @ApiOperation("获取直播列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "直播名称", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", defaultValue = "20", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面位置", defaultValue = "1", paramType = "query")
    })
    @GetMapping("/list")
    public JsonResult<PageVO<LivesVO>> getList(HttpServletRequest request, String name) {
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        LiveBroadcastExample example = new LiveBroadcastExample();
        example.setName(name);
        List<LiveBroadcast> livesList = liveBroadModel.getLivesList(example, pager);
        List<LivesVO> livesVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(livesList)) {
            livesList.forEach(node->{
                LivesVO vo = new LivesVO();
                vo.setName(node.getName());
                vo.setAnchorName(node.getAnchorName());
                vo.setRoomId(node.getRoomId());
                livesVOS.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(livesVOS, pager));
    }

    @ApiOperation("获取直播间列表及直播间信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "start", value = "起始房间，0表示从第1个房间开始拉取", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每次拉取的房间数量，建议100以内", paramType = "query")
    })
    @GetMapping("/wxGetLiveInfoList")
    public JsonResult wxGetLiveInfoList(HttpServletRequest request, Integer start,Integer limit) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.GET_LIVE_LIST.getUrl()+access_token;
            Map map = new HashMap();
            map.put("start",start);
            map.put("limit",limit);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(map));
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询失败");
    }

    @ApiOperation("获取直播间回放")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
            @ApiImplicitParam(name = "start", value = "起始房间，0表示从第1个房间开始拉取", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每次拉取的房间数量，建议100以内", paramType = "query")
    })
    @GetMapping("/wxGetLivePlayback")
    public JsonResult wxGetLivePlayback(HttpServletRequest request,Integer roomId, Integer start,Integer limit) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.GET_LIVE_PLAYBACK.getUrl()+access_token;
            Map map = new HashMap();
            map.put("action","get_replay");
            map.put("room_id",roomId);
            map.put("start",start);
            map.put("limit",limit);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(map));
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询失败");
    }

    @ApiOperation("直播间导入商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "[商品 ID]", paramType = "query"),
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
    })
    @GetMapping("/wxAddLiveGoods")
    public JsonResult wxAddLiveGoods(HttpServletRequest request,Integer[] ids,Integer roomId) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.ADD_LIVE_GOODS.getUrl()+access_token;
            Map map = new HashMap();
            map.put("ids",ids);
            map.put("roomId",roomId);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(map));
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询失败");
    }

    @ApiOperation("删除直播间")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
    })
    @GetMapping("/wxDelLive")
    public JsonResult wxDelLive(HttpServletRequest request,Integer roomId) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.DEL_LIVE.getUrl()+access_token;
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(new HashMap<>().put("id",roomId)));
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询失败");
    }

    @ApiOperation("编辑直播间")
    @PostMapping("/wxBroadcastRoomEdit")
    public JsonResult wxBroadcastRoomEdit(HttpServletRequest request, @RequestBody LiveBroadcastEditDto liveBroadcastEditDto) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.EDIT_LIVE.getUrl()+access_token;
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(liveBroadcastEditDto));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                log.warn("直播间编辑失败原因："+reStr);
                return SldResponse.success("编辑失败");
            }
            LiveBroadcast live_broadcast = new LiveBroadcast();
            PropertyUtils.copyProperties(live_broadcast,liveBroadcastEditDto);
            live_broadcast.setRoomId(String.valueOf(liveBroadcastEditDto.getId()));
            liveBroadModel.broadcastRoomEdit(live_broadcast);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("编辑成功");
    }

    @ApiOperation("获取直播间推流地址")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
    })
    @GetMapping("/wxGetPushUrl")
    public JsonResult wxGetPushUrl(HttpServletRequest request,Integer roomId) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.GET_PUSH_LIVE.getUrl()+access_token;
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(new HashMap<>().put("id",roomId)));
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询失败");
    }

    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("start",1);
        map.put("limit",10);
        System.out.println(JSON.toJSONString(map));
    }

}
