package org.dromara.zjk.learning_world.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zjk.domain.ExpertBaseInfo;
import org.dromara.zjk.enums.PublishStatusEnum;
import org.dromara.zjk.learning_world.domain.bo.ZjkLearningCourseBo;
import org.dromara.zjk.learning_world.domain.entity.ZjkLearningCourse;
import org.dromara.zjk.learning_world.domain.excel.ZjkLearningCourseExcel;
import org.dromara.zjk.learning_world.domain.vo.ZjkLearningCourseVo;
import org.dromara.zjk.learning_world.enums.course.CourseTypeEnum;
import org.dromara.zjk.learning_world.enums.course.GiveCourseTypeEnum;
import org.dromara.zjk.learning_world.mapper.ZjkLearningCourseMapper;
import org.dromara.zjk.learning_world.service.IZjkLearningCourseService;
import org.dromara.zjk.mapper.ZjkExpertMapper;
import org.dromara.zjk.utils.EnumUtil;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 课程Service业务层处理
 *
 * @author ygh
 * @date 2024-11-08
 */
@RequiredArgsConstructor
@Service
public class ZjkLearningCourseServiceImpl implements IZjkLearningCourseService {

    private final ZjkLearningCourseMapper baseMapper;

    private final ZjkExpertMapper expertMapper;

    /**
     * 查询课程
     *
     * @param id 主键
     * @return 课程
     */
    @Override
    public ZjkLearningCourseVo queryById(Long id) {
        return baseMapper.queryById(id);
    }

    /**
     * 分页查询课程列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 课程分页列表
     */
    @Override
    public TableDataInfo<ZjkLearningCourseVo> queryPageList(ZjkLearningCourseBo bo, PageQuery pageQuery) {
        ExpertBaseInfo expertBaseInfo = expertMapper.getExpertBaseInfo(LoginHelper.getUserId());
        String performWorkId = null;
        if (null != expertBaseInfo && expertBaseInfo.getPerformWorkId() != null) {
            performWorkId = expertBaseInfo.getPerformWorkId();
            bo.setPerformWorkIdList(List.of(expertBaseInfo.getPerformWorkId().split(",")));

        }
        LambdaQueryWrapper<ZjkLearningCourse> lqw = buildQueryWrapper(bo);
        Page<ZjkLearningCourseVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<ZjkLearningCourseVo> records = result.getRecords();
        if (CollectionUtil.isEmpty(records)) {
            return TableDataInfo.build(result);
        }
        for (ZjkLearningCourseVo record : records) {
            if (StringUtils.isNotBlank(performWorkId)) {
                String coursePerformWorkId = record.getPerformWorkId();
                if (StringUtils.isNotBlank(coursePerformWorkId)) {
                    record.setRecommended(performWorkId.contains(coursePerformWorkId));

                }
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的课程列表
     *
     * @param bo 查询条件
     * @return 课程列表
     */
    @Override
    public List<ZjkLearningCourseVo> queryList(ZjkLearningCourseBo bo) {
        LambdaQueryWrapper<ZjkLearningCourse> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ZjkLearningCourse> buildQueryWrapper(ZjkLearningCourseBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ZjkLearningCourse> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getCourseName()), ZjkLearningCourse::getCourseName, bo.getCourseName());
        lqw.eq(StringUtils.isNotBlank(bo.getCourseClassify()), ZjkLearningCourse::getCourseClassify, bo.getCourseClassify());
        lqw.eq(StringUtils.isNotBlank(bo.getTeachingType()), ZjkLearningCourse::getTeachingType, bo.getTeachingType());
        lqw.eq(StringUtils.isNotBlank(bo.getCourseBrief()), ZjkLearningCourse::getCourseBrief, bo.getCourseBrief());
        lqw.eq(StringUtils.isNotBlank(bo.getCoursePic()), ZjkLearningCourse::getCoursePic, bo.getCoursePic());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), ZjkLearningCourse::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getCourseAttachment()), ZjkLearningCourse::getCourseAttachment, bo.getCourseAttachment());
        lqw.in(bo.getRecommended() != null && bo.getRecommended() && !CollectionUtil.isEmpty(bo.getPerformWorkIdList()), ZjkLearningCourse::getPerformWorkId, bo.getPerformWorkIdList());
        return lqw;
    }

    /**
     * 新增课程
     *
     * @param bo 课程
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(ZjkLearningCourseBo bo) {
        ZjkLearningCourse add = MapstructUtils.convert(bo, ZjkLearningCourse.class);
        add.setUserId(LoginHelper.getUserId());
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改课程
     *
     * @param bo 课程
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(ZjkLearningCourseBo bo) {
        ZjkLearningCourse update = MapstructUtils.convert(bo, ZjkLearningCourse.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZjkLearningCourse entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除课程信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<ZjkLearningCourseExcel> exportList(ZjkLearningCourseBo bo) {
        List<ZjkLearningCourseVo> zjkLearningCourseVos = queryList(bo);
        if (CollectionUtil.isEmpty(zjkLearningCourseVos)) {
            return List.of();
        }
        List<ZjkLearningCourseExcel> zjkLearningCourseExcels = BeanUtil.copyToList(zjkLearningCourseVos, ZjkLearningCourseExcel.class);
        for (ZjkLearningCourseExcel learningCourseExcel : zjkLearningCourseExcels) {
            String teachingType = learningCourseExcel.getTeachingType();
            if (!StringUtils.isEmpty(teachingType)) {
                String nameByCode = EnumUtil.getNameByCode(GiveCourseTypeEnum.class, teachingType);
                learningCourseExcel.setTeachingTypeName(nameByCode);
            }

            String courseClassify = learningCourseExcel.getCourseClassify();
            if (!StringUtils.isEmpty(courseClassify)) {
                String nameByCode = EnumUtil.getNameByCode(CourseTypeEnum.class, courseClassify);
                learningCourseExcel.setCourseClassifyName(nameByCode);
            }
            String status = learningCourseExcel.getStatus();
            if (!StringUtils.isEmpty(status)) {
                String nameByCode = EnumUtil.getNameByCode(PublishStatusEnum.class, status);
                learningCourseExcel.setStatusName(nameByCode);

            }
        }

        return zjkLearningCourseExcels;
    }

    @Override
    public int updateStatus(ZjkLearningCourseBo bo) {
        Long id = bo.getId();
        ZjkLearningCourse zjkLearningCourse = baseMapper.selectById(id);
        if (zjkLearningCourse == null) {
            throw new ServiceException("无效id");
        }
        zjkLearningCourse.setStatus(bo.getStatus());
        zjkLearningCourse.setTakedownTime(new Date());
        return baseMapper.updateById(zjkLearningCourse);
    }
}
