package com.ym.mec.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ym.mec.biz.dal.dao.MusicGroupSchoolTermCourseDetailDao;
import com.ym.mec.biz.dal.entity.MusicGroupSchoolTermCourseDetail;
import com.ym.mec.biz.dal.entity.TenantInfo;
import com.ym.mec.biz.dal.enums.IndexDataType;
import com.ym.mec.biz.event.source.CourseEventSource;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.redis.service.RedisCache;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.im.ImFeignService;
import com.ym.mec.util.date.DateUtil;
import com.yonge.log.service.HistoryMessageService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RequestMapping("task")
@RestController
public class TaskController extends BaseController {

	@Autowired
	private MusicGroupStudentFeeService musicGroupStudentFeeService;
	@Autowired
	private VipGroupService vipGroupService;
	@Autowired
	private CourseScheduleService courseScheduleService;
	@Autowired
	private TeacherAttendanceService teacherAttendanceService;
	@Autowired
	private CourseScheduleTeacherSalaryService courseScheduleTeacherSalaryService;
	@Autowired
	private StudentCourseHomeworkService studentCourseHomeworkService;
	@Autowired
	private CourseHomeworkService courseHomeworkService;
	@Autowired
	private StudentPaymentOrderService studentPaymentOrderService;
	@Autowired
	private TeacherCourseStatisticsService teacherCourseStatisticsService;
	@Autowired
	private PracticeGroupService practiceGroupService;
	@Autowired
	private CourseScheduleEvaluateService courseScheduleEvaluateService;
	@Autowired
	private CourseReviewService courseReviewService;
	@Autowired
	private CoursesGroupService coursesGroupService;
	@Autowired
	private ExtracurricularExercisesService extracurricularExercisesService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private MusicGroupPaymentCalenderService musicGroupPaymentCalenderService;
	@Autowired
	private MusicGroupPaymentCalenderDetailService musicGroupPaymentCalenderDetailService;
	@Autowired
	private StudentServeService studentServeService;
	@Autowired
	private OperatingReportService operatingReportService;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private StudentGoodsSellService studentGoodsSellService;
	@Autowired
	private SysMessageService sysMessageService;
	@Autowired
	private CourseEventSource courseEventSource;
	@Autowired
	private CourseScheduleStatisticsService courseScheduleStatisticsService;
	@Autowired
	private RedisCache<String, Object> redisCache;
	@Autowired
	private IndexBaseMonthDataService indexBaseMonthDataService;
	@Autowired
	private InspectionItemPlanService inspectionItemPlanService;
	@Autowired
	private StudentInstrumentService studentInstrumentService;
	@Autowired
	private HistoryMessageService historyMessageService;
	@Autowired
	private ImFeignService imFeignService;
	@Autowired
	private IndexErrDataRecordService indexErrDataRecordService;
	@Autowired
	private ClassGroupService classGroupService;
	@Autowired
	private MusicGroupSchoolTermCourseDetailDao musicGroupSchoolTermCourseDetailDao;
	@Autowired
	private MusicGroupSchoolTermCourseDetailService musicGroupSchoolTermCourseDetailService;
	@Autowired
	private SysMusicCompareRecordService sysMusicCompareRecordService;
	@Autowired
	private TenantInfoService tenantInfoService;
    @Autowired
    private TenantOrderRecordService tenantOrderRecordService;
	@Autowired
	private AppRedemptionCodeService appRedemptionCodeService;
	@Autowired
	private TeacherContractsService teacherContractsService;
    @Autowired
    private ImLiveBroadcastRoomService imLiveBroadcastRoomService;
	@Autowired
	private StudentStatisticsService studentStatisticsService;
	@Autowired
	private ImSendGroupMessageService imSendGroupMessageService;
    @Autowired
    private TempLittleArtistTrainingCampService tempLittleArtistTrainingCampService;
    @Autowired
    private OperatingReportNewService operatingReportNewService;

	//每月经营报表
	@GetMapping(value = "/operatingReportMonth")
	public void operatingReportMonth(){
		Date month = DateUtil.addMonths(new Date(),-1);
		operatingReportNewService.operatingReportMonth(month);
	}

    @GetMapping(value = "/syncImHistoryMessageTask")
	// 同步即时通讯聊天记录
	public void syncImHistoryMessageTask(String date) throws Exception {
		if(date == null){
			date = DateUtil.format(DateUtil.addHours(new Date(),-2), DateUtil.YEAR_MONTH_DAY_HOUR);
		}
		Object o = imFeignService.historyGet(date);
		JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(o));
		if(jsonObject.get("code").equals(200)){
			Boolean success = redisCache.getRedisTemplate().opsForValue().setIfAbsent("syncImHistoryMessage" + date,date);
			if(!success){
				return;
			}
			String url = jsonObject.getString("url");
			if(StringUtils.isEmpty(url)){
				return;
			}
			File file = new File(FileUtils.getTempDirectoryPath() + url.substring(url.lastIndexOf("/")));
			URL url1 = new URL(url);
			FileUtils.copyURLToFile(url1,file);
			historyMessageService.saveImHistoryMessage(new File(file.getAbsolutePath()));
		}
	}

	@GetMapping(value = "/autoAffirmReceiveTask")
	// 自动确认收货
	public void affirmReceive(){
		studentGoodsSellService.affirmReceive(null);
	}

	@GetMapping(value = "/closeStudentServiceTag")
	// 关闭指定学员服务指标
	public void closeStudentServiceTag(){
		studentServeService.closeStudentServiceTag();
	}

	@GetMapping(value = "/pushWaitSendMessageTask")
	// 每天9点推送前一天22点之后的推送消息
	public void pushWaitSendMessageTask(){
		sysMessageService.pushWaitSendMessageTask();
	}

	@GetMapping(value = "/repertoryWarn")
	// 商品库存预警
	public void repertoryWarn(){
		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				goodsService.repertoryWarn(tenantInfo.getId());
			}
		}
	}

	@GetMapping(value = "/refreshUserMusicGroupPaymentStatusTask")
	// 刷新学员乐团付费状态
	public void refreshUserMusicGroupPaymentStatusTask(){
		musicGroupPaymentCalenderDetailService.refreshUserMusicGroupPaymentStatusTask();
	}

	@GetMapping("/refreshPaymentFeeStatus")
	// 刷新付费状态
	public void refreshPaymentFeeStatus() {
		musicGroupStudentFeeService.refreshPaymentFeeStatus();
	}

	@GetMapping("/vipGroupAwardedMonthlyRewards")
	// vip课月度奖励
	public void vipGroupAwardedMonthlyRewards() {
		//问过测试了，这个功能没有用过
//		vipGroupService.awardedMonthlyRewards();
	}

	@GetMapping("/vipGroupTeacherSalarySettlement")
	// vip课课酬结算
	public void vipGroupTeacherSalarySettlement() {
        List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				courseScheduleTeacherSalaryService.teacherSalarySettlement(tenantInfo.getId());
			}
		}
		redisCache.getRedisTemplate().opsForSet().add(CourseScheduleTeacherSalaryService.TASK_KEY, "VIP");
	}

	@GetMapping("/practiceTeacherSalarySettlement")
	// 陪练课课酬结算
	public void practiceTeacherSalarySettlement() {
        List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				courseScheduleTeacherSalaryService.practiceTeacherSalarySettlement(tenantInfo.getId());
			}
		}
		redisCache.getRedisTemplate().opsForSet().add(CourseScheduleTeacherSalaryService.TASK_KEY, "PRACTICE");
	}

	// 乐团课课酬结算
	@GetMapping("/musicGroupTeacherSalarySettlement")
	public void musicGroupTeacherSalarySettlement() {
        List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				courseScheduleTeacherSalaryService.musicGroupTeacherSalarySettlement(tenantInfo.getId());
			}
		}
		redisCache.getRedisTemplate().opsForSet().add(CourseScheduleTeacherSalaryService.TASK_KEY, "MUSIC");
	}

	@GetMapping("/updateCourseScheduleToOverStatus")
	// 更新课程状态至已结束
	public void updateCourseScheduleToOverStatus() throws Exception {
		List<Long> courseIds = courseScheduleService.updateCourseScheduleToOverStatus();
		courseEventSource.courseStatusChange(courseIds);
		courseIds = courseScheduleService.updateCourseScheduleToUnderway();
		courseEventSource.courseStatusChange(courseIds);
		//发送定时群消息
		imSendGroupMessageService.sendTimedMessages();
		//更新乐团课统计信息
		courseScheduleStatisticsService.courseScheduleStatistics();
	}

	@GetMapping("/updateVipGroupToFinishedStatus")
	// 更新VIP课程状态至已结束
	public void updateVipGroupToFinishedStatus() {
		vipGroupService.updateVipGroupStatusToFinished();
	}

	@GetMapping("/stopVipGroupWithNoCreate")
	// 取消达到报名时间未达到报名人数的vip课
	public void stopVipGroupWithNoCreate() {
		vipGroupService.stopVipGroupWithNoCreate(null);
	}

	@GetMapping("/pushNoSignOutMessage")
	// 推送未签退消息提醒
	public void pushNoSignOutMessage() {
		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				teacherAttendanceService.pushNoSignOutMessage(tenantInfo.getId());
			}
		}
	}

	@GetMapping("/studentCoursesScheduleRemind")
	// 学生有课提醒
	public void studentCoursesScheduleRemind() {
		// courseScheduleService.studentCoursesScheduleRemind();
	}

	@GetMapping("/studentSignInRemind")
	// 学生上课提醒
	public void studentSignInRemind() {
		courseScheduleService.studentSignInRemind();
	}

	@GetMapping("/studentHomeworkRemind")
	// 学生作业提醒
	public void studentHomeworkRemind() {
		studentCourseHomeworkService.homeworkRemind();
	}

	@GetMapping("/teacherCoursesScheduleRemind")
	// 老师有课提醒
	public void teacherCoursesScheduleRemind() {
		courseScheduleService.teacherCoursesScheduleRemind();
	}

	@GetMapping("/teacherSignInRemind")
	// 老师上课提醒
	public void teacherSignInRemind() {
		// courseScheduleService.teacherSignInRemind();
	}

	@GetMapping("/homeworkNoReplyRemind")
	// 老师未回复作业提醒
	public void homeworkNoReplyRemind() {
		courseHomeworkService.homeworkNoReplyRemind();
	}

	// 查询订单状态
	@GetMapping("/queryOrderStatus")
	public void queryOrderStatus() throws Exception {
		try {
			studentPaymentOrderService.queryOrderStatus();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 统计老师课酬
	@GetMapping("/teacherCourseStatistic")
	public void teacherCourseStatisticsService() throws Exception {
		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				TenantContextHolder.setTenantId(tenantInfo.getId());
				teacherCourseStatisticsService.teacherCourseStatistic();
				TenantContextHolder.clearTenantId();
			}
		}
	}

	// 更新历史陪练课至已结束
	@GetMapping("/updateHistoryPracticeGroupStatus")
	public void updateHistoryPracticeGroupStatus() {
		practiceGroupService.updateHistoryPracticeGroupStatus();
	}

	// 练习报告定时推送
	@GetMapping("/pushStudyReport")
	public void pushStudyReport() {
		practiceGroupService.pushStudyReport(null, "JIGUANG");
	}

	// 新增待填写月报定时推送(推送老师)
	@GetMapping("/pushNeedPostReport")
	public void pushNeedPostReport() {
		courseScheduleEvaluateService.pushNeedPostReport();
	}

	// 定时预生成待提交月报
	@GetMapping("/createEvaluate")
	public void createEvaluate() {
		courseScheduleEvaluateService.createEvaluate(new Date());
	}

	// 新增待填写评论定时推送(推送老师)
	@GetMapping("/pushNeedReview2Teacher")
	public void pushNeedReview2Teacher() {
		courseReviewService.pushNeedReview2Teacher();
	}

	//对外无学生课程组提醒
	@GetMapping("/noStudentsCourseGroupRemind")
	public void noStudentsCourseGroupRemind(){
		coursesGroupService.noStudentsCourseGroupRemind();
	}

	//更新对外课程组状态至已结束
	@GetMapping("/finishCourseGroup")
	public void finishCourseGroup(){
		coursesGroupService.finishCourseGroup();
	}

	//学生服务信息统计
	@GetMapping("/exercisesSituationStatistics")
	public void exercisesSituationStatistics(String monday){
		TenantContextHolder.setTenantId(1);
		studentServeService.exercisesSituationStatistics2(monday,1);
		TenantContextHolder.clearTenantId();
//		studentServeService.exercisesSituationStatistics2(null,new ArrayList<>(Arrays.asList(1095257)));
//		studentServeService.exercisesSituationStatistics(null);
	}

	//更新学生运营指标
	@GetMapping("/updateStudentOperatingTag")
	public void updateStudentOperatingTag(){
		studentService.updateOperatingTempTag();
	}

	// 更新乐团缴费日历的状态
	@GetMapping("/updateMusicGroupPaymentCalenderStatus")
	public void updateMusicGroupPaymentCalenderStatus() {
		musicGroupPaymentCalenderService.autoUpdateMusicGroupPaymentCalenderStatus();
	}

	// 更新乐团学员缴费状态
	@GetMapping("/updateMusicGroupStudentFeeStatus")
	public void updateMusicGroupStudentFeeStatus() {
//		musicGroupPaymentCalenderService.autoUpdateMusicGroupStudentFeeStatus();
	}

	// 推送教师异常考勤
	@GetMapping("/pushTeacherExceptionAttendanceTask")
	public void pushTeacherExceptionAttendanceTask() {
		teacherAttendanceService.pushTeacherExceptionAttendanceTask();
	}

	//应布置课外训练提醒
	@GetMapping("/studentServeRemind")
	public void studentServeRemind(){
		extracurricularExercisesService.studentServeRemind();
	}

	//经营报表
	@GetMapping("/operatingReport")
	public void operatingReport(){
		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				TenantContextHolder.setTenantId(tenantInfo.getId());
				operatingReportService.statistics(tenantInfo.getId());
				TenantContextHolder.clearTenantId();
			}
		}
	}

	@GetMapping("/updateCourseActualPrice")
	public void updateCourseActualPrice(){
		courseEventSource.courseStatusChange(null);
	}

	@GetMapping("/countIndexBaseData")
	public void countIndexBaseData(String month, String dataTypes){
		Set<IndexDataType> dataTypeSet = new HashSet<>();
		if(StringUtils.isNotBlank(dataTypes)){
			dataTypeSet = Arrays.stream(dataTypes.split(",")).map(s->IndexDataType.valueOf(s)).collect(Collectors.toSet());
		}

		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				indexBaseMonthDataService.indexBaseDataTask(tenantInfo.getId(), month, dataTypeSet);
			}
		}
	}

	//乐团巡查计划当日9:00
	@GetMapping("/inspectionPlan")
	public void inspectionPlan(){
		inspectionItemPlanService.pushNotice();
	}

	//乐保到期提醒
	@GetMapping("/maintenanceNotice")
	public void maintenanceNotice(){
		studentInstrumentService.pushNotice();
	}

	//每年9.1升级学员的班级
	@GetMapping("/updateGrade")
	public void updateGrade(){
		studentService.updateGrade();
	}

	//乐保历史数据处理
	@GetMapping("/maintenanceOldDateAdd")
	public void maintenanceOldDateAdd(){
		studentInstrumentService.addOldStudentInstrument();
	}

	//更新学员指导老师和声部信息
	@GetMapping("/updateStudentTeacherAndSubject")
	public void updateStudentTeacherAndSubject(){
		studentService.updateStudentTeacherAndSubject();
	}

	//推送查看今日收入提醒
	@GetMapping("/todayIncomeRemind")
	public void todayIncomeRemind(){
		courseScheduleTeacherSalaryService.todayIncomeRemind();
	}

	//大雅基本工资标记
	@GetMapping("/salaryMarkNew")
	public void salaryMarkNew(Date startDay){
		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				TenantContextHolder.setTenantId(tenantInfo.getId());
				courseScheduleTeacherSalaryService.salaryMarkNew(startDay,tenantInfo.getId());
				TenantContextHolder.clearTenantId();
			}
		}
	}

	//历史异常数据记录
	@GetMapping("/indexErrDataRecordTask")
	public void indexErrDataRecordTask(String date){
		indexErrDataRecordService.indexErrDataRecordTask(date);
	}

	//历史异常数据记录
	@GetMapping("/autoCleanPreCourseTask")
	public void autoCleanPreCourseTask(){
		//获取所有未确认的预排课数据
		List<MusicGroupSchoolTermCourseDetail> courseDetails = musicGroupSchoolTermCourseDetailDao.queryAllNoCourse();
		if(courseDetails.size() > 0){
			for (MusicGroupSchoolTermCourseDetail courseDetail : courseDetails) {
				classGroupService.cancelPreCourseSchedule(courseDetail.getId(),null);
			}
		}
	}

	@ApiOperation("每天10点推送排课、续费提醒")
	@GetMapping(value = "/musicSchoolTermPush")
	public void musicSchoolTermPush() {
		Object o = redisCache.get("musicSchoolTermPush");
		if(o != null){
			return;
		}
		List<TenantInfo> tenantInfos = tenantInfoService.list(new QueryWrapper<TenantInfo>().eq("state_",1));
		if(tenantInfos != null && tenantInfos.size() > 0){
			for (TenantInfo tenantInfo : tenantInfos) {
				musicGroupSchoolTermCourseDetailService.musicSchoolTermPush(tenantInfo.getId());
			}
		}
		redisCache.getRedisTemplate().opsForValue().set("musicSchoolTermPush","musicSchoolTermPush",
				23,
				TimeUnit.HOURS);
	}

	@ApiOperation("会员到期后清空会员信息")
	@GetMapping(value = "/cleanStudentMember")
	public void cleanStudentMember() {
		studentServeService.cleanStudentMember();
	}

	@ApiOperation("清理学员云教练连续使用天数")
	@GetMapping(value = "/cleanStudentCloudStudySequenceDays")
	public void cleanStudentCloudStudySequenceDays(){
		studentService.cleanStudentCloudStudySequenceDays();
	}

	@ApiOperation("本周学员训练提醒")
	@GetMapping(value = "/curWeekStudentTrainRemind")
	public void curWeekStudentTrainRemind(){
		sysMusicCompareRecordService.curWeekStudentTrainRemind();
	}

	@ApiOperation("标记进行中乐团在读学员+VIP、网管有课学员总数（除弦乐声部、去重，去除在云教练的乐团的学员")
	@GetMapping(value = "/remarkCountFlag")
	public void remarkCountFlag(){
//		studentService.remarkCountFlag();
	}

	@ApiOperation("兑换码分配量检测")
	@GetMapping(value = "/redemptionCodeWarn")
	public void redemptionCodeWarn(){
		appRedemptionCodeService.checkLowVolume();
	}

    @ApiOperation("定时校验-机构订单状态")
    @GetMapping(value = "/checkTenantOrder")
    public void checkTenantOrder(){
        tenantOrderRecordService.checkTenantOrder();
    }

    @ApiOperation("每晚12点-检查机构状态")
    @GetMapping(value = "/checkTenantState")
    public void checkTenantState(){
        tenantInfoService.checkTenantState();
    }

    @ApiOperation("查询老师协议签订状态")
    @GetMapping(value = "/queryTeacherContractSignStatus")
    public void queryTeacherContractSignStatus(){
    	teacherContractsService.queryTeacherContractSignStatus();
    }

    @ApiOperation("每分钟-查询是否有直播间需要创建")
    @GetMapping(value = "/createLiveRoom")
    public void createLiveRoom(){
        imLiveBroadcastRoomService.createLiveRoom();
    }

    @ApiOperation("每分钟-查询是否有直播间需要销毁")
    @GetMapping(value = "/destroyExpiredLiveRoom")
    public void destroyExpiredLiveRoom(){
        imLiveBroadcastRoomService.destroyExpiredLiveRoom();
    }

    @ApiOperation("学员小课统计")
    @GetMapping(value = "/studentSmallClassStatistics")
    public void studentSmallClassStatistics(){
		studentStatisticsService.updateStudentStatistics();
    }

    @ApiOperation("定时任务-修改训练营状态-每天0点执行")
    @GetMapping(value = "/checkCampState")
    public void  checkCampState(){
        tempLittleArtistTrainingCampService.checkCampState();
    }

    @ApiOperation("每天早上8点执行-提醒当天开启训练营并已分群的用户开始训练")
    @GetMapping(value = "/pushStartTrain")
    public void  pushStartTrain(){
        tempLittleArtistTrainingCampService.pushStartTrain();
    }
}
