package com.xunwang.education.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunwang.commonutils.JwtUtils;
import com.xunwang.commonutils.RedisIdWorker;
import com.xunwang.education.entity.TeacherCourses;
import com.xunwang.education.entity.dto.MyPublishTeacherCoursesDto;
import com.xunwang.education.entity.dto.MyTeacherCourseDetailDto;
import com.xunwang.education.entity.dto.MyTeacherCoursesDto;
import com.xunwang.education.entity.vo.TeacherCoursesVo;
import com.xunwang.education.entity.vo.TeacherListQuery;
import com.xunwang.education.mapper.TeacherCoursesMapper;
import com.xunwang.education.service.TeacherCertificationsService;
import com.xunwang.education.service.TeacherCoursesService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 老师课程发布 服务实现类
 * </p>
 *
 * @author Long
 * @since 2022-12-04
 */
@Service
public class TeacherCoursesServiceImpl extends ServiceImpl<TeacherCoursesMapper, TeacherCourses> implements TeacherCoursesService {

    @Resource
    private TeacherCertificationsService certificationsService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加课程发布信息
     * @param teacherCoursesVo
     * @param uid
     */
    @Override
    public int addTeacherCourses(TeacherCoursesVo teacherCoursesVo, String uid) {
        TeacherCourses teacherCourses = new TeacherCourses();
        teacherCourses.setCourseId(String.valueOf(redisIdWorker.nextId("courseId")));
        BeanUtils.copyProperties(teacherCoursesVo, teacherCourses);
        // uid
        teacherCourses.setUid(uid);
        // 老师类型
        String teacherType = certificationsService.getTeacherType(uid);
        teacherCourses.setTeacherType(teacherType);
        teacherCourses.setSubject(teacherCoursesVo.getSubjectBig());

        return baseMapper.insert(teacherCourses);
    }

    /**
     * 查询个人已发布的课程
     * @param request
     * @return
     */
    @Override
    public HashMap<String, Object> showPersonCourse(HttpServletRequest request) {
        String uid = JwtUtils.getUIdByJwtToken(request);
        List<MyPublishTeacherCoursesDto> list = baseMapper.selectPublishCourseList(uid);
        int count = 0;
        for (MyPublishTeacherCoursesDto item : list) {
            if ("上架".equals(item.getDisplay())) {
                count++;
            }
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("publishCounts", count);
        hashMap.put("list", list);
        return hashMap;
    }

    /**
     * 删除已发布的课程
     * @param courseId
     * @return
     */
    @Override
    public int deletePersonCourse(int courseId) {
        int i = baseMapper.deleteById(courseId);
        return i;
    }

    /**
     * 分页查询
     * 查询全部老师根据条件
     * @param queryObj
     */
    @Override
    public List<MyTeacherCoursesDto> queryAllByConditions(TeacherListQuery queryObj) {
        queryObj.setPageNum((queryObj.getPageNum() - 1) * queryObj.getPageSize());
        String time = queryObj.getTime();
        if ("上午".equals(time)) {
            queryObj.setTime("A");
        } else if ("下午".equals(time)) {
            queryObj.setTime("P");
        } else if ("晚上".equals(time)) {
            queryObj.setTime("E");
        }

        List<MyTeacherCoursesDto> teacherLists = baseMapper.selectTeachers(queryObj);
        return teacherLists;
    }

    /**
     * 查询个人是否有正在审核的课程
     * @param uid
     * @return
     */
    @Override
    public boolean queryPersonVerifyCourse(String uid) {
        QueryWrapper<TeacherCourses> queryWrapper = new QueryWrapper();
        queryWrapper.eq("verify_status", "审核中");
        int count = count(queryWrapper);
        if (count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 查询个人未成交的课程数
     * @param uid
     * @return
     */
    @Override
    public int queryPersonNoDeal(String uid) {
        return count(new QueryWrapper<TeacherCourses>().eq("deal", "未成交"));
    }

    /**
     * 更新个人课程上下架
     * @param request
     */
    @Override
    public boolean updatePersonDisplay(HttpServletRequest request) {
        String display = request.getParameter("display");
        String courseId = request.getParameter("courseId");
        TeacherCourses teacherCourses = new TeacherCourses();
        teacherCourses.setDisplay(display);
        teacherCourses.setCourseId(courseId);
        if ("下架".equals(display)) {
            String key = "viewCount:course";
            Long rank = stringRedisTemplate.opsForZSet().rank(key, courseId);
            if (rank != null) {
                // 有访问量
                // 1.更新viewCount到数据库
                Double score = stringRedisTemplate.opsForZSet().score(key, courseId);
                if (score != null) {
                    teacherCourses.setViewedCount(score.intValue());
                }
                // 2.删除redis中存的viewCount数据
                stringRedisTemplate.opsForZSet().remove(key, courseId);
            }
        }
        return updateById(teacherCourses);
    }

    public int getTeacherViewCount(String uid) {
        return baseMapper.getTeacherViewCount(uid);
    }

    @Override
    public List<TeacherCourses> getTeacherCourseId(String uid) {
        return baseMapper.getTeacherCourseId(uid);
    }

    /**
     * 根据课程id查询课程是否上锁或下架
     * @param courseId
     * @return
     */
    @Override
    public String queryLockOrDisplay(String courseId) {
        TeacherCourses courses = getById(courseId);
        if (courses.getDisplay().equals("下架")) {
            return "该课程已下架";
        }
        if (courses.getLocked().equals("已锁")) {
            return "该课程已锁,请30分钟后查看";
        }
        String version = courses.getVersion();
        return "课程ok "+version;
    }

    /**
     * 锁定课程号
     * @param courseId
     * @param version
     * @return
     */
    @Override
    public boolean lockCourseId(String courseId, String version) {
        TeacherCourses courses = new TeacherCourses();
        courses.setLocked("已锁");
        courses.setVersion((Integer.parseInt(version) + 1) + "");
        return update(courses, new LambdaQueryWrapper<TeacherCourses>().eq(TeacherCourses::getCourseId, courseId).eq(TeacherCourses::getVersion, version));
    }

    /**
     * 查询个人课程详情信息
     * @param courseId
     * @return
     */
    @Override
    public MyTeacherCourseDetailDto getPersonCourseDetailById(String courseId) {
        return baseMapper.getPersonCourseDetailById(courseId);
    }


}
