package com.slodon.b2b2c.controller.live;


import com.alibaba.fastjson.JSON;
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.live.dto.LiveBroadcastDto;
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 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.*;

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

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

    @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(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 = "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();
                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));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                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));
            JSONObject jsonObject = JSONObject.parseObject(reStr);
            String errCode = jsonObject.getString("errcode");
            if (!"0".equals(errCode)){
                log.warn("获取直播间列表及直播间信息："+reStr);
                return SldResponse.fail(jsonObject.getString("errmsg"));
            }
            return SldResponse.success(reStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SldResponse.success("查询失败");
    }

}
