package com.platform.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.platform.entity.TmLiveRoomInfo;
import com.platform.service.custom.LiveRoomInfoService;
import com.platform.utils.ResourceUtil;
import com.platform.utils.WxOpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

/**
 * @author abnerhou
 * @date 2020/9/17 10:43
 * @desciption
 */

@Component
@EnableScheduling
@Async
@Slf4j
public class WxLiveRoomUpdateTask {

    @Autowired
    private LiveRoomInfoService liveRoomInfoService;

    public final int PAGE_SIZE = 100;


    @Scheduled(cron = "0 */5 * * * ?")
    public void run() throws InterruptedException {
        IPage<TmLiveRoomInfo> resultPage = liveRoomInfoService.getListByCreateTime(1, 5);
        if (null != resultPage && !CollectionUtils.isEmpty(resultPage.getRecords())) {
            TmLiveRoomInfo tmLiveRoomInfo = resultPage.getRecords().get(0);
            Long roomId = tmLiveRoomInfo.getRoomId();
            long total = resultPage.getTotal();
            if (null != roomId) {
                long pages = total / PAGE_SIZE;
                long left = total % PAGE_SIZE;
                if (left > 0) {
                    pages += 1;
                }
                int startRoomId = roomId.intValue();
                log.info("当天需要更新直播间的个数为:{}，页数为:{},每页大小为:{},起始roomId为:{}", total, pages, PAGE_SIZE, startRoomId);
                if (pages > 0) {
                    for (int i = 0; i < pages; i++) {
                        JSONObject result = WxOpUtils.getLiveRoomList(0, PAGE_SIZE, ResourceUtil.getConfigByName("wx.appId"),
                                ResourceUtil.getConfigByName("wx.secret"));
                        parseWxRsp(result);
                        startRoomId += PAGE_SIZE;
                    }
                }

            }


        }

    }

    private void parseWxRsp(JSONObject rsp) {
        if (null != rsp) {
            int errcode = rsp.getInteger("errcode");
            if (errcode == 0) {
                JSONArray roomInfo = rsp.getJSONArray("room_info");
                if (null != roomInfo) {
                    List<JSONObject> objList = roomInfo.toJavaList(JSONObject.class);
                    doUpdateRoomStatus(objList);
                }
            }

        }
    }

    public void doUpdateRoomStatus(List<JSONObject> objList) {
        if (CollectionUtils.isEmpty(objList)) {
            return;
        }
        objList.forEach(obj -> {
            if (null != obj) {
                int roomId = null != obj.getInteger("roomid") ? obj.getInteger("roomid") : -1;
                int liveStatus = null != obj.getInteger("live_status") ? obj.getInteger("live_status") : -1;
                long endTime = null != obj.getLong("end_time") ? obj.getLong("end_time") : 0;
                Instant timestamp = Instant.ofEpochMilli(endTime * 1000);
                LocalDateTime endTimeDate = null;
                if (null != timestamp) {
                    endTimeDate = LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault());
                }
                LocalDateTime todayZero = LocalDateTime.of(LocalDate.now().getYear(),
                        LocalDate.now().getMonth(), LocalDate.now().getDayOfMonth(),
                        0, 0, 0);
                if (null != endTimeDate && endTimeDate.isBefore(todayZero)) {
                    log.info("房间[{}]停播时间已经是昨天之前，跳过更新状态", roomId);
                } else {
                    if (roomId != -1 && liveStatus != -1) {
                        TmLiveRoomInfo liveRoomInfo = liveRoomInfoService.getByRoomId(roomId);
                        if (null != liveRoomInfo && (null == liveRoomInfo.getLiveStatus() || liveRoomInfo.getLiveStatus() != liveStatus)) {
                            liveRoomInfo.setLiveStatus(liveStatus);
                            liveRoomInfoService.updateLiveRoom(liveRoomInfo);
                        }
                    }
                }
            }
        });
    }
}
