package com.slodon.b2b2c.controller.live;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.controller.common.UploadController;
import com.slodon.b2b2c.core.constant.ResponseConst;
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.*;
import com.slodon.b2b2c.enums.WxLiveUrlEnum;
import com.slodon.b2b2c.errors.WxCodeError;
import com.slodon.b2b2c.live.dto.LiveBroadcastDto;
import com.slodon.b2b2c.live.example.LiveBroadcastExample;
import com.slodon.b2b2c.live.example.LiveGoodsExample;
import com.slodon.b2b2c.live.pojo.LiveBroadcast;
import com.slodon.b2b2c.live.pojo.LiveGoods;
import com.slodon.b2b2c.live.vo.LivesVO;
import com.slodon.b2b2c.model.live.LiveBroadModel;
import com.slodon.b2b2c.model.live.LiveJobModel;
import com.slodon.b2b2c.seller.pojo.Vendor;
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.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "admin-微信直播管理")
@RestController
@Slf4j
@RequestMapping("v3/live/seller/broad")
public class LiveBroadController extends BaseController {

    private final static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

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

    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(WxLiveUrlEnum.ACCESS_TOKEN_URL.getUrl() + 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("添加临时素材")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "multipartFile", value = "文件", paramType = "formData", required = true)
    })
    @PostMapping(value = "upload", consumes = "multipart/*", headers = "content-type=multipart/form-data")
    public JsonResult mediaUpload(HttpServletRequest request,MultipartFile multipartFile) {
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            //先保存到本地
            JsonResult uploadImg = uploadController.uploadImg(multipartFile, "tempImg");
            resultMap = (HashMap<String, Object>) uploadImg.getData();
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.TEMP_UPLOAD.getUrl();
            url = url.replace("ACCESS_TOKEN",access_token).replace("TYPE","image");
            File file = MultipartFileToFile(multipartFile);
            String result = FileUploadUtil.postUploadSSL(url, file, file.getName());
            JSONObject jsonObject = JSONObject.parseObject(result);
            resultMap.put("mediaId",jsonObject.getString("media_id"));
//            resultMap.put("url",jsonObject.getString("media_id"));
//            resultMap.put("path",jsonObject.getString("media_id"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return SldResponse.success(resultMap);
    }
    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码
        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @ApiOperation("添加直播间")
    @PostMapping("/wxBroadcastRoomCreate")
    public JsonResult wxBroadcastRoomCreate(HttpServletRequest request,LiveBroadcastDto liveBroadcastDto) {
        HashMap<String, String> resultMap = new HashMap<>();
        try {
            Vendor vendor = UserUtil.getUser(request, Vendor.class);
            if (vendor == null || vendor.getVendorId() == null){
                return SldResponse.fail("获取商户id失败");
            }
            liveBroadcastDto.setVendorId(String.valueOf(vendor.getVendorId()));
            //校验
            checkParam(liveBroadcastDto,resultMap);
            if (String.valueOf(ResponseConst.STATE_FAIL).equals(resultMap.get("state").toString())){
                return SldResponse.fail(resultMap.get("msg"));
            }
            //获取token
            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 jsonObject.getString("qrcode_url") != null
                        ? SldResponse.fail("qrcode_url")
                        : SldResponse.fail( WxCodeError.WX_CODE.get(errCode));
            }
            liveBroadcastDto.setRoomId(String.valueOf(jsonObject.get("roomId")));
            liveBroadModel.broadcastRoomCreate(liveBroadcastDto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success(resultMap);
    }

    private void checkParam(LiveBroadcastDto liveBroadcastDto, HashMap<String, String> resultMap) throws ParseException {
        resultMap.put("state","255");
        if(liveBroadcastDto==null){
            resultMap.put("msg","请填写参数");
            return;
        }
        if(liveBroadcastDto.getName() == null || liveBroadcastDto.getName().length() < 3 || liveBroadcastDto.getName().length() > 17){
            resultMap.put("msg","直播间名字，最短3个汉字，最长17个汉字");
            return;
        }
        if(liveBroadcastDto.getCoverImg() == null){
            resultMap.put("msg","背景图必填");
            return;
        }
        if(liveBroadcastDto.getStartTimeStr() == null || liveBroadcastDto.getEndTimeStr() == null){
            resultMap.put("msg","开始和结束时间必填");
            return;
        }
        if(liveBroadcastDto.getAnchorName() == null || liveBroadcastDto.getAnchorName().length() < 2 || liveBroadcastDto.getAnchorName().length() > 15){
            resultMap.put("msg","主播昵称，最短2个汉字，最长15个汉字");
            return;
        }
        if(liveBroadcastDto.getAnchorWechat() == null){
            resultMap.put("msg","主播微信号不能为空");
            return;
        }
        if(liveBroadcastDto.getShareImg() == null){
            resultMap.put("msg","分享图必填");
            return;
        }
        if(liveBroadcastDto.getFeedsImg() == null){
            resultMap.put("msg","购物直播频道封面图必填");
            return;
        }
        if(liveBroadcastDto.getType() == null){
            liveBroadcastDto.setType(0);
        }
        if(liveBroadcastDto.getCloseLike() == null){
            resultMap.put("msg","是否关闭点赞必填");
            return;
        }
        if(liveBroadcastDto.getCloseGoods() == null){
            resultMap.put("msg","是否关闭货架必填");
            return;
        }
        if(liveBroadcastDto.getCloseComment() == null){
            resultMap.put("msg","是否关闭评论必填");
            return;
        }
        if(liveBroadcastDto.getCloseKf() == null){
            resultMap.put("msg","是否关闭客服必填");
            return;
        }
        Date startTimeDate = sdf.parse(liveBroadcastDto.getStartTimeStr());
        Date endTimeDate = sdf.parse(liveBroadcastDto.getEndTimeStr());
        Long startTime = startTimeDate.getTime() / 1000;
        Long endTime = endTimeDate.getTime() / 1000;

        if (startTime-System.currentTimeMillis()/1000<600){
            resultMap.put("msg","开始时间需要在当前时间的10分钟后 并且 开始时间不能在 6 个月后");
            return;
        }
        if (endTime-startTime<1800 || endTime-startTime>86400  ){
            resultMap.put("msg","开播时间和结束时间间隔不得短于30分钟，不得超过24小时");
            return;
        }
        liveBroadcastDto.setStartTime(startTimeDate.getTime() / 1000);
        liveBroadcastDto.setEndTime(endTimeDate.getTime() / 1000);


        resultMap.put("state","200");
    }

    @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) {
        Vendor vendor = UserUtil.getUser(request, Vendor.class);
        PagerInfo pager = WebUtil.handlerPagerInfo(request);
        LiveBroadcastExample example = new LiveBroadcastExample();
        example.setName(name);
        if (vendor != null && vendor.getVendorId() != null){
            example.setVendorId(String.valueOf(vendor.getVendorId()));
        }
        List<LiveBroadcast> livesList = liveBroadModel.getLivesList(example, pager);
        List<LivesVO> livesVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(livesList)) {
            livesList.forEach(node->{
                LivesVO vo = new LivesVO();
                try {
                    PropertyUtils.copyProperties(vo,node);
                    vo.setStartTimeStr(sdf.format(node.getStartTime()*1000));
                    vo.setEndTimeStr(sdf.format(node.getEndTime()*1000));
                    vo.setCoverImgUrl(FileUrlUtil.getFileUrl(vo.getCoverImgPath(), null));
                    vo.setFeedsImgUrl(FileUrlUtil.getFileUrl(vo.getFeedsImgPath(), null));
                    vo.setShareImgUrl(FileUrlUtil.getFileUrl(vo.getShareImgPath(), null));
                    vo.setLiveStatusName(getLiveStatusName(vo.getLiveStatus()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                livesVOS.add(vo);
            });
        }
        return SldResponse.success(new PageVO<>(livesVOS, pager));
    }
    private String getLiveStatusName(Integer liveStatus){
        switch (liveStatus){
            case 101: return "直播中";
            case 102: return "未开始";
            case 103: return "已结束";
            case 104: return "禁播";
            case 105: return "暂停";
            case 106: return "异常";
            case 107: return "已过期";
            default:return "状态异常";
        }
    };

    @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));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                log.warn("获取直播间列表及直播间信息："+reStr);
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
            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));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
            //添加到关联关系表
            liveBroadModel.addLiveGoodsRelation(Arrays.asList(ids),roomId);
        } 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)));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
            liveBroadModel.wxDelLive(roomId);
            return SldResponse.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("删除失败");
    }

    @ApiOperation("编辑直播间")
    @PostMapping("/wxBroadcastRoomEdit")
    public JsonResult wxBroadcastRoomEdit(HttpServletRequest request, LiveBroadcastDto liveBroadcastDto) {
        try {
            //校验
            HashMap<String, String> resultMap = new HashMap<>();
            checkParam(liveBroadcastDto,resultMap);
            if ("255".equals(resultMap.get("state"))){
                return SldResponse.fail(resultMap.get("msg"));
            }
            if (StringUtils.isEmpty(liveBroadcastDto.getRoomId())){
                return SldResponse.fail("直播间id不能为空");
            }
            String access_token = getToken();
            String url = WxLiveUrlEnum.EDIT_LIVE.getUrl()+access_token;
            liveBroadcastDto.setId(Integer.valueOf(liveBroadcastDto.getRoomId()));
            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 jsonObject.getString("qrcode_url") != null
                        ? SldResponse.fail("qrcode_url")
                        : SldResponse.fail( WxCodeError.WX_CODE.get(errCode));
            }

            LiveBroadcast live_broadcast = new LiveBroadcast();
            PropertyUtils.copyProperties(live_broadcast,liveBroadcastDto);
            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+"&roomId"+roomId;
            String reStr = HttpClientUtil.sendGet(url);
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询成功");
    }

    @ApiOperation("获取直播间分享二维码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
    })
    @GetMapping("/getSharedCode")
    public JsonResult getSharedCode(HttpServletRequest request,Integer roomId) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.GET_SHARED_CODE.getUrl()+access_token+"&roomId"+roomId;
            String reStr = HttpClientUtil.sendGet(url);
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询成功");
    }

    @ApiOperation("开启/关闭直播间官方收录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
            @ApiImplicitParam(name = "isFeedsPublic", value = "是否开启官方收录 【1: 开启，0：关闭】", paramType = "query"),
    })
    @GetMapping("/updateFeedPublic")
    public JsonResult updateFeedPublic(HttpServletRequest request,Integer roomId,Integer isFeedsPublic) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.UPDATE_FEED_PUBLIC.getUrl()+access_token;
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("roomId",roomId);
            hashMap.put("isFeedsPublic",isFeedsPublic);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(hashMap));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("成功");
    }

    @ApiOperation("开启/关闭回放功能")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
            @ApiImplicitParam(name = "closeReplay", value = "是否关闭回放 【0：开启，1：关闭】", paramType = "query"),
    })
    @GetMapping("/updateReplay")
    public JsonResult updateReplay(HttpServletRequest request,Integer roomId,Integer closeReplay) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.UPDATE_REPLAY.getUrl()+access_token;
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("roomId",roomId);
            hashMap.put("closeReplay",closeReplay);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(hashMap));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("成功");
    }

    @ApiOperation("开启/关闭客服功能")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
            @ApiImplicitParam(name = "closeKf", value = "是否关闭客服 【0：开启，1：关闭】", paramType = "query"),
    })
    @GetMapping("/updateKf")
    public JsonResult updateKf(HttpServletRequest request,Integer roomId,Integer closeKf) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.UPDATE_KF.getUrl()+access_token;
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("roomId",roomId);
            hashMap.put("closeKf",closeKf);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(hashMap));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("成功");
    }

    @ApiOperation("开启/关闭直播间全局禁言")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "roomId", value = "房间ID", paramType = "query"),
            @ApiImplicitParam(name = "banComment", value = "1-禁言，0-取消禁言", paramType = "query"),
    })
    @GetMapping("/updateComment")
    public JsonResult updateComment(HttpServletRequest request,Integer roomId,Integer banComment) {
        try {
            String access_token = getToken();
            //校验
            String url = WxLiveUrlEnum.UPDATE_COMMENT.getUrl()+access_token;
            HashMap<Object, Object> hashMap = new HashMap<>();
            hashMap.put("roomId",roomId);
            hashMap.put("banComment",banComment);
            String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(hashMap));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                return SldResponse.fail(WxCodeError.WX_CODE.get(errCode));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("成功");
    }

    //---------------------------------定时处理-------------------------------------

    @Resource
    private LiveJobModel liveJobModel;

    public boolean jobUpdateLiveInfoList() {
        //获取需要修改的最小roomId
        Integer roomId = liveJobModel.getLiveRoomId();
        if (roomId == null || roomId == 0) {
            return true;
        }
        //需要查询更新的数量
        Integer livesNum = liveJobModel.getLivesNum(roomId);

        try {
            String access_token = getToken();
            //循环修改
            for (int i = 0; i < livesNum; i += 50) {
                forUpdateLive(i, access_token);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private void forUpdateLive(Integer startIndex, String access_token) throws Exception {
        String url = WxLiveUrlEnum.GET_LIVE_LIST.getUrl()+ access_token;
        Map map = new HashMap();
        map.put("start", startIndex);
        map.put("limit",50);
        String reStr = HttpClientUtil.sendJsonPostNew(url,JSON.toJSONString(map));
        JSONObject jsonObject = JSONObject.parseObject(reStr);
        String errCode = jsonObject.getString("errcode");
        if (!"0".equals(errCode)){
            log.warn("获取直播间列表及直播间信息："+reStr);
            return ;
        }
        JSONArray roomInfos = jsonObject.getJSONArray("room_info");
        List<LivesVO> livesVOS = new ArrayList<>();
        for (int i = 0; i < roomInfos.size(); i++) {
            JSONObject infosJSONObject = roomInfos.getJSONObject(i);
            LivesVO livesVO = new LivesVO();
            livesVO.setRoomId(String.valueOf(infosJSONObject.get("roomid")));
            livesVO.setLiveStatus(infosJSONObject.getInteger("live_status"));
            livesVOS.add(livesVO);
        }
        liveJobModel.updateLivesType(livesVOS);
    }
}
