package com.ym.mec.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.ym.mec.biz.dal.dao.MusicGroupSchoolTermCourseDetailDao;
import com.ym.mec.biz.dal.entity.MusicGroupSchoolTermCourseDetail;
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.entity.UploadReturnBean;
import com.ym.mec.common.redis.service.RedisCache;
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.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 TenantPaymentOrderService tenantPaymentOrderService;

	@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 RedisCache<String, Object> redisCache;
	@Autowired
	private IndexBaseMonthDataService indexBaseMonthDataService;

	@Autowired
	private InspectionItemPlanService inspectionItemPlanService;

	@Autowired
	private StudentInstrumentService studentInstrumentService;

	@Autowired
	private CloudTeacherOrderService cloudTeacherOrderService;
	@Autowired
	private HistoryMessageService historyMessageService;
	@Autowired
	private UploadFileService uploadFileService;
	@Autowired
	private ImFeignService imFeignService;

	@Autowired
	private IndexErrDataRecordService indexErrDataRecordService;

	@Autowired
	private ClassGroupService classGroupService;

	@Autowired
	private MusicGroupSchoolTermCourseDetailDao musicGroupSchoolTermCourseDetailDao;

	@Autowired
	private MusicGroupSchoolTermCourseDetailService musicGroupSchoolTermCourseDetailService;

	@GetMapping(value = "/syncImHistoryMessageTask")
	// 同步即时通讯聊天记录
	public void syncImHistoryMessageTask(String date) throws Exception {
//		date = "2021060710";
		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("/")));
//			File file = new File("/Users/chenxiaoyu/Documents/" + url.substring(url.lastIndexOf("/")));
			URL url1 = new URL(url);
			FileUtils.copyURLToFile(url1,file);
			UploadReturnBean uploadReturnBean = uploadFileService.uploadImHistoryMsgFile(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(){
		goodsService.repertoryWarn();
	}

	@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() {
		courseScheduleTeacherSalaryService.teacherSalarySettlement();
		redisCache.getRedisTemplate().opsForSet().add(CourseScheduleTeacherSalaryService.TASK_KEY, "VIP");
//		courseScheduleTeacherSalaryService.salaryMark();
	}

	@GetMapping("/practiceTeacherSalarySettlement")
	// 陪练课课酬结算
	public void practiceTeacherSalarySettlement() {
		courseScheduleTeacherSalaryService.practiceTeacherSalarySettlement();
		redisCache.getRedisTemplate().opsForSet().add(CourseScheduleTeacherSalaryService.TASK_KEY, "PRACTICE");
//		courseScheduleTeacherSalaryService.salaryMark();
	}

	// 乐团课课酬结算
	@GetMapping("/musicGroupTeacherSalarySettlement")
	public void musicGroupTeacherSalarySettlement() {
		courseScheduleTeacherSalaryService.musicGroupTeacherSalarySettlement();
		redisCache.getRedisTemplate().opsForSet().add(CourseScheduleTeacherSalaryService.TASK_KEY, "MUSIC");
//		courseScheduleTeacherSalaryService.salaryMark();
	}

	@GetMapping("/updateCourseScheduleToOverStatus")
	// 更新课程状态至已结束
	public void updateCourseScheduleToOverStatus() {
		courseScheduleService.updateCourseScheduleToOverStatus();
		courseScheduleService.updateCourseScheduleToUnderway();
		courseEventSource.courseStatusChange(null);
	}

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

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

	@GetMapping("/pushNoSignOutMessage")
	// 推送未签退消息提醒
	public void pushNoSignOutMessage() {
		teacherAttendanceService.pushNoSignOutMessage();
	}

	@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();
		}
		tenantPaymentOrderService.queryOrderStatusFromRemote();
	}

	// 统计老师课酬
	@GetMapping("/teacherCourseStatistic")
	public void teacherCourseStatisticsService() throws Exception {
		teacherCourseStatisticsService.teacherCourseStatistic();
	}

	// 更新历史陪练课至已结束
	@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){
		studentServeService.exercisesSituationStatistics2(monday,null);
//		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(){
		operatingReportService.statistics();
	}

	@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());
		}
		indexBaseMonthDataService.indexBaseDataTask(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){
		courseScheduleTeacherSalaryService.salaryMarkNew(startDay);
	}

	//处理未生效的乐团云教练订单
	@GetMapping("/checkCloudOrderStart")
	public void checkCloudOrderStart(){
		cloudTeacherOrderService.checkCloudOrderStart();
	}

	//历史异常数据记录
	@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() {
		musicGroupSchoolTermCourseDetailService.musicSchoolTermPush();
	}

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