package com.tzld.piaoquan.api.component;

import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.model.vo.contentplatform.WxBaseUserInfoVO;
import com.tzld.piaoquan.api.model.vo.contentplatform.WxVideoV2VO;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class VideoApiService {

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Value("${video.api.host:https://videotest.yishihui.com}")
    private String videoApiHost;

    public List<String> getCoverImagePaths(Long videoId) {
        String url = videoApiHost + "/longvideoapi/video/getCoverImagePaths";
        try {
            String post = httpPoolClient.post(url, "id=" + videoId, "application/x-www-form-urlencoded;charset=UTF-8");
            JSONObject res = JSONObject.parseObject(post);
            JSONObject data = res.getJSONObject("data");
            return data.getJSONArray("videoCoverImages").toJavaList(String.class);
        } catch (Exception e) {
            log.error("VideoApiService getCoverImagePaths error", e);
        }
        return null;
    }

    public WxBaseUserInfoVO webLogin(String code, Integer appType, String appId, String machineCode) {
        String url = videoApiHost + "/longvideoapi/user/webLogin";
        try {
            String post = httpPoolClient.post(url, "code=" + code +
                    "&appType=" + appType +
                    "&appId=" + appId +
                    "&path=%2F" +
                    "&clientTimestamp=" + System.currentTimeMillis() +
                    "&loginUid=" +
                    "&token=" +
                    "&machineCode=" + machineCode, "application/x-www-form-urlencoded;charset=UTF-8");
            JSONObject res = JSONObject.parseObject(post);
            return res.getObject("data", WxBaseUserInfoVO.class);
        } catch (Exception e) {
            log.error("VideoApiService webLogin error", e);
        }
        return null;
    }

    public void saveUserPhoneNumber(Long uid, String phoneNumber) {
        String url = videoApiHost + "/longvideoapi/openapi/user/saveUserPhoneNumber";
        try {
            JSONObject param = new JSONObject();
            param.put("uid", uid);
            param.put("phoneNumber", phoneNumber);
            String post = httpPoolClient.post(url, param.toJSONString());
            JSONObject res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("VideoApiService saveUserPhoneNumber error", e);
        }
    }

    public Long publishVideo(Long uid, String videoUrl, String coverUrl, String title) {
        String url = videoApiHost + "/longvideoapi/crawler/video/send";
        JSONObject res = null;
        try {
            String param = "videoPath=" + videoUrl +
                    "&crawlerSrcCode=CONTENT" +
                    "&crawlerSrcPublishTimestamp=" + System.currentTimeMillis() +
                    "&crawlerTaskTimestamp=" + System.currentTimeMillis() +
                    "&coverImgPath=" + coverUrl +
                    "&appType=888888" +
                    "&loginUid=" + uid +
                    "&title=" + title +
                    "&viewStatus=1" +
                    "&versionCode=1";
            log.info("VideoApiService publishVideo param={}", param);
            String post = httpPoolClient.post(url, param, "application/x-www-form-urlencoded;charset=UTF-8");
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("VideoApiService publishVideo error", e);
        }
        if (Objects.isNull(res)) {
            return null;
        }
        if (res.getInteger("code") != 0) {
            log.error("publishVideo error, uid:{} videoUrl={} coverUrl={} title={} res={}", uid, videoUrl, coverUrl, title, res);
            throw new CommonException(ExceptionEnum.VIDEO_PUBLISH_FAILED.getCode(),
                    ExceptionEnum.VIDEO_PUBLISH_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        JSONObject data = res.getJSONObject("data");
        Long videoId = data.getLong("id");
        log.info("VideoApiService publishVideo success, uid:{} videoId={}", uid, videoId);
        return videoId;
    }

    public void updateVideo(Long uid, Long videoId, String coverUrl, String title) {
        String url = videoApiHost + "/longvideoapi/openapi/video/update";
        JSONObject res = null;
        try {
            JSONObject videoDetail = getVideoInfo(videoId);
            JSONObject chargeDetail = videoDetail.getJSONObject("chargeDetail");
            JSONObject param = new JSONObject();
            param.put("loginUid", uid);
            param.put("id", videoId);
            param.put("videoId", videoId);
            param.put("appType", 8);
            param.put("coverImgPath", coverUrl);
            param.put("title", title);
            param.put("viewStatus", 1);
            param.put("videoCollectionId", videoDetail.getLong("videoCollectionId"));
            param.put("barrageSwitch", videoDetail.getLong("barrageSwitch"));
            param.put("charge", chargeDetail.getInteger("charge"));
            param.put("price", chargeDetail.getLong("price"));
            param.put("allowIosPlay", chargeDetail.getLong("allowIosPlay"));
            param.put("allowDownload", 0);
            log.info("VideoApiService updateVideo param={}", param.toJSONString());
            String post = httpPoolClient.post(url, param.toJSONString());
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("VideoApiService updateVideo error", e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_UPDATE_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("VideoApiService updateVideo error, uid:{} videoId={} coverUrl={} title={} res={}", uid, videoId, coverUrl, title, res);
            throw new CommonException(ExceptionEnum.VIDEO_UPDATE_FAILED.getCode(), res.getString("msg"));
        }
    }

    public JSONObject getVideoInfo(Long videoId) {
        String url = videoApiHost + "/longvideoapi/openapi/video/getVideoInfo";
        JSONObject res = null;
        try {
            JSONObject param = new JSONObject();
            param.put("videoId", videoId);
            String post = httpPoolClient.post(url, param.toJSONString());
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("VideoApiService getVideoInfo error", e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_INFO_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("VideoApiService getVideoInfo error, videoId={} res={}", videoId, res);
            throw new CommonException(ExceptionEnum.VIDEO_INFO_FAILED.getCode(),
                    ExceptionEnum.VIDEO_INFO_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONObject("data");
    }

    public void deleteVideo(Long uid, Long videoId) {
        String url = videoApiHost + "/longvideoapi/openapi/video/delete";
        int retryCount = 3;
        while (retryCount > 0) {
            try {
                JSONObject param = new JSONObject();
                param.put("loginUid", uid);
                param.put("videoId", videoId);
                String post = httpPoolClient.post(url, param.toJSONString());
                JSONObject res = JSONObject.parseObject(post);
                if (Objects.isNull(res)) {
                    throw new CommonException(ExceptionEnum.VIDEO_DELETE_FAILED);
                }
                if (res.getInteger("code") != 0) {
                    log.error("VideoApiService deleteVideo error, videoId={} res={}", videoId, res);
                    throw new CommonException(ExceptionEnum.VIDEO_DELETE_FAILED.getCode(),
                            ExceptionEnum.VIDEO_DELETE_FAILED.getMsg() + "，" + res.getString("msg"));
                } else {
                    log.info("VideoApiService deleteVideo success, uid:{} videoId={}", uid, videoId);
                    return;
                }
            } catch (Exception e) {
                log.error("VideoApiService deleteVideo error", e);
            }
            retryCount--;
        }
    }

    public List<WxVideoV2VO> getUserVideoList(Long uid, List<Long> excludeVideoIds, Integer pageNum, Integer pageSize) {
        String url = videoApiHost + "/longvideoapi/openapi/video/getUserVideoListAuditPass";
        JSONObject res = null;
        try {
            JSONObject param = new JSONObject();
            param.put("uid", uid);
            param.put("excludeVideoIds", excludeVideoIds);
            param.put("pageNum", pageNum);
            param.put("pageSize", pageSize);
            String post = httpPoolClient.post(url, param.toJSONString());
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("VideoApiService getUserVideoList error, uid={} excludeVideoIds={} pageNum={} pageSize={}",
                    uid, excludeVideoIds, pageNum, pageSize, e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_GET_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("VideoApiService getUserVideoList error, uid={} excludeVideoIds={} pageNum={} pageSize={} res={}",
                    uid, excludeVideoIds, pageNum, pageSize, res);
            throw new CommonException(ExceptionEnum.VIDEO_GET_FAILED.getCode(),
                    ExceptionEnum.VIDEO_GET_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONArray("data").toJavaList(WxVideoV2VO.class);
    }

    public List<WxVideoV2VO> getTagVideoList(String tagName, String roomId, List<Long> excludeVideoIds, Integer pageNum, Integer pageSize) {
        String url = videoApiHost + "/longvideoapi/openapi/video/getTagVideoListAuditPass";
        JSONObject res = null;
        try {
            JSONObject param = new JSONObject();
            param.put("tagName", tagName);
            param.put("sentRoomId", roomId);
            param.put("excludeVideoIds", excludeVideoIds);
            param.put("pageNum", pageNum);
            param.put("pageSize", pageSize);
            String post = httpPoolClient.post(url, param.toJSONString());
            res = JSONObject.parseObject(post);
        } catch (Exception e) {
            log.error("VideoApiService getTagVideoList error, tagName={} excludeVideoIds={} pageNum={} pageSize={}",
                    tagName, excludeVideoIds, pageNum, pageSize, e);
        }
        if (Objects.isNull(res)) {
            throw new CommonException(ExceptionEnum.VIDEO_GET_FAILED);
        }
        if (res.getInteger("code") != 0) {
            log.error("VideoApiService getTagVideoList error, tagName={} excludeVideoIds={} pageNum={} pageSize={} res={}",
                    tagName, excludeVideoIds, pageNum, pageSize, res);
            throw new CommonException(ExceptionEnum.VIDEO_GET_FAILED.getCode(),
                    ExceptionEnum.VIDEO_GET_FAILED.getMsg() + "，" + res.getString("msg"));
        }
        return res.getJSONArray("data").toJavaList(WxVideoV2VO.class);
    }

}
