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

import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.base.entity.DlDriveSchoolStudent;
import cn.iocoder.yudao.module.base.mapper.DlDriveSchoolStudentMapper;
import cn.iocoder.yudao.module.base.vo.DlDriveSchoolStudentVO;
import cn.iocoder.yudao.module.course.service.ProcessService;
import cn.iocoder.yudao.module.course.vo.CommissionExportVO;
import cn.iocoder.yudao.module.jx.domain.DriveSchoolCar;
import cn.iocoder.yudao.module.jx.mapper.DriveSchoolCarMapper;
import cn.iocoder.yudao.module.jx.vo.DriveSchoolCarVO;
import cn.iocoder.yudao.module.train.entity.Train;
import cn.iocoder.yudao.module.train.service.TrainService;
import cn.iocoder.yudao.module.train.vo.*;
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.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

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

@Tag(name = "管理后台 - 练车记录")
@RestController
@RequestMapping("/train")
@Validated
public class TrainController {

    @Resource
    private TrainService trainService;
    @Resource
    private ProcessService processService;
    @Resource
    private DlDriveSchoolStudentMapper studentMapper;
    @Resource
    private DriveSchoolCarMapper carMapper;


    @GetMapping("/page")
    @Operation(summary = "获得练车记录分页")
    public CommonResult<IPage<?>> getPage(TrainVO pageReqVO,
                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<TrainVO> page = new Page<>(pageNo,pageSize);
        if("my".equals(pageReqVO.getSelectType())){
            //查自己的
            Long userId = SecurityFrameworkUtils.getLoginUserId();
            pageReqVO.setCoachId(userId);
        }
        return success(trainService.queryListPage(pageReqVO,page));
    }


    @PostMapping("/create")
    @Operation(summary = "到场打卡")
    public CommonResult<?> createObj( @RequestBody TrainVO trainVO) {
        trainService.createObj(trainVO);
        return success(true);
    }

    @PutMapping("/update")
    @Operation(summary = "离场打卡")
    public CommonResult<?> updateObj( @RequestBody TrainVO trainVO) {
        trainService.updateObj(trainVO);
        return success(true);
    }


    @GetMapping("/get")
    @Operation(summary = "查看练车记录详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    public CommonResult<?> getById(@RequestParam("id") String id) {
        return success(trainService.getById(id));
    }


    /**
     * 首页数据统计查询接口 --
     * @author vinjor-M
     * @date 14:12 2025/2/14
     * @param type 查询类型（car-训练车辆|student-训练学生）
     * @param timeType 时间查询类型（all-全部|day-当日|month-当月|more-自定义）
     * @param coachId 教练id
     * @param startTime 查询时间范围--开始
     * @param endTime 查询时间范围--结束
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<?>
     **/
    @GetMapping("/indexGetTrainList")
    @Operation(summary = "首页数据统计查询接口")
    public CommonResult<IPage<?>> indexGetTrainList(@RequestParam(value = "type") String type,
                                           @RequestParam(value = "timeType") String timeType,
                                           @RequestParam(value = "coachId",required = false) Long coachId,
                                           @RequestParam(value = "sourceCoachId",required = false) Long sourceCoachId,
                                           @RequestParam(value = "searchValue",required = false) String searchValue,
                                           @RequestParam(value = "courseType",required = false) String courseType,
                                           @RequestParam(value = "subject",required = false) Integer subject,
                                           @RequestParam(value = "sort",required = false) String sort,
                                           @RequestParam(value = "startTime",required = false) String startTime,
                                           @RequestParam(value = "endTime",required = false) String endTime,
                                           @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        //默认查全部数据
        String startTimeStr = "";
        String endTimeStr = "";
        if("more".equals(timeType)){
            if(StringUtils.isNotEmpty(startTime)){
                startTimeStr = startTime+" 00:00:01";
            }
            if(StringUtils.isNotEmpty(endTime)) {
                endTimeStr = endTime + " 23:59:59";
            }
        }else if("month".equals(timeType)){
            //当月
            startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 00:00:01";
            endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 23:59:59";
        }else if("day".equals(timeType)){
            //当天
            startTimeStr = DateUtil.formatDate(DateUtil.date())+" 00:00:01";
            endTimeStr = DateUtil.formatDate(DateUtil.date())+" 23:59:59";
        }
        if("student".equals(type)){
            Page<DlDriveSchoolStudent> page = new Page<>(pageNo,pageSize);
            IPage<TrainVO> studentPage = studentMapper.selectTrainStudentNew(coachId,startTimeStr,endTimeStr,searchValue,courseType,subject,sort,page);
            return success(studentPage);
        }else{
            //训练车辆
            Page<DriveSchoolCarVO> page = new Page<>(pageNo,pageSize);
            IPage<DriveSchoolCarVO> driveSchoolCarIPage = carMapper.selectTrainCar(coachId, subject, startTimeStr, endTimeStr, searchValue, courseType, page);
            for (DriveSchoolCarVO record : driveSchoolCarIPage.getRecords()) {
                List<Train> trainList = carMapper.selectTrainStudentList(Long.parseLong(record.getUserId()), subject, startTimeStr, endTimeStr, searchValue, courseType);
                record.setStudentList(trainList);
            }

            return success(driveSchoolCarIPage);
        }
    }

