package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.auth.api.client.SysUserFeignService;
import com.yonge.cooleshow.auth.api.entity.SysUser;
import com.yonge.cooleshow.biz.dal.dao.TeacherDao;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonAuthRecordDao;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonGroupDao;
import com.yonge.cooleshow.biz.dal.dao.VideoLessonGroupDetailDao;
import com.yonge.cooleshow.biz.dal.dto.search.VideoGroupSearch;
import com.yonge.cooleshow.biz.dal.dto.search.VideoLessonGroupSearch;
import com.yonge.cooleshow.biz.dal.dto.search.VideoLessonSearch;
import com.yonge.cooleshow.biz.dal.entity.Subject;
import com.yonge.cooleshow.biz.dal.entity.VideoLessonAuthRecord;
import com.yonge.cooleshow.biz.dal.entity.VideoLessonGroup;
import com.yonge.cooleshow.biz.dal.entity.VideoLessonGroupDetail;
import com.yonge.cooleshow.biz.dal.enums.AuthStatusEnum;
import com.yonge.cooleshow.biz.dal.enums.ClientEnum;
import com.yonge.cooleshow.biz.dal.enums.MessageTypeEnum;
import com.yonge.cooleshow.biz.dal.service.SysConfigService;
import com.yonge.cooleshow.biz.dal.enums.TeacherTagEnum;
import com.yonge.cooleshow.biz.dal.service.SysMessageService;
import com.yonge.cooleshow.biz.dal.service.TeacherService;
import com.yonge.cooleshow.biz.dal.service.VideoLessonGroupService;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.cooleshow.common.constant.SysConfigConstant;
import com.yonge.cooleshow.common.enums.YesOrNoEnum;
import com.yonge.toolset.base.exception.BizException;
import com.yonge.toolset.base.string.MessageFormatter;
import com.yonge.toolset.thirdparty.message.MessageSenderPluginContext;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * VideoLessonGroupService服务实现类
 *
 * @author yzp
 * @version v1.0
 * @date 2022-03-26 00:01:38
 **/
@Service
public class VideoLessonGroupServiceImpl extends ServiceImpl<VideoLessonGroupDao, VideoLessonGroup> implements VideoLessonGroupService {

    private final static Logger log = LoggerFactory.getLogger(VideoLessonGroupServiceImpl.class);

    @Autowired
    private VideoLessonGroupDao videoLessonGroupDao;
    @Autowired
    private VideoLessonGroupDetailDao videoLessonGroupDetailDao;
    @Autowired
    private VideoLessonAuthRecordDao recordDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private SysMessageService sysMessageService;

    @Autowired
    private TeacherService teacherService;
    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private SysConfigService sysConfigService;

    public VideoLessonGroupDao getDao() {
        return videoLessonGroupDao;
    }

