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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.course.dao.CourseClassificationDao;
import com.sqx.modules.course.dao.CourseCollectDao;
import com.sqx.modules.course.entity.Course;
import com.sqx.modules.course.entity.CourseCollect;
import com.sqx.modules.course.entity.CourseDetails;
import com.sqx.modules.course.service.CourseCollectService;
import com.sqx.modules.course.service.CourseDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
public class CourseCollectServiceImpl extends ServiceImpl<CourseCollectDao, CourseCollect> implements CourseCollectService {

    @Autowired
    private CourseClassificationDao courseClassificationDao;
    @Autowired
    private CourseDetailsService courseDetailsService;

    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);

    @Override
    @CacheEvict(value = "app:courseCollect", key = "#courseCollect.userId")
    public Result insertCourseCollect(CourseCollect courseCollect) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            if (courseCollect.getClassify() == 3) {
                QueryWrapper<CourseCollect> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("user_id", courseCollect.getUserId()).eq("classify", 3).eq("course_id", courseCollect.getCourseId());
                queryWrapper.orderByDesc("create_time");
                queryWrapper.last("limit 1");
                CourseCollect collect = baseMapper.selectOne(queryWrapper);
                if (collect != null) {
                    collect.setUpdateTime(DateUtils.format(new Date()));
                    collect.setCourseCollectId(courseCollect.getCourseCollectId());
                    baseMapper.updateById(collect);
                    return Result.success("操作成功！");
                }

                collect = new CourseCollect()
                        .setUserId(courseCollect.getUserId())
                        .setCourseId(courseCollect.getCourseId())
                        .setCourseDetailsId(courseCollect.getCourseDetailsId())
                        .setClassify(3)
                        .setCreateTime(DateUtils.format(new Date()))
                        .setUpdateTime(DateUtils.format(new Date()));
                baseMapper.insert(collect);
                return Result.success("操作成功！");
            }
            CourseCollect courseCollect1 = selectCourseCollectUserIdAnd(courseCollect.getUserId(), courseCollect.getCourseId(),courseCollect.getClassify(),courseCollect.getCourseDetailsId());
            if (courseCollect.getType() == 1) {
                if(courseCollect1==null){
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    courseCollect.setCreateTime(df.format(new Date()));
                    courseCollect.setUpdateTime(courseCollect.getCreateTime());
                    baseMapper.insert(courseCollect);
                    if(courseCollect.getClassify()==2){
                        CourseDetails courseDetails = courseDetailsService.getById(courseCollect.getCourseDetailsId());
                        courseDetails.setGoodNum(courseDetails.getGoodNum()+1);
                        courseDetailsService.updateById(courseDetails);
                    }
                }else{
                    courseCollect1.setUpdateTime(DateUtils.format(new Date()));
                    baseMapper.updateById(courseCollect1);
                }
            } else {
                if(courseCollect1!=null){
                    baseMapper.deleteById(courseCollect1.getCourseCollectId());
                    if(courseCollect.getClassify()==2){
                        CourseDetails courseDetails = courseDetailsService.getById(courseCollect.getCourseDetailsId());
                        courseDetails.setGoodNum(courseDetails.getGoodNum()-1);
                        courseDetailsService.updateById(courseDetails);
                    }
                }
            }
            return Result.success("操作成功！");
        }catch (Exception e){
            e.printStackTrace();
            log.error("收藏短剧出错了！"+e.getMessage());
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙,请稍后再试！");
    }

    @Override
    @CachePut(value = "app:courseCollect", key = "#userId")
    public Result selectByUserId(Integer page, Integer limit, Long userId,Integer classify) {
        PageHelper.startPage(page,limit);
        List<Course> courseList = baseMapper.selectCourseByCollect( userId,classify);
        PageInfo<Course> pageInfo = new PageInfo<>(courseList);
        List<Course> courses = pageInfo.getList();
        if (courses != null && courses.size() > 0) {
            for (Course course : courses) {
                course.setCourseClassification(courseClassificationDao.selectById(course.getClassifyId()));
            }
        }
        return Result.success().put("data", PageUtils.page(pageInfo, true));
    }


    @Override
    public CourseCollect selectCourseCollectUserIdAnd(Long userId,Long courseId,Integer classify,Long courseDetailsId){
        return baseMapper.selectOne(new QueryWrapper<CourseCollect>().eq(courseDetailsId!=null,"course_details_id",courseDetailsId).eq("user_id",userId).eq("classify",classify).eq("course_id",courseId));
    }


}