    @GetMapping("/indexGetTrainStudentCount")
    @Operation(summary = "首页数据统计查询接口")
    public CommonResult<?> indexGetTrainStudentCount(@RequestParam(value = "type") String type,
                                                    @RequestParam(value = "timeType") String timeType,
                                                    @RequestParam(value = "coachId",required = false) Long coachId,
                                                    @RequestParam(value = "sourceCoachId",required = false) Long sourceCoachId,
                                                    @RequestParam(value = "searchValue",required = false) String searchValue,
                                                    @RequestParam(value = "courseType",required = false) String courseType,
                                                    @RequestParam(value = "subject",required = false) Integer subject,
                                                    @RequestParam(value = "sort",required = false) String sort,
                                                    @RequestParam(value = "startTime",required = false) String startTime,
                                                    @RequestParam(value = "endTime",required = false) String endTime) {
        //默认查全部数据
        String startTimeStr = "";
        String endTimeStr = "";
        if("more".equals(timeType)){
            if(StringUtils.isNotEmpty(startTime)){
                startTimeStr = startTime+" 00:00:01";
            }
            if(StringUtils.isNotEmpty(endTime)) {
                endTimeStr = endTime + " 23:59:59";
            }
        }else if("month".equals(timeType)){
            //当月
            startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 00:00:01";
            endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 23:59:59";
        }else if("day".equals(timeType)){
            //当天
            startTimeStr = DateUtil.formatDate(DateUtil.date())+" 00:00:01";
            endTimeStr = DateUtil.formatDate(DateUtil.date())+" 23:59:59";
        }
        if("student".equals(type)){
            TrainStudentCountVO trainStudentCountVO = studentMapper.selectTrainStudentCount(coachId, startTimeStr, endTimeStr, searchValue, courseType, subject, sort);
            return success(trainStudentCountVO);
        }else{
            return success(null);
        }
    }



