package com.ruoyi.school.course.service;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.page.RespPage;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.core.api.APIBaseResponse;
import com.ruoyi.core.api.APIResponse;
import com.ruoyi.core.api.ApiResEnums;
import com.ruoyi.mall.domain.Product;
import com.ruoyi.mall.service.ProductService;
import com.ruoyi.school.course.domain.ScCourse;
import com.ruoyi.school.course.domain.ScCourseType;
import com.ruoyi.school.course.domain.req.course.ReqAddScCourse;
import com.ruoyi.school.course.domain.req.course.ReqChangeScCourse;
import com.ruoyi.school.course.domain.req.course.ReqSearchScCourse;
import com.ruoyi.school.course.domain.req.course.ReqSelect;
import com.ruoyi.school.course.domain.resp.course.RespScCourseDetail;
import com.ruoyi.school.course.domain.resp.course.RespSearchCourse;
import com.ruoyi.school.course.mapper.ScCourseMapper;
import com.ruoyi.school.member.domain.ScMemberCardCourses;
import com.ruoyi.school.member.service.ScMemberCardCourseService;
import com.ruoyi.system.service.impl.BusinessSysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author ：zhangbaoyu
 * @date ：Created in 2020-01-14 17:24
 */
@Service
@Transactional
public class BusinessScCourseService {

    @Autowired
    private IScCourseService scCourseService;
    @Autowired
    private ScCourseMapper courseMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private BusinessSysDeptService deptService;
    @Autowired
    private IScCourseTypeService courseTypeService;



    /**
     * 查询
     *
     * @param reqSearchScCourse
     * @return
     */
    public APIResponse searchList(ReqSearchScCourse reqSearchScCourse) {
        RespPage<RespSearchCourse> searchCourseRespPage = scCourseService.searchCourse(reqSearchScCourse);
        return APIResponse.toAPIResponse(searchCourseRespPage);
    }

    /**
     * 查询课程列表
     * 含有会员报读状态
     *
     * @param reqSearchScCourse
     * @return
     */
    public APIResponse selectCourseListWithStudentCourse(ReqSearchScCourse reqSearchScCourse) {
        RespPage respPage = new RespPage(reqSearchScCourse.getPageNum(), reqSearchScCourse.getPageSize());
        List<RespSearchCourse> courseList = courseMapper.selectCourseListWithStudentCourse(reqSearchScCourse, respPage, SecurityUtils.getLoginUser().getNowTenantId());
        respPage.setRows(courseList);
        return APIResponse.toAPIResponse(respPage);
    }

    /**
     * 前端select
     *
     * @return
     */
    public APIResponse select(ReqSelect reqSelect) {
        QueryWrapper qw = new QueryWrapper();
        qw.select("course_name", "course_id");

        if (StrUtil.isNotEmpty(reqSelect.getSearch())) {
            qw.like("course_name", reqSelect.getSearch());
        }
        qw.eq("tenant_id", SecurityUtils.getLoginUser().getNowTenantId());
        if (ObjectUtil.isNotEmpty(reqSelect.getDepartId())) {
            qw.last(" and (JSON_CONTAINS(depart_id, CAST("+reqSelect.getDepartId()+" AS JSON)) or depart_id is null)");
        }
//        qw.orderByDesc("create_time");
        List<ScCourse> list = scCourseService.list(qw);
        return APIResponse.toAPIResponse(list);
    }

    /**
     * 详情
     *
     * @param courseId
     * @return
     */
    public APIResponse detailById(Long courseId) {
        if (null == courseId) {
            return APIResponse.toAPIResponse(ApiResEnums.PARAM_FAIL);
        }

        // 课程详情
        ScCourse detailInfo = scCourseService.getById(courseId);


        RespScCourseDetail respScCourseDetail = new RespScCourseDetail();
        respScCourseDetail.setCourseId(detailInfo.getCourseId()+"");
        respScCourseDetail.setCourseName(detailInfo.getCourseName());
        respScCourseDetail.setCourseTypeId(detailInfo.getCourseTypeId());
        respScCourseDetail.setTeachingMode(detailInfo.getTeachingMode());
        respScCourseDetail.setCourseIntro(detailInfo.getCourseIntro());
        respScCourseDetail.setClaFee(detailInfo.getClaFee());
        respScCourseDetail.setCourseCampus(ObjectUtil.isEmpty(detailInfo.getDepartId())?"全部校区":"部分校区");
        respScCourseDetail.setPartCampus(detailInfo.getDepartId());
        respScCourseDetail.setRemark(detailInfo.getRemark());
        respScCourseDetail.setStar(detailInfo.getStar());

        if(null != detailInfo.getCourseTypeId()) {
            ScCourseType courseType = courseTypeService.getById(detailInfo.getCourseTypeId());
            Optional.ofNullable(courseType).ifPresent(item->{
                respScCourseDetail.setCourseTypeName(item.getCourseType());
            });
        }

        return APIResponse.toAPIResponse(respScCourseDetail);
    }

    /**
     * 添加课程
     *
     * @param reqAddScCourse
     * @return
     */
    public APIResponse addScCourse(ReqAddScCourse reqAddScCourse) {
        APIBaseResponse checkParam = reqAddScCourse.checkParam();
        if (!checkParam.isSuccess()) {
            throw new RuntimeException(checkParam.getRespMsg());
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // course 表保存
        ScCourse scCourse = new ScCourse();
        scCourse.setCourseName(reqAddScCourse.getCourseName());
        scCourse.setCourseTypeId(reqAddScCourse.getCourseTypeId());
        scCourse.setTeachingMode(reqAddScCourse.getTeachingMode());
        scCourse.setCourseIntro(reqAddScCourse.getCourseIntro());
        scCourse.setCreateUser(loginUser.getUserId());
        scCourse.setLastUpdateUser(loginUser.getUserId());
        scCourse.setTenantId(loginUser.getNowTenantId());
        scCourse.setClaFee(reqAddScCourse.getClaFee());
        scCourse.setDepartId(reqAddScCourse.getPartCampus());
        scCourse.setTuitionFee(reqAddScCourse.getTuitionFee());
        scCourse.setRemark(reqAddScCourse.getRemark());
        scCourse.setStar(reqAddScCourse.getStar());
        boolean addScCourse = scCourseService.save(scCourse);

        //默认班级


        return  APIResponse.toOkResponse();
    }

    /**
     * 更新
     *
     * @param reqChangeScCourse
     * @return
     */
    public APIResponse updateScCourse(ReqChangeScCourse reqChangeScCourse) {
        APIBaseResponse checkParam = reqChangeScCourse.checkParam();
        if (!checkParam.isSuccess()) {
            return APIResponse.toExceptionResponse(checkParam.getRespMsg());
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();

        // 更新课程信息
        ScCourse updateCourse = new ScCourse();
        updateCourse.setCourseId(reqChangeScCourse.getCourseId());
        updateCourse.setCourseName(reqChangeScCourse.getCourseName());
//        updateCourse.setCourseTypeId(reqChangeScCourse.getCourseTypeId());
        updateCourse.setTeachingMode(reqChangeScCourse.getTeachingMode());
        updateCourse.setCourseIntro(reqChangeScCourse.getCourseIntro());
        updateCourse.setClaFee(reqChangeScCourse.getClaFee());
        updateCourse.setTuitionFee(reqChangeScCourse.getTuitionFee());
        updateCourse.setLastUpdateUser(loginUser.getUserId());
        updateCourse.setLastUpdateTime(new Date());
        updateCourse.setTenantId(loginUser.getNowTenantId());
        updateCourse.setSale("1");
//        updateCourse.setDepartId(reqChangeScCourse.getPartCampus());
        updateCourse.setImportId(-1L);
        updateCourse.setRemark(reqChangeScCourse.getRemark());
        updateCourse.setStar(reqChangeScCourse.getStar());
        boolean updateScCourse = scCourseService.updateById(updateCourse);

        return APIResponse.toOkResponse();
    }

    @Autowired
    private ScMemberCardCourseService cardCourseService;
    /**
     * 删除
     *
     * @param courseIds
     * @return
     */
    public APIResponse deleteById(List<Long> courseIds) {
        if (null == courseIds || courseIds.isEmpty()) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }

        String arrayAsString = courseIds.stream()
                .map(Object::toString) // 将Long转换为String
                .collect(Collectors.joining(",")); // 使用逗号和空格连接字符串

        //有对应的单独定义的会员卡项
        int cardCourses= cardCourseService.count(new QueryWrapper<ScMemberCardCourses>()
                .last(" where  JSON_CONTAINS(courses, CAST("+arrayAsString+" AS JSON))"));
        if (cardCourses != 0) {
            return APIResponse.toExceptionResponse("已有会员卡项使用,无法删除");
        }

        int productCount= productService.count(new QueryWrapper<Product>().in("course_id",courseIds));
        if (productCount != 0) {
            return APIResponse.toExceptionResponse("已在商城上架,无法删除");
        }

        boolean deleteScCourse = scCourseService.removeByIds(courseIds);
        if (deleteScCourse) {
            return APIResponse.toOkResponse();
        } else {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
    }

    /**
     * 变更是否开售
     *
     * @param scCourse
     * @return
     */
    public APIResponse changeCourseSale(ScCourse scCourse) {
        if (null == scCourse.getCourseId()) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
        if (StrUtil.isEmpty(scCourse.getSale())) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
        UpdateWrapper uw = new UpdateWrapper();
        uw.set("sale", scCourse.getSale());
        uw.eq("course_id", scCourse.getCourseId());
        boolean updateScCourse = scCourseService.update(uw);
        if (updateScCourse) {
            return APIResponse.toOkResponse();
        } else {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
    }

}