    /**
     * @Description: 查询视频课组
     * @Author: cy
     * @Date: 2022/3/31
     */
    @Override
    public IPage<VideoLessonGroupVo> selectPage(IPage<VideoLessonGroupVo> page, VideoLessonGroupSearch query) {
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    public List<VideoLessonGroupVo> selectPage(VideoLessonGroupSearch query) {
        List<VideoLessonGroupVo> list = baseMapper.selectPage(null, query);
        List<VideoLessonGroupVo> collect = list.stream().sorted(Comparator.comparing(VideoLessonGroupVo::getCountStudent, Comparator.reverseOrder())).limit(2).collect(Collectors.toList());
        return collect;
    }

    /**
     * @Description: 根据组id查详情
     * @Author: cy
     * @Date: 2022/4/11
     */
    public VideoLessonGroup selectGroup(Long groupId) {
        return videoLessonGroupDao.selectGroupById(groupId);
    }

    /**
     * @Description: 修改视频课组
     * @Author: cy
     * @Date: 2022/3/31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGroup(VideoLessonGroupUpVo lessonGroupUpVo) {
        videoLessonGroupDao.updateGroup(lessonGroupUpVo);
    }

    /**
     * @Description: 审核-修改视频课组审核状态
     * @Author: cy
     * @Date: 2022/4/24
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGroup(VideoLessonExamineVo examineVo) {
        //改主表
        videoLessonGroupDao.updateExamine(examineVo);

        VideoLessonGroup lessonGroup = baseMapper.selectById(examineVo.getId());
        //插从表
        VideoLessonAuthRecord record = new VideoLessonAuthRecord();
        record.setAuditStatus(examineVo.getAuditStatus());
        record.setVideoGroupId(examineVo.getId());
        record.setAuditId(examineVo.getAuditId());
        record.setAuditName(examineVo.getAuditName());
        record.setRemarks(examineVo.getRemarks());
        recordDao.insert(record);

        //清状态
        recordDao.delete(Wrappers.<VideoLessonAuthRecord>lambdaQuery()
                .eq(VideoLessonAuthRecord::getVideoGroupId, examineVo.getId())
                .eq(VideoLessonAuthRecord::getAuditStatus, AuthStatusEnum.DOING));

        // 设置标签
        if (AuthStatusEnum.PASS.getCode().equals(examineVo.getAuditStatus())) {
            teacherService.setTeacherTag(lessonGroup.getTeacherId(), TeacherTagEnum.VIDEO);
        }

        //推送
        String status = examineVo.getAuditStatus();
        Map<Long, String> receivers = new HashMap<>();
        SysUser teacher = sysUserFeignService.queryUserById(lessonGroup.getTeacherId());
        receivers.put(lessonGroup.getTeacherId(), teacher.getPhone());
        if (status.equals("PASS")) {
            try {
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIDEO_SHEET_AUTH_PASS,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), lessonGroup.getLessonName());
            } catch (Exception e) {
                log.warn("视频课审核失败，{}", e.getMessage());
            }
        } else {
            try {
                String remark = "无";
                if (!StringUtils.isEmpty(examineVo.getRemarks())) {
                    remark = examineVo.getRemarks();
                }
                sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.VIDEO_SHEET_AUTH_UNPASS,
                        receivers, null, 0, null, ClientEnum.TEACHER.getCode(), lessonGroup.getLessonName(), remark);
            } catch (Exception e) {
                log.warn("视频课审核失败，{}", e.getMessage());
            }
        }

    }

    /**
     * @Description: 删除视频课
     * @Author: cy
     * @Date: 2022/3/31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGroup(Long id) {
        videoLessonGroupDao.deleteById(id);
        videoLessonGroupDetailDao.deleteByGroupId(id);
    }

    /**
     * @Description: 新增视频课组&视频课
     * @Author: cy
     * @Date: 2022/4/1
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(VideoLessonVo lessonVo, SysUser sysUser) {
        VideoLessonGroup lessonGroup = lessonVo.getLessonGroup();
        List<VideoLessonGroupDetail> lessonList = lessonVo.getLessonList();

        //校验声部
        Long subjectId = Long.valueOf(lessonGroup.getLessonSubject());
        List<Subject> subjectList = teacherDao.querySubject(sysUser.getId());
        List<Long> longList = subjectList.stream().map(Subject::getId).collect(Collectors.toList());
        if (!longList.contains(subjectId)) {
            throw new BizException("该声部无法选择");
        }

        //添加组
        lessonGroup.setTeacherId(sysUser.getId());
        lessonGroup.setAuditVersion(YesOrNoEnum.NO);
        videoLessonGroupDao.insert(lessonGroup);

        for (VideoLessonGroupDetail detail : lessonList) {
            detail.setVideoLessonGroupId(lessonGroup.getId());
            detail.setTeacherId(sysUser.getId());
        }

        //添加课程
        videoLessonGroupDetailDao.insertVideoLesson(lessonList);

        //刷新统计
        VideoLessonGroupUpVo groupUpVo = new VideoLessonGroupUpVo();
        groupUpVo.setId(lessonGroup.getId());
        videoLessonGroupDao.updateGroup(groupUpVo);

        //记录video_lesson_auth_record
        VideoLessonAuthRecord record = new VideoLessonAuthRecord();
        record.setVideoGroupId(lessonGroup.getId());
        record.setAuditStatus(AuthStatusEnum.DOING.getCode());
        recordDao.insert(record);
    }

    /**
     * @Description: 学员详情-查询视频课列表
     * @Author: cy
     * @Date: 2022/4/2
     */
    @Override
    public IPage<VideoLessonStudentDetailVo> selectStudentPage(IPage<VideoLessonStudentDetailVo> page, VideoLessonSearch search) {
        return page.setRecords(baseMapper.selectStudentPage(page, search));
    }

    /**
     * @Description: 老师详情-查询视频课列表
     * @Author: cy
     * @Date: 2022/4/6
     */
    @Override
    public IPage<VideoLessonTeacherVo> selectTeacherPage(IPage<VideoLessonTeacherVo> page, VideoLessonSearch search) {
        return page.setRecords(baseMapper.selectTeacherPage(page, search));
    }

    /**
     * @Description: 老师详情-视频课详情-查询购买学员列表
     * @Author: cy
     * @Date: 2022/4/6
     */
    @Override
    public IPage<VideoLessonPurchaseVo> selectPurchaseStudent(IPage<VideoLessonPurchaseVo> page, VideoLessonSearch search) {
        return page.setRecords(baseMapper.selectPurchaseStudent(page, search));
    }

    /**
     * @Description: 根据组id查询视频课&视频课组
     * @Author: cy
     * @Date: 2022/4/7
     */
    @Override
    public VideoLessonStudentVo selectVideoLesson(Long groupId) {
        VideoLessonStudentVo lessonStudentVo = new VideoLessonStudentVo();

        VideoLessonGroupVo videoLessonGroupVo = detail(groupId);
        if (videoLessonGroupVo == null) return lessonStudentVo;

        lessonStudentVo.setLessonGroup(videoLessonGroupVo);
        VideoLessonSearch search = new VideoLessonSearch();
        search.setVideoLessonGroupId(groupId);
        lessonStudentVo.setDetailList(videoLessonGroupDetailDao.selectPage(null, search));
        return lessonStudentVo;
    }

    private VideoLessonGroupVo detail(Long groupId) {
        VideoLessonGroupSearch query = new VideoLessonGroupSearch();
        query.setGroupId(groupId);
        List<VideoLessonGroupVo> lessonGroup = videoLessonGroupDao.selectPage(null, query);
        if (CollectionUtils.isEmpty(lessonGroup)) {
            return null;
        }
        return lessonGroup.get(0);
    }

    /**
     * @Description: 修改视频课组&视频课
     * @Author: cy
     * @Date: 2022/4/7
     */
    @Override
    public void update(VideoLessonVo lessonVo, SysUser sysUser) {
        VideoLessonGroup lessonGroup = lessonVo.getLessonGroup();
        List<VideoLessonGroupDetail> lessonList = lessonVo.getLessonList();

        //查询原评审信息
        List<VideoLessonAuthRecord> recordList = recordDao.selectList(Wrappers.<VideoLessonAuthRecord>lambdaQuery().eq(VideoLessonAuthRecord::getVideoGroupId, lessonGroup.getId()));
        List<Long> recoreIds = recordList.stream().map(VideoLessonAuthRecord::getId).collect(Collectors.toList());

        //清除原有组&课
        videoLessonGroupDao.deleteById(lessonGroup.getId());
        videoLessonGroupDetailDao.deleteByGroupId(lessonGroup.getId());

        //添加组
        lessonGroup.setTeacherId(sysUser.getId());
        videoLessonGroupDao.insert(lessonGroup);

        for (VideoLessonGroupDetail detail : lessonList) {
            detail.setVideoLessonGroupId(lessonGroup.getId());
            detail.setTeacherId(sysUser.getId());
        }

        //添加课程
        videoLessonGroupDetailDao.insertVideoLesson(lessonList);

        //刷新统计
        VideoLessonGroupUpVo groupUpVo = new VideoLessonGroupUpVo();
        groupUpVo.setId(lessonGroup.getId());
        videoLessonGroupDao.updateGroup(groupUpVo);

        //更新历史记录的组id
        recordDao.updateIds(recoreIds, lessonGroup.getId());

        //重新提审
        VideoLessonAuthRecord record = new VideoLessonAuthRecord();
        record.setVideoGroupId(lessonGroup.getId());
        record.setAuditStatus(AuthStatusEnum.DOING.getCode());
        recordDao.insert(record);
    }

    /**
     * @Description: 查询视频课组
     * @Author: cy
     * @Date: 2022/4/11
     */
    @Override
    public IPage<LessonGroupVo> selectLessonGroup(IPage<LessonGroupVo> page, VideoLessonGroupSearch query) {
        query.setAuditStatus(AuthStatusEnum.PASS);
        return page.setRecords(baseMapper.selectLessonGroup(page, query));
    }

    /**
     * @Description: 查询所有视频课组
     * @Author: cy
     * @Date: 2022/4/20
     */
    @Override
    public IPage<VideoLessonAuthGroup> queryGroupList(IPage<VideoLessonAuthGroup> page, VideoGroupSearch query) {
        return page.setRecords(baseMapper.queryGroupList(page, query));
    }

    /**
     * @Description: 学生端-我的-我的课程-购买的视频课组
     * @Author: cy
     * @Date: 2022/4/20
     */
    @Override
    public IPage<LessonGroupVo> selectLessonGroupById(IPage<LessonGroupVo> page, VideoLessonGroupSearch query) {
        return page.setRecords(baseMapper.selectLessonGroup(page, query));
    }

    /**
     * @Description: 首页-视频课统计
     * @Author: cy
     * @Date: 2022/5/7
     */
    public CountVideoGroupVo countVideoGroup() {
        CountVideoGroupVo countVideoGroup = baseMapper.countVideoGroup();
        countVideoGroup.setVideoLessonList(baseMapper.selectVideoLesson());
        return countVideoGroup;
    }

    @Override
    public ShareProfitVo shareVideoCourseProfit(SysUser sysUser, Long videoGroupId) {

        VideoLessonStudentVo videoLessonStudentVo = selectVideoLesson(videoGroupId);

        String teacherVideoGroupShareProfitUrl= sysConfigService.findConfigValue(SysConfigConstant.TEACHER_VIDEO_GROUP_SHARE_PROFIT_URL);

        ShareProfitVo result = new ShareProfitVo();
        result.setType("VIDEO");
        result.setTeacherId(sysUser.getId());
        result.setVideoGroup(videoLessonStudentVo);
        result.setUrl(MessageFormatter.arrayFormat(teacherVideoGroupShareProfitUrl, videoGroupId, sysUser.getId()));
        result.setName(sysUser.getUsername());
        result.setAvatar(sysUser.getAvatar());
        return result;

    }
}