package cn.iocoder.yudao.module.course.controller.admin;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.base.entity.DriveSchoolCourseDeduct;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseDeductService;
import cn.iocoder.yudao.module.base.service.DlDriveSchoolCourseService;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolCourseVO;
import cn.iocoder.yudao.module.course.entity.Process;
import cn.iocoder.yudao.module.course.service.ProcessService;
import cn.iocoder.yudao.module.course.service.SchoolCourseOrderService;
import cn.iocoder.yudao.module.course.vo.*;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolDeduct;
import cn.iocoder.yudao.module.jx.service.IDriveSchoolDeductService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 学员课程进度")
@RestController
@RequestMapping("/process")
@Validated
public class ProcessController {

    @Resource
    private ProcessService processService;

    @Autowired
    private DlDriveSchoolCourseDeductService driveSchoolCourseDeductService;

    @Autowired
    private IDriveSchoolDeductService driveSchoolDeductService;

    @Resource
    private SchoolCourseOrderService schoolCourseOrderService;




    /**
     * 学员课程进度分页查询
     *
     * @param pageReqVO {@link ProcessVO}
     * @param pageNo    分页参数
     * @param pageSize  分页参数
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<com.baomidou.mybatisplus.core.metadata.IPage < ?>>
     * @author PQZ
     * @date 15:33 2025/2/17
     **/
    @GetMapping("/page")
    @Operation(summary = "学员课程进度分页")
    public CommonResult<IPage<?>> getDlDriveSchoolCoachPage(ProcessVO pageReqVO,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<ProcessVO> page = new Page<>(pageNo, pageSize);
        return success(processService.pageProcess(page, pageReqVO));
    }

    /**
     * 教练查自己带教的课程和科目
     *
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     * @author vinjor-M
     * @date 11:05 2025/1/15
     **/
    @GetMapping("/getMyCourseAndSubject")
    @Operation(summary = "教练查自己带教的课程和科目")
    public CommonResult<?> getMyCourseAndSubject() {
        return success(processService.getMyCourseAndSubject());
    }

    /**
     * 教练查自己带教的课程和科目在训练中的学生
     *
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     * @author vinjor-M
     * @date 11:05 2025/1/15
     **/
    @GetMapping("/getMyCourseStudentPage")
    @Operation(summary = "教练查自己带教的课程和科目在训练中的学生")
    public CommonResult<IPage<?>> getMyCourseStudentPage(Process process,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<Process> page = new Page<>(pageNo, pageSize);
        return success(processService.getMyCourseStudentPage(process, page));
    }

    /**
     * 通过id查询学员进度课程
     *
     * @param id 学员课程进度id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<cn.iocoder.yudao.module.base.vo.DlDriveSchoolCoachRespVO>
     * @author PQZ
     * @date 11:28 2025/2/18
     **/
    @GetMapping("/get")
    @Operation(summary = "通过id 查询学员进度课程")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<ProcessVO> getDlDriveSchoolCoach(@RequestParam("id") String id) {
        ProcessVO processVO = BeanUtils.toBean(processService.getById(id), ProcessVO.class);
        Long coachId = processVO.getCoachId();
        Integer subject = processVO.getSubject();
        Long userId = processVO.getUserId();
        String courseId = processVO.getCourseId();
        BigDecimal deduct = BigDecimal.ZERO;
        DriveSchoolCourseDeduct courseDeduct = driveSchoolCourseDeductService.getDeductByCourseIdAndSubject(courseId, subject);
        if (courseDeduct != null) {
            if (courseDeduct.getDeduct() != null) {
                deduct = courseDeduct.getDeduct();
            }
            else if (courseDeduct.getCourseSubject() != null) {
                DriveSchoolDeduct schoolDeduct = driveSchoolDeductService.queryBySubject(courseDeduct.getCourseSubject());
                if (schoolDeduct != null && schoolDeduct.getDeduct() != null) {
                    deduct = schoolDeduct.getDeduct();
                }
            }
        }
        List<SchoolCourseOrderVO> courseByInfo = schoolCourseOrderService.getCourseByInfo(userId, courseId);
        BigDecimal studentPay = BigDecimal.ZERO;
        BigDecimal studentRemainingPay = BigDecimal.ZERO;
        if (!courseByInfo.isEmpty()) {
            studentPay = courseByInfo.get(0).getReserveMoney() != null ?
                    courseByInfo.get(0).getReserveMoney() : BigDecimal.ZERO;
            studentRemainingPay = courseByInfo.get(0).getRestMoney() != null ?
                    courseByInfo.get(0).getRestMoney() : BigDecimal.ZERO;
        }
        processVO.setCoachCommission(deduct);
        processVO.setStudentPay(studentPay);
        processVO.setStudentRemainingPay(studentRemainingPay);

        return success(processVO);
    }

    @GetMapping("/getProcessAndBatch")
    @Operation(summary = "通过id 查询学员进度课程及批次信息")
    public CommonResult<ProcessAndExamBatchVO> getProcessAndBatch(@RequestParam("id") String id) {
        ProcessAndExamBatchVO processAndBatch = processService.getProcessAndBatch(id);
        return success(processAndBatch);
    }

    /**
     * 财务审核
     *
     * @param process {@link Process}
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 15:23 2025/2/18
     **/
    @PostMapping("/check")
    @Operation(summary = "财务审核")
    public CommonResult<Boolean> saveSchoolCoach(@Valid @RequestBody Process process) {
        processService.checkProcess(process);
        return success(true);
    }

    /**
     * 保存学员课程进度
     *
     * @param request {@link ProcessAddVO}
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     */
    @PostMapping("/saveProcess")
    @Operation(summary = "保存学员课程进度")
    public CommonResult<Boolean> saveProcess(@RequestBody ProcessAddVO request) {
        // 订单id和科目集合不能为空
        if (request.getOrderId() == null || request.getProcessList() == null) {
            throw new RuntimeException("订单和科目不能为空");
        }
        processService.saveProcess(request);
        return success(true);
    }

    /**
     * 通过学员id和课程id查询学员课程进度
     *
     * @param userId   学员id
     * @param courseId 课程id
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.util.List < cn.iocoder.yudao.module.course.vo.ProcessVO>>
     */
    @GetMapping("/getAllByUserIdAndCourseId")
    public CommonResult<?> getAllByUserIdAndCourseId(Long userId, String courseId) {
        return success(processService.getAllByUserIdAndCourseId(userId, courseId));
    }

    /**
     * 教练自招学员，自动分配教练
     */
    @PostMapping("/autoAssignCoach")
    public CommonResult<Boolean> autoAssignCoach(@RequestBody ProcessNewVO requset) {
        processService.autoAssignCoach(requset);
        return success(true);
    }

}
