package com.zhongzheng.modules.course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhongzheng.common.exception.CustomException;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.common.utils.ServletUtils;
import com.zhongzheng.modules.course.bo.*;
import com.zhongzheng.modules.course.domain.CourseSectionBusiness;
import com.zhongzheng.modules.course.domain.CourseStreaming;
import com.zhongzheng.modules.course.domain.CourseStreamingBusiness;
import com.zhongzheng.modules.course.mapper.CourseSectionMapper;
import com.zhongzheng.modules.course.mapper.CourseStreamingMapper;
import com.zhongzheng.modules.course.service.ICourseSectionBusinessService;
import com.zhongzheng.modules.course.service.ICourseStreamingBusinessService;
import com.zhongzheng.modules.course.service.ICourseStreamingService;
import com.zhongzheng.modules.course.vo.CourseStreamingVo;
import com.zhongzheng.modules.polyv.service.IPolyvVideoService;
import com.zhongzheng.modules.polyv.vo.PolyvVideoQuerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 课程流媒体Service业务层处理
 *
 * @author hjl
 * @date 2021-10-11
 */
@Service
public class CourseStreamingServiceImpl extends ServiceImpl<CourseStreamingMapper, CourseStreaming> implements ICourseStreamingService {

    @Autowired
    private ICourseStreamingBusinessService iCourseStreamingBusinessService;

    @Autowired
    private CourseStreamingMapper courseStreamingMapper;

    @Autowired
    private IPolyvVideoService iPolyvVideoService;

    @Override
    public CourseStreamingVo queryById(Long id){
        CourseStreaming db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, CourseStreamingVo.class);
    }

    @Override
    public List<CourseStreamingVo> selectList(CourseStreamingQueryBo bo) {
        return courseStreamingMapper.selectList(bo);
    }

    @Override
    public List<CourseStreamingVo> queryList(CourseStreamingQueryBo bo) {
        LambdaQueryWrapper<CourseStreaming> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getStreamingType() != null, CourseStreaming::getStreamingType, bo.getStreamingType());
        lqw.like(StrUtil.isNotBlank(bo.getStreamingName()), CourseStreaming::getStreamingName, bo.getStreamingName());
        lqw.eq(StrUtil.isNotBlank(bo.getCode()), CourseStreaming::getCode, bo.getCode());
        lqw.eq(StrUtil.isNotBlank(bo.getLiveChannelNumber()), CourseStreaming::getLiveChannelNumber, bo.getLiveChannelNumber());
        lqw.eq(StrUtil.isNotBlank(bo.getLivePushUrl()), CourseStreaming::getLivePushUrl, bo.getLivePushUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getLivePullUrl()), CourseStreaming::getLivePullUrl, bo.getLivePullUrl());
        lqw.eq(StrUtil.isNotBlank(bo.getLiveUrl()), CourseStreaming::getLiveUrl, bo.getLiveUrl());
        lqw.eq(bo.getStreamingAddressType() != null, CourseStreaming::getStreamingAddressType, bo.getStreamingAddressType());
        lqw.eq(StrUtil.isNotBlank(bo.getIntroduce()), CourseStreaming::getIntroduce, bo.getIntroduce());
        lqw.eq(StrUtil.isNotBlank(bo.getRecordingVideoId()), CourseStreaming::getRecordingVideoId, bo.getRecordingVideoId());
        lqw.eq(StrUtil.isNotBlank(bo.getPlaybackUrl()), CourseStreaming::getPlaybackUrl, bo.getPlaybackUrl());
        lqw.eq(bo.getStatus() != null, CourseStreaming::getStatus, bo.getStatus());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<CourseStreamingVo> entity2Vo(Collection<CourseStreaming> collection) {
        List<CourseStreamingVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, CourseStreamingVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<CourseStreaming> page = (Page<CourseStreaming>)collection;
            Page<CourseStreamingVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByAddBo(CourseStreamingAddBo bo) {
        CourseStreaming add = BeanUtil.toBean(bo, CourseStreaming.class);
        add.setCode(ServletUtils.getEncoded("L"));
        validEntityBeforeSave(add);
        add.setCreateTime(DateUtils.getNowTime());
        add.setUpdateTime(DateUtils.getNowTime());
        boolean result = this.save(add);
        if(result){
            for(int i=0;i<bo.getBusinessList().size();i++){
                CourseStreamingBusinessAddBo item = bo.getBusinessList().get(i);
                item.setStreamingId(add.getId());
                iCourseStreamingBusinessService.insertByAddBo(item);
            }
        }
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByEditBo(CourseStreamingEditBo bo) {
        CourseStreaming update = BeanUtil.toBean(bo, CourseStreaming.class);
        validEntityBeforeSave(update);
        update.setUpdateTime(DateUtils.getNowTime());
        if(bo.getBusinessList()!= null){
            iCourseStreamingBusinessService.remove(new LambdaQueryWrapper<CourseStreamingBusiness>().eq(CourseStreamingBusiness::getStreamingId, bo.getId()));
            for(int i=0;i<bo.getBusinessList().size();i++){
                CourseStreamingBusinessAddBo item = bo.getBusinessList().get(i);
                item.setStreamingId(bo.getId());
                iCourseStreamingBusinessService.insertByAddBo(item);
            }
        }
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(CourseStreaming entity){
        //TODO 做一些数据校验,如唯一约束
        if(StringUtils.isNotBlank(entity.getRecordingVideoId())){
            try{
                PolyvVideoQuerVo polyvVideo = iPolyvVideoService.queryById(entity.getRecordingVideoId());
                if(polyvVideo == null){
                    throw new CustomException("保利威视频不存在");
                }
                entity.setPolyvId(polyvVideo.getPolyvId());
            }catch (Exception e){
                throw new CustomException("保利威视频错误");
            }

        }
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
