package com.tzld.piaoquan.api.service.contentplatform.impl;

import com.tzld.piaoquan.api.common.enums.ExceptionEnum;
import com.tzld.piaoquan.api.common.enums.contentplatform.DeletedStatusEnum;
import com.tzld.piaoquan.api.common.enums.contentplatform.UploadVideoAuditStatusEnum;
import com.tzld.piaoquan.api.common.exception.CommonException;
import com.tzld.piaoquan.api.component.VideoApiService;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformGzhPlanVideoMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformQwPlanVideoMapper;
import com.tzld.piaoquan.api.dao.mapper.contentplatform.ContentPlatformUploadVideoMapper;
import com.tzld.piaoquan.api.model.config.LoginUserContext;
import com.tzld.piaoquan.api.model.param.contentplatform.DeleteVideoParam;
import com.tzld.piaoquan.api.model.param.contentplatform.PublishVideoParam;
import com.tzld.piaoquan.api.model.param.contentplatform.UploadVideoListParam;
import com.tzld.piaoquan.api.model.param.contentplatform.VideoAuditCallBackParam;
import com.tzld.piaoquan.api.model.po.contentplatform.*;
import com.tzld.piaoquan.api.model.vo.contentplatform.UploadVideoItemVO;
import com.tzld.piaoquan.api.service.contentplatform.ContentPlatformSettingService;
import com.tzld.piaoquan.api.service.contentplatform.ContentPlatformUploadContentService;
import com.tzld.piaoquan.api.util.CdnUtil;
import com.tzld.piaoquan.growth.common.utils.page.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ContentPlatformUploadContentServiceImpl implements ContentPlatformUploadContentService {

    @Autowired
    ContentPlatformUploadVideoMapper uploadVideoMapper;
    @Autowired
    ContentPlatformSettingService settingService;
    @Autowired
    VideoApiService videoApiService;
    @Autowired
    ContentPlatformGzhPlanVideoMapper gzhPlanVideoMapper;
    @Autowired
    ContentPlatformQwPlanVideoMapper qwPlanVideoMapper;

    @Override
    public UploadVideoItemVO publishVideo(PublishVideoParam param) {
        if (param.getVideoId() != null) {
            return updateVideo(param);
        } else {
            return createVideo(param);
        }
    }

    @Override
    public UploadVideoItemVO createVideo(PublishVideoParam param) {
        ContentPlatformAccount user = LoginUserContext.getUser();
        ContentPlatformPqAccountRel pqAccountRel = settingService.getPqAccountRel(user.getId());
        if (pqAccountRel == null) {
            throw new CommonException(ExceptionEnum.PQ_ACCOUNT_NOT_BINDING);
        }
        if (StringUtils.isBlank(param.getTitle())
                || StringUtils.isBlank(param.getCoverUrl())
                || StringUtils.isBlank(param.getVideoUrl())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR);
        }
        if (!param.getCoverUrl().startsWith("http")) {
            param.setCoverUrl(CdnUtil.VIDEO_CDN_URL_HOST + param.getCoverUrl());
        }
        // 调用视频发布 获取videoId
        Long videoId = videoApiService.publishVideo(pqAccountRel.getPqUid(), param.getVideoUrl(), param.getCoverUrl(), param.getTitle());
        if (videoId == null) {
            throw new CommonException(ExceptionEnum.VIDEO_PUBLISH_FAILED);
        }
        if (!param.getVideoUrl().startsWith("http")) {
            param.setVideoUrl(CdnUtil.VIDEO_CDN_URL_HOST + param.getVideoUrl());
        }
        ContentPlatformUploadVideo uploadVideo = new ContentPlatformUploadVideo();
        uploadVideo.setVideoId(videoId);
        uploadVideo.setTitle(param.getTitle());
        uploadVideo.setCover(param.getCoverUrl());
        uploadVideo.setVideo(param.getVideoUrl());
        uploadVideo.setAuditStatus(UploadVideoAuditStatusEnum.WAIT_AUDIT.getVal());
        uploadVideo.setCreateAccountId(user.getId());
        uploadVideo.setCreateTimestamp(System.currentTimeMillis());
        uploadVideo.setUpdateTimestamp(System.currentTimeMillis());
        uploadVideoMapper.insertSelective(uploadVideo);
        return UploadVideoItemVO.convert(uploadVideo);
    }

    @Override
    public UploadVideoItemVO updateVideo(PublishVideoParam param) {
        ContentPlatformAccount user = LoginUserContext.getUser();
        ContentPlatformUploadVideo uploadVideo = getUploadVideo(param.getVideoId());
        if (uploadVideo == null) {
            return null;
        }
        if (!Objects.equals(user.getId(), uploadVideo.getCreateAccountId())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR);
        }
        if (StringUtils.isBlank(param.getTitle())
                || StringUtils.isBlank(param.getCoverUrl())
                || StringUtils.isBlank(param.getVideoUrl())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR);
        }
        if (!param.getCoverUrl().startsWith("http")) {
            param.setCoverUrl(CdnUtil.VIDEO_CDN_URL_HOST + param.getCoverUrl());
        }
        if (!param.getVideoUrl().startsWith("http")) {
            param.setVideoUrl(CdnUtil.VIDEO_CDN_URL_HOST + param.getVideoUrl());
        }
        // 调用修改视频接口
        ContentPlatformPqAccountRel pqAccountRel = settingService.getPqAccountRel(user.getId());
        videoApiService.updateVideo(pqAccountRel.getPqUid(), uploadVideo.getVideoId(), param.getCoverUrl(), param.getTitle());
        // save
        uploadVideo.setTitle(param.getTitle());
        uploadVideo.setCover(param.getCoverUrl());
        uploadVideo.setAuditStatus(UploadVideoAuditStatusEnum.AUDITING.getVal());
        uploadVideo.setUpdateTimestamp(System.currentTimeMillis());
        uploadVideoMapper.updateByPrimaryKeySelective(uploadVideo);
        return UploadVideoItemVO.convert(uploadVideo);
    }

    private ContentPlatformUploadVideo getUploadVideo(Long videoId) {
        ContentPlatformUploadVideoExample example = new ContentPlatformUploadVideoExample();
        example.createCriteria().andVideoIdEqualTo(videoId);
        List<ContentPlatformUploadVideo> uploadVideos = uploadVideoMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(uploadVideos)) {
            return null;
        }
        return uploadVideos.get(0);
    }

    @Override
    public void deleteVideo(DeleteVideoParam param) {
        ContentPlatformAccount user = LoginUserContext.getUser();
        ContentPlatformUploadVideo uploadVideo = getUploadVideo(param.getVideoId());
        if (uploadVideo == null) {
            return;
        }
        if (!Objects.equals(user.getId(), uploadVideo.getCreateAccountId())) {
            throw new CommonException(ExceptionEnum.PARAM_ERROR);
        }
        // 检查视频是否被引用
        if (checkVideoCited(uploadVideo)) {
            throw new CommonException(ExceptionEnum.VIDEO_CITED);
        }
        uploadVideo.setIsDelete(DeletedStatusEnum.DELETED.getVal());
        uploadVideo.setUpdateTimestamp(System.currentTimeMillis());
        uploadVideoMapper.updateByPrimaryKeySelective(uploadVideo);
        // 调用删除视频接口
        ContentPlatformPqAccountRel pqAccountRel = settingService.getPqAccountRel(user.getId());
        videoApiService.deleteVideo(pqAccountRel.getPqUid(), uploadVideo.getVideoId());
    }

    private Boolean checkVideoCited(ContentPlatformUploadVideo uploadVideo) {
        Boolean result = false;
        ContentPlatformGzhPlanVideoExample example = new ContentPlatformGzhPlanVideoExample();
        example.createCriteria().andVideoIdEqualTo(uploadVideo.getVideoId());
        List<ContentPlatformGzhPlanVideo> gzhPlanVideos = gzhPlanVideoMapper.selectByExample(example);
        if (CollectionUtils.isNotEmpty(gzhPlanVideos)) {
            result = true;
            return result;
        }
        ContentPlatformQwPlanVideoExample qwPlanVideoExample = new ContentPlatformQwPlanVideoExample();
        qwPlanVideoExample.createCriteria().andVideoIdEqualTo(uploadVideo.getVideoId());
        List<ContentPlatformQwPlanVideo> qwPlanVideos = qwPlanVideoMapper.selectByExample(qwPlanVideoExample);
        if (CollectionUtils.isNotEmpty(qwPlanVideos)) {
            result = true;
        }
        return result;
    }

    @Override
    public void videoAuditCallBack(VideoAuditCallBackParam param) {
        ContentPlatformUploadVideo uploadVideo = getUploadVideo(param.getVideoId());
        if (uploadVideo == null) {
            return;
        }
        // 转化审核状态
        Integer auditStatus = UploadVideoAuditStatusEnum.parsePqAuditStatus(param.getAuditStatus());
        uploadVideo.setAuditStatus(auditStatus);
        // 更改审核失败原因
        if (auditStatus.equals(UploadVideoAuditStatusEnum.AUDIT_REJECT.getVal())) {
            String auditReason = parseAuditReason(param.getReason());
            uploadVideo.setAuditReason(auditReason);
        }
        uploadVideo.setUpdateTimestamp(System.currentTimeMillis());
        uploadVideoMapper.updateByPrimaryKeySelective(uploadVideo);
    }

    private String parseAuditReason(String auditReason) {
        if (StringUtils.isBlank(auditReason)) {
            return "内容违规";
        }
        if (auditReason.contains("标题")) {
            return "标题违规";
        } else if (auditReason.contains("封面")) {
            return "封面违规";
        } else {
            return "内容违规";
        }
    }

    @Override
    public Page<UploadVideoItemVO> uploadVideoList(UploadVideoListParam param) {
        ContentPlatformAccount user = LoginUserContext.getUser();
        Page<UploadVideoItemVO> result = new Page<>(param.getPageNum(), param.getPageSize());
        Long count = getUploadVideoCount(param, user.getId());
        result.setTotalSize(count.intValue());
        if (count == 0) {
            result.setObjs(new ArrayList<>());
            return result;
        }
        List<ContentPlatformUploadVideo> videoList = getUploadVideoList(param, user.getId());
        List<UploadVideoItemVO> list = buildUploadVideoItemVOList(videoList);
        result.setObjs(list);
        return result;
    }

    private Long getUploadVideoCount(UploadVideoListParam param, Long accountId) {
        ContentPlatformUploadVideoExample example = new ContentPlatformUploadVideoExample();
        ContentPlatformUploadVideoExample.Criteria criteria = example.createCriteria();
        if (param.getAuditStatus() != null) {
            criteria.andAuditStatusEqualTo(param.getAuditStatus());
        }
        if (StringUtils.isNotBlank(param.getTitle())) {
            criteria.andTitleLike("%" + param.getTitle() + "%");
        }
        criteria.andCreateAccountIdEqualTo(accountId);
        criteria.andIsDeleteEqualTo(DeletedStatusEnum.NOT_DELETED.getVal());
        return uploadVideoMapper.countByExample(example);
    }

    private List<ContentPlatformUploadVideo> getUploadVideoList(UploadVideoListParam param, Long id) {
        ContentPlatformUploadVideoExample example = new ContentPlatformUploadVideoExample();
        ContentPlatformUploadVideoExample.Criteria criteria = example.createCriteria();
        if (param.getAuditStatus() != null) {
            criteria.andAuditStatusEqualTo(param.getAuditStatus());
        }
        if (StringUtils.isNotBlank(param.getTitle())) {
            criteria.andTitleLike("%" + param.getTitle() + "%");
        }
        criteria.andCreateAccountIdEqualTo(id);
        criteria.andIsDeleteEqualTo(DeletedStatusEnum.NOT_DELETED.getVal());
        example.setOrderByClause("create_timestamp desc");
        example.setPage(new Page<>(param.getPageNum(), param.getPageSize()));
        return uploadVideoMapper.selectByExample(example);
    }

    private List<UploadVideoItemVO> buildUploadVideoItemVOList(List<ContentPlatformUploadVideo> videoList) {
        if (CollectionUtils.isEmpty(videoList)) {
            return new ArrayList<>();
        }
        return videoList.stream().map(UploadVideoItemVO::convert).collect(Collectors.toList());
    }

}