    @GetMapping("/indexGetTrainStudentNum")
    @Operation(summary = "首页数据统计查询接口")
    public CommonResult<?> indexGetTrainStudentNum(@RequestParam(value = "type") String type,
                                                    @RequestParam(value = "timeType") String timeType,
                                                    @RequestParam(value = "coachId",required = false) Long coachId,
                                                    @RequestParam(value = "sourceCoachId",required = false) Long sourceCoachId,
                                                    @RequestParam(value = "searchValue",required = false) String searchValue,
                                                    @RequestParam(value = "courseType",required = false) String courseType,
                                                    @RequestParam(value = "subject",required = false) Integer subject,
                                                    @RequestParam(value = "sort",required = false) String sort,
                                                    @RequestParam(value = "startTime",required = false) String startTime,
                                                    @RequestParam(value = "endTime",required = false) String endTime,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        //默认查全部数据
        String startTimeStr = "";
        String endTimeStr = "";
        if("more".equals(timeType)){
            if(StringUtils.isNotEmpty(startTime)){
                startTimeStr = startTime+" 00:00:01";
            }
            if(StringUtils.isNotEmpty(endTime)) {
                endTimeStr = endTime + " 23:59:59";
            }
        }else if("month".equals(timeType)){
            //当月
            startTimeStr = DateUtil.format(DateUtil.beginOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 00:00:01";
            endTimeStr = DateUtil.format(DateUtil.endOfMonth(DateUtil.date()),"yyyy-MM-dd")+" 23:59:59";
        }else if("day".equals(timeType)){
            //当天
            startTimeStr = DateUtil.formatDate(DateUtil.date())+" 00:00:01";
            endTimeStr = DateUtil.formatDate(DateUtil.date())+" 23:59:59";
        }

            //人数
            return success(carMapper.selectTrainStudent(coachId,subject, startTimeStr,endTimeStr,searchValue,courseType));

    }

    /**
     * 定时任务提醒教练未进行离场打卡学员信息
     */
    @TenantIgnore
    @Scheduled(cron = "0 30 18 * * ?")
    public void noClockInRemind() {
        trainService.noClockInRemind();
    }

    @GetMapping("noClockInRemindByUserId")
    public CommonResult<NoClockInRemindVO>noClockInRemindByUserId(String carNo){
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        return success(trainService.noClockInRemindByUserId(userId, carNo));
    }

    /**
     * 根据教练打卡id，获取对应学员列表信息
     */
    @GetMapping("getTrainStudentList")
    public CommonResult<List<Train>> getTrainStudentList(@RequestParam(value = "coachClockId") String coachClockId){
        return success(trainService.getTrainStudentList(coachClockId));
    }

    /**
     * 根据教练打卡id，获取对应异常学员列表信息
     */
    @GetMapping("getTrainErrorStudentList")
    public CommonResult<List<Train>> getTrainErrorStudentList(@RequestParam(value = "coachClockId") String coachClockId){
        return success(trainService.getTrainErrorStudentList(coachClockId));
    }

    /**
     * 获取学员导出数据列表
     */
    @GetMapping("getExportList")
    public CommonResult<IPage<TrainExportVO>> getExportList(TrainExportVO exportVO,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        Page<TrainExportVO> page = new Page<>(pageNo, pageSize);
        return success(trainService.getExportList(exportVO,page));
    }

    /**
     * 导出数据（支持三种模式）
     * @param exportVO 包含导出类型（exportType）、分页参数等
     */
    @GetMapping("/export")
    public void exportCommission(TrainExportVO exportVO, HttpServletResponse response) throws IOException {
        // 校验导出类型
        if (exportVO.getExportType() == null || !Arrays.asList("current", "all", "range").contains(exportVO.getExportType())) {
            throw new IllegalArgumentException("无效的导出类型: " + exportVO.getExportType());
        }

        // 根据不同类型查询数据
        List<TrainExportVO> exportData;
        String fileName = "学员训练记录";

        switch (exportVO.getExportType()) {
            case "current":
                exportData = trainService.getTrainList(exportVO);
                fileName += "_第" + exportVO.getPageNo() + "页";
                break;
            case "all":
                exportData = trainService.getAllTrainList(exportVO);
                fileName += "_全部数据";
                break;
            case "range":
                exportData = trainService.getTrainListByRange(exportVO);
                fileName += "_" + exportVO.getStartPage() + "-" + exportVO.getEndPage() + "页";
                break;
            default:
                throw new IllegalArgumentException("无效的导出类型: " + exportVO.getExportType());
        }

        // 导出Excel
        ExcelUtils.write(response, fileName + ".xlsx", "学员训练记录", TrainExportVO.class, exportData);
    }

    /**
     * 当日正在训练学员统计
     */
    @GetMapping("getTodayTrainSituation")
    public CommonResult<CloakAndTrainCountVO> getTodayTrainSituation(TodayTrainVO train){
        return success(trainService.getTodayTrainSituation(train));
    }

    /**
     * 获取当前正在训练的学员列表
     */
    @GetMapping("getTodayStudentTrainSituation")
    public CommonResult<IPage<TodayTrainVO>> getTodayStudentTrainSituation(TodayTrainVO train,
                                                                    @RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
                                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize){
        Page<TodayTrainVO> page = new Page<>(pageNum, pageSize);
        return success(trainService.getTodayStudentTrainSituation(train,page));
    }
}
