package com.ssj.aijia.common.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.conch.conch.domain.ConchDerver;
import com.ssj.bean.weixin.problem.domain.CnArea;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.bean.weixin.user.domain.User;
import com.ssj.conch.util.FileTools;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.annotation.IgnoreSecurity;
import com.ssj.framework.core.security.annotation.ModifySecurity;
import com.ssj.framework.core.security.exception.CommonException;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.log.service.RequestApiLogService;
import com.ssj.service.conch.common.service.AppCommonService;
import com.ssj.service.conch.conch.service.ConchDerverService;
import com.ssj.service.conch.conch.service.HomeworkRankingService;
import com.ssj.service.conch.opentest.RecordQuestionService;
import com.ssj.service.conch.parents.v2.service.ParentV2Service;
import com.ssj.service.conch.utils.MapUtils;
import com.ssj.service.kmt.arrange.service.KmtArrangeAllotService;
import com.ssj.service.kmt.service.KmtExerciseBookService;
import com.ssj.service.kmt.service.KmtExerciseMapperService;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.sys.situation.service.LearningConditionService;
import com.ssj.service.sys.teacher.OnlineTeacherWeightService;
import com.ssj.service.test.DeveloperService;
import com.ssj.service.weixin.library.service.ILibVipService;
import com.ssj.service.weixin.problem.service.CnAreaService;
import com.ssj.service.weixin.problem.service.ProblemService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yangcan
 * 类描述:后台运维接口(非爱加人员慎用)
 * 创建时间:2019年5月6日 上午11:03:16

 */
@Api(value = "后台运维接口", tags = "后台运维接口")
@RestController
@RequestMapping("/api/devops/devops")
public class DevopsManagerController extends BaseController {

	@Reference(version = "1.0" ,timeout = 60000)
	private AppCommonService appCommonService;
	
	@Reference(version = "1.0" ,timeout = 60000)
	private PushTemplateService  pushTemplateService;
	
	@Reference(version = "1.0" ,timeout = 60000)
	private SconXingeService sconXingeService;
	
	@Autowired
	private TokenManager tokenManager;

	@Reference(version = "1.0" ,timeout = 60000)
	private RequestApiLogService requestApiLogService;

	@Reference(version = "1.0" ,timeout = 60000)
	private EasemobService easemobService;
	
	@Reference(version = "1.0" ,timeout = 60000)
	private ProblemService problemService;
	
	@Reference(version = "1.0", timeout = 60000)
    private ConchDerverService conchDerverService;
	
	@Reference(version = "1.0", timeout = 60000)
    private UserService userService;

	@Reference(version = "1.0", timeout = 60000)
    private HomeworkRankingService homeworkRankingService;
	@Reference(version = "1.0", timeout = 60000)
	private OnlineTeacherWeightService onlineTeacherWeightService;
	@Reference(version = "1.0", timeout = 60000)
	private CnAreaService cnAreaService;
	@Reference(version = "1.0", timeout = 60000)
	private LearningConditionService learningConditionService;
	@Reference(version = "1.0", timeout = 60000)
	private ILibVipService libVipService;
	@Reference(version = "1.0", timeout = 60000)
	private ParentV2Service parentV2Service;
	@Reference(version = "1.0", timeout = 60000)
	private KmtExerciseMapperService kmtExerciseMapperService;
	@Reference(version = "1.0", timeout = 60000)
	private KmtArrangeAllotService kmtArrangeAllotService;
	@Reference(version = "1.0", timeout = 60000)
	private DeveloperService developerService;
	@Reference(version = "1.0", timeout = 60000)
	private KmtExerciseBookService kmtExerciseBookService;
	@Reference(version = "1.0", timeout = 60000)
	private RecordQuestionService recordQuestionService;
	@Autowired
	private SystemResourceLocator systemResourceLocator;

	@ApiOperation(value = "测试Token", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testToken", method = RequestMethod.POST)
	public ResponseEntity testToken(@RequestParam(name = "userId") String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			List<String> token = tokenManager.getToken(userId);
			Map<String,Object> data =new HashMap<String, Object>();
			data.put("token", token);
		
			responseEntity.success(data,"成功");
		} catch (Exception e) {
			logger.error("获取用户token发生异常：", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}


	@ApiOperation(value = "通过userId获取token信息", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/getToken", method = RequestMethod.POST)
	public ResponseEntity getToken(@RequestParam(name = "userId") String userId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("token", tokenManager.getToken(userId));
			map.put("userId", userId);
			responseEntity.success(map,"成功");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}

	@ApiOperation(value = "通过token获取userId信息", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/getUserId", method = RequestMethod.POST)
	public ResponseEntity getUserId(@RequestParam(name = "token") String token) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			Map<String, Object> map = new HashMap<String,Object>();
			map.put("userId", tokenManager.getUserId(token));
			map.put("token", token);
			responseEntity.success(map,"成功");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "测试环信推送", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testEasemobSendMessage", method = RequestMethod.POST)
	public ResponseEntity testEasemobSendMessage(@RequestParam(name = "easemobName") String easemobName,@RequestParam(name = "content") String content) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String title = "你灿哥给你发消息了!";
			easemobService.sendSystemMessages(easemobName, title, JSON.toJSONString(content));
			responseEntity.success();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "测试微信公众号推送", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testWxPush", method = RequestMethod.POST)
	public ResponseEntity testWxPush(@RequestParam(name = "accessToken") String accessToken,@RequestParam(name = "openId") String openId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			Map<String,String> data =new HashMap<String, String>();
			data.put("first", "微信公众号推送测试\n");
			data.put("keyword1","私塾家");
			data.put("keyword2", "私塾家");
			data.put("keyword3", DateHelper.format(new Date(),"yyyy年MM月dd日"));
			data.put("remark", "\n推送测试请忽略!");
			String template_id=(String) SystemResourceLocator.getValue("sendTemplate55");
			//String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/zuoyb/inform_"+id+".html";
			String url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.nayun.framework&android_schema=";
			SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id, url, data);
			pushTemplateService.saveAndSendPushWxTemplate(sendTemplateShort);
			responseEntity.success();
		} catch (Exception e) {
			logger.error("测试微信公众号推送", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "小塾生成二维码", httpMethod = "POST")
	@IgnoreSecurity
	@ModifySecurity
	@RequestMapping(value = "/conchCreateQrcode", method = RequestMethod.POST)
	public ResponseEntity conchCreateQrcode(@RequestParam(name = "derver") String derver) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			//更新小塾创建时间为一个月前
			ConchDerver conchDerver = conchDerverService.findByDerver(derver);
			//将时间改为上个月的第一天
			conchDerver.setCreatedDate(DateHelper.getLastMonthFirstDay(new Date()));
			conchDerverService.save(conchDerver);
			//清除缓存
			tokenManager.delString("DERVER_"+derver);
			
			responseEntity.success();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}

	@ApiOperation(value = "解绑小塾内部专用",httpMethod = "POST")
    @ModifySecurity
	@IgnoreSecurity
	@RequestMapping(value = "/untieDerverByCeshi", method = RequestMethod.POST)
	public ResponseEntity untieDerverByCeshi(@RequestParam(name = "derver") String derver) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			responseEntity =conchDerverService.untyingParents(derver);
			responseEntity.success();
		} catch (Exception e) {
			logger.error("解绑小塾异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "解绑小塾异常");
		}
		return responseEntity;
	}

	@ApiOperation(value = "清除废弃用户环信账号",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/cleanNoUserEasemobName", method = RequestMethod.POST)
	public ResponseEntity cleanNoUserEasemobName() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			List<User> userList = userService.findNoUserEasemobName();
			int i = 0;
			for (User user : userList) {
				if(StringUtils.isNotBlank(user.getEasemobName())) {
					easemobService.deleteUserSingle(user.getEasemobName());
					i++;
				}
				user.setEasemobName(null);
			}
			userService.save(userList);
			responseEntity.success("总共清除"+i+"个废弃环信账号");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "清除废弃用户环信账号异常");
		}
		return responseEntity;
	}

	@ApiOperation(value = "测试小塾积分计算定时任务",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testConchIntegralCompute", method = RequestMethod.POST)
	public ResponseEntity testConchIntegralCompute() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int computeCount = homeworkRankingService.computeCorrectionIntegral();
			responseEntity.success("总共计算"+ computeCount + "次");
		} catch (Exception e) {
			logger.error("计算积分异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "计算失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "测试实时权重计算定时任务",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testRealTimeWeightCompute", method = RequestMethod.POST)
	public ResponseEntity testRealTimeWeightCompute() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			long computeCount = onlineTeacherWeightService.computeAndSaveWeight();
			responseEntity.success("总共计算"+ computeCount + "次");
		} catch (Exception e) {
			logger.error("实时权重计算异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "计算失败");
		}
		return responseEntity;
	}
	
	
	@ApiOperation(value = "测试系统消息推送",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testSystemMessagePush", method = RequestMethod.POST)
	public ResponseEntity testSystemMessagePush(@RequestParam(name = "type") String type,
			@RequestParam(name = "title") String title) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			appCommonService.pushAllBySystemMessage(type, title);
			responseEntity.success();
		} catch (Exception e) {
			logger.error("测试系统消息推送异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙,请稍后重试");
		}
		return responseEntity;
	}

	@RequestMapping(value = "/updateSchoolData", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "更新学校经纬度", httpMethod = "POST", notes = "更新学校经纬度")
	public ResponseEntity updateSchoolData() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			List<CnArea> list = cnAreaService.findLatLngIsNullList();
			int num = 0;
			for (CnArea cnArea : list) {
				if (StringUtils.isNotBlank(cnArea.getSchoolAddress())) {
					JSONObject location = MapUtils.getLngAndLat(cnArea.getSchoolAddress());
					if (location != null) {
						cnArea.setSchoolLng(location.getString("lng"));
						cnArea.setSchoolLat(location.getString("lat"));
						cnAreaService.save(cnArea);
						num++;
					}
				}
			}
			responseEntity.success("成功更新"+num+"条学校经纬度");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}


	@RequestMapping(value = "/exportConchData", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "exportConchData", httpMethod = "POST", notes = "更新小塾数据")
	public ResponseEntity exportConchData(@RequestParam(name = "filePath") String filePath) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			File fi = new File(filePath);
			InputStream ins = new FileInputStream(fi);
			Workbook wb = WorkbookFactory.create(ins);
			ins.close();
			// 得到excel工作表对象
			Sheet sheet = wb.getSheetAt(0);

			//总行数
			int sumRow = sheet.getPhysicalNumberOfRows();
			//从第二行开始读取
			for (int i = 1; i < sumRow; i++) {
				Row row = sheet.getRow(i);
				row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
				//如果该列没有订单编号则继续往下读取
				if(row == null || row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
					continue;
				}

				//获取第一列imei号
				String imei = row.getCell(0).getStringCellValue();
				System.out.println("imei:"+imei);
				//通过imei号查询小塾信息
				List<ConchDerver> list = conchDerverService.findByImei(imei);
				if(!CollectionUtils.isEmpty(list)) {
					StringBuffer derver = new StringBuffer();
					StringBuffer simcard = new StringBuffer();
					for (ConchDerver conchDerver:list) {
						derver.append(conchDerver.getDerver()).append(",");
						simcard.append(conchDerver.getSimcard()).append(",");
					}
					//写入第二列设备号
					row.createCell(1).setCellValue(derver.substring(0,derver.length()-1));
					//写入第三列卡号
					row.createCell(2).setCellValue(simcard.substring(0,simcard.length()-1));
				}
			}
			try {
				FileOutputStream out = new FileOutputStream(filePath);
				wb.write(out);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			responseEntity.success();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}


	@RequestMapping(value = "/matchConchData", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "matchConchData", httpMethod = "POST", notes = "匹配小塾数据库")
	public ResponseEntity matchConchData(@RequestParam(name = "filePath") String filePath) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			File fi = new File(filePath);
			InputStream ins = new FileInputStream(fi);
			Workbook wb = WorkbookFactory.create(ins);
			ins.close();
			// 得到excel工作表对象
			Sheet sheet = wb.getSheetAt(0);

			//总行数
			int sumRow = sheet.getPhysicalNumberOfRows();
			//从第二行开始读取
			for (int i = 1; i < sumRow; i++) {
				Row row = sheet.getRow(i);
				//获取第二列小塾设备号
				row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
				//如果第二列小塾设备号没有值
				if(row == null || row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).getStringCellValue())) {
					continue;
				}

				//获取第二列imei号
				String derver = row.getCell(1).getStringCellValue();
				System.out.println("imsi:"+derver);
				//通过derver号查询小塾信息
				ConchDerver conchDerver = conchDerverService.findByDerver(derver);
				if(conchDerver == null) {
					//写入第二列设备号
					row.createCell(5).setCellValue("是");
				}
			}
			try {
				FileOutputStream out = new FileOutputStream(filePath);
				wb.write(out);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			responseEntity.success();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}

	@RequestMapping(value = "/importConchData", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "导入小塾sim信息（第一行需为标题，第一列需为sim卡号，第二列为sim）", httpMethod = "POST", notes = "导入小塾sim信息（第一行需为标题，第一列需为sim卡号，第二列为sim）")
	public ResponseEntity importConchData(@RequestParam(name = "filePath") String filePath) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			return conchDerverService.importConchData(filePath);
		} catch (Exception e) {
			logger.error("导入sim失败", e);
			responseEntity.failure(ResponseConstant.CODE_500, "导入sim失败");
		}

		return responseEntity;
	}

	@RequestMapping(value = "/generateHomeworkCountData", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "统计作业数据（总题数、错题数、正确率）", httpMethod = "POST", notes = "统计作业数据（总题数、错题数、正确率）")
	public ResponseEntity generateHomeworkCountData(@RequestParam(required = false) Integer offset) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int totalCount = learningConditionService.countDailyHomeworkData(offset);
			return responseEntity.success("统计完成，共生成" + totalCount + "条记录");
		} catch (Exception e) {
			logger.error("统计失败", e);
			responseEntity.failure(ResponseConstant.CODE_500, "统计失败");
		}

		return responseEntity;
	}

	@RequestMapping(value = "/generateMonthlyHomeworkCountData", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "统计每月作业数据（总题数、错题数、正确率）", httpMethod = "POST", notes = "统计作业数据（总题数、错题数、正确率）")
	public ResponseEntity generateMonthlyHomeworkCountData(@RequestParam(required = false) Integer offset,
														   @RequestParam Boolean calculateScore,
														   @RequestParam Boolean notify) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int totalCount = learningConditionService.countMonthlyHomeworkData(offset, calculateScore, notify);
			return responseEntity.success("统计完成，共生成" + totalCount + "条记录");
		} catch (Exception e) {
			logger.error("统计失败", e);
			responseEntity.failure(ResponseConstant.CODE_500, "统计失败");
		}

		return responseEntity;
	}

	@RequestMapping(value = "/testGrowthReportNotifyTask", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "测试成长报告推送通知")
	public ResponseEntity testGrowthReportNotifyTask(@RequestParam(required = false) String vipId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			if (StringUtils.isNotBlank(vipId)) {
				responseEntity = developerService.testGrowthReportNotifyTask(vipId);
			} else {
				developerService.testAllGrowthReportNotifyTask();
			}
		} catch (Exception e) {
			logger.error("推送完成", e);
			responseEntity.failure(ResponseConstant.CODE_500, "推送失败");
		}

		return responseEntity.success("推送成功");
	}

	@RequestMapping(value = "/removeRequestLog", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "清除请求日志信息", httpMethod = "POST", notes = "清除请求日志信息")
	public ResponseEntity removeRequestLog(@ApiParam(required = true, name = "days", value = "保留日志天数")
											   @RequestParam(name = "days",required = true) int days) {
		ResponseEntity responseEntity;
		try {
			if(days < 1) {
				days = 1;
			}
			//清除非保留日志天数数据
			responseEntity = requestApiLogService.deleteLogs(days);
		} catch (Exception e) {
			logger.error("清除请求日志信息失败", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "清除请求日志信息失败");
		}
		return responseEntity;
	}


	@ApiOperation(value = "手动更新出勤信息",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/updateAttendType", method = RequestMethod.POST)
	public ResponseEntity updateAttendType(@RequestParam(name = "date") String date)  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			kmtArrangeAllotService.updateAttendType(date);
			responseEntity.success();
		} catch (Exception e) {
			logger.error("更新出勤信息失败", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新出勤信息失败");
		}
		return responseEntity;
	}


	@ApiOperation(value = "全量同步练习册题目到es",	notes = "es中索引名为kmt_exercise_question_know，同步前需把数据库表kmt_exercise_question_know.loaded=1或2的记录设置loaded=0")
	@IgnoreSecurity
	@RequestMapping(value = "/updateTotal2Es", method = RequestMethod.POST)
	public ResponseEntity updateTotal2Es()  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			long updateCount = kmtExerciseMapperService.updateTotal2Es();
			responseEntity.success(String.format("更新完成:共更新%s条数据", updateCount));
		} catch (Exception e) {
			logger.error("全量更新es索引kmt_exercise_question_know中的数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "全量同步kmt题目到es",	notes = "es中索引名为kmt_question_know，同步前需设置数据库表kmt_question_know.loaded=0")
	@IgnoreSecurity
	@RequestMapping(value = "/updateAllKmtQuestion2Es", method = RequestMethod.POST)
	public ResponseEntity updateAllKmtQuestion2Es()  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			long updateCount = developerService.updateAllKmtQuestion2Es();
			responseEntity.success(String.format("更新完成:共更新%s条数据", updateCount));
		} catch (Exception e) {
			logger.error("全量更新es索引kmt_question_know中的数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "生成周报数据",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/generateWeeklyReport", method = RequestMethod.POST)
	public ResponseEntity generateWeeklyReport(@RequestParam(required = false) Integer offset,
											   @RequestParam Boolean calculateScore,
											   @RequestParam Boolean notify)  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int weeklyReportCount = learningConditionService.prepareGenerateWeeklyReport(offset, calculateScore);
			String msg = String.format("成功生成%s条数据", weeklyReportCount);
			if (notify) {
				try {
					learningConditionService.pushWeeklyGrowthReportNotify();
					msg = msg + "，推送通知成功";
				} catch (Exception e) {
					logger.error("给对应学生的家长推送周报通知异常-->",e);
					msg = msg + "，推送通知失败";
				}
			}
			responseEntity.success(msg);
		} catch (Exception e) {
			logger.error("生成周报数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新出勤信息失败");
		}
		return responseEntity;
	}


	@ApiOperation(value = "初始化config到redis",httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/initRedisUtilsConfig", method = RequestMethod.POST)
	public ResponseEntity initRedisUtilsConfig()  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			systemResourceLocator.init();
			responseEntity.success();
		} catch (Exception e) {
			logger.error("初始化config到redis", e);
			responseEntity.failure(ResponseConstant.CODE_500, "初始化config到redis失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "测试某个方法", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/testOneMethod", method = RequestMethod.POST)
	public ResponseEntity testOneMethod() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			responseEntity = developerService.testOneMethod();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新周报知识点占比和掌握程度情况")
	@IgnoreSecurity
	@RequestMapping(value = "/updateStudentWeeklyReportKnowledgeSituation", method = RequestMethod.POST)
	public ResponseEntity updateStudentWeeklyReportKnowledgeSituation() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int updateCount = learningConditionService.updateStudentWeeklyReportKnowledgeSituation();
			return responseEntity.success(updateCount, "更新成功");
		} catch (Exception e) {
			logger.error("更新周报知识点占比和掌握程度情况异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新月报知识点掌握程度情况")
	@IgnoreSecurity
	@RequestMapping(value = "/updateMonthlyReportKnowledgeSituation", method = RequestMethod.POST)
	public ResponseEntity updateMonthlyReportKnowledgeSituation() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int updateCount = learningConditionService.updateMonthlyReportKnowledgeSituation();
			return responseEntity.success(updateCount, "更新成功");
		} catch (Exception e) {
			logger.error("更新月报知识点掌握程度情况异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "统计生成知识点错题统计数据")
	@IgnoreSecurity
	@RequestMapping(value = "/generateKnowledgeWrongQuestionCount", method = RequestMethod.POST)
	public ResponseEntity generateKnowledgeWrongQuestionCount(@RequestParam(required = false) String homeworkId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.generateKnowledgeWrongQuestionCount(homeworkId);
			return responseEntity.success(count, "生成成功");
		} catch (Exception e) {
			logger.error("统计生成知识点错题统计数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新错题知识点统计数据题目状态")
	@IgnoreSecurity
	@RequestMapping(value = "/updateKnowledgeWrongQuestionCountQuestionStatus", method = RequestMethod.POST)
	public ResponseEntity updateKnowledgeWrongQuestionCountQuestionStatus() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.updateKnowledgeWrongQuestionCountQuestionStatus();
			return responseEntity.success(count, "更新成功");
		} catch (Exception e) {
			logger.error("更新错题知识点统计数据题目状态异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新指定月份月报中的transcended_student_proportion（超过?比例的同级学生）")
	@IgnoreSecurity
	@RequestMapping(value = "/updateTranscendedStudentProportion", method = RequestMethod.POST)
	public ResponseEntity updateTranscendedStudentProportion(@RequestParam(required = false) String month) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.updateTranscendedStudentProportion(month);
			return responseEntity.success(count, "更新成功");
		} catch (Exception e) {
			logger.error("更新指定月份月报中的transcended_student_proportion（超过?比例的同级学生）异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "统计生成学期知识点掌握熟练度数据")
	@IgnoreSecurity
	@RequestMapping(value = "/generateMasteryOfSemesterKnowledge", method = RequestMethod.POST)
	public ResponseEntity generateMasteryOfSemesterKnowledge(@RequestParam(required = false) Boolean countAllHomework) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.generateMasteryOfSemesterKnowledge(countAllHomework);
			return responseEntity.success(count, "生成成功");
		} catch (Exception e) {
			logger.error("统计生成学期知识点掌握熟练度数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新es中zyb_know_how_details_sort索引的数据",	notes = "es中索引名为zyb_know_how_details_sort")
	@IgnoreSecurity
	@RequestMapping(value = "/updateKnowHowDetailsSortInEs", method = RequestMethod.POST)
	public ResponseEntity updateKnowHowDetailsSortInEs()  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			developerService.updateKnowHowDetailsSortInEs();
			responseEntity.success("更新成功");
		} catch (Exception e) {
			logger.error("更新es中zyb_know_how_details_sort索引的数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新kmt_exercise_book_count",	notes = "更新kmt_exercise_book_count")
	@IgnoreSecurity
	@RequestMapping(value = "/updateKmtExerciseBookCount", method = RequestMethod.POST)
	public ResponseEntity updateKmtExerciseBookCount(@RequestParam(name = "exerciseBookId", required = false) String exerciseBookId)  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.updateKmtExerciseBookStatus(exerciseBookId);
			responseEntity.success(count, "更新成功");
		} catch (Exception e) {
			logger.error("更新kmt_exercise_book_count异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新kmt_exercise_book_status_count",	notes = "更新kmt_exercise_book_status_count")
	@IgnoreSecurity
	@RequestMapping(value = "/updateKmtExerciseBookStatusCount", method = RequestMethod.POST)
	public ResponseEntity updateKmtExerciseBookStatusCount(@RequestParam(name = "exerciseBookId", required = false) String exerciseBookId)  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.updateKmtExerciseBookStatusCount(exerciseBookId);
			responseEntity.success(count, "更新成功");
		} catch (Exception e) {
			logger.error("更新kmt_exercise_book_status_count异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新scon_knowledge_proficiency.knowledge_version",	notes = "更新scon_knowledge_proficiency.knowledge_version")
	@IgnoreSecurity
	@RequestMapping(value = "/updateKnowledgeProficiencyKnowledgeVersion", method = RequestMethod.POST)
	public ResponseEntity updateKnowledgeProficiencyKnowledgeVersion()  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.updateKnowledgeProficiencyKnowledgeVersion();
			responseEntity.success(count, "更新成功");
		} catch (Exception e) {
			logger.error("更新scon_knowledge_proficiency.knowledge_version异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新zyb_student_push.type，type=0但是学生上传了作业，则type需要更新为4",	notes = "更新zyb_student_push.type，type=0但是学生上传了作业，则type需要更新为4")
	@IgnoreSecurity
	@RequestMapping(value = "/updateStudentPushType", method = RequestMethod.POST)
	public ResponseEntity updateStudentPushType()  {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			int count = developerService.updateStudentPushType();
			responseEntity.success(count, "更新成功");
		} catch (Exception e) {
			logger.error("更新zyb_student_push.type异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新kmt_exercise_book版本数据", notes = "更新kmt_exercise_book版本数据")
	@ModifySecurity
	@IgnoreSecurity
	@RequestMapping(value = "/updateVersion", method = RequestMethod.POST)
	public ResponseEntity updateVersion(@RequestParam int type, @RequestParam(required = false) String subject, @RequestParam(required = false) Integer version) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			kmtExerciseBookService.updateVersion(type, subject, version);
			responseEntity.success("更新成功");
		} catch (Exception e) {
			logger.error("更新kmt_exercise_book版本数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "导入练习册绑定机构数据", notes = "导入练习册绑定机构数据")
	@IgnoreSecurity
	@ModifySecurity
	@RequestMapping(value = "/updateExerciseLib", method = RequestMethod.POST)
	public ResponseEntity updateExerciseLib() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			kmtExerciseBookService.updateExerciseLib();
			responseEntity.success("导入成功");
		} catch (CommonException e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		} catch (Exception e) {
			logger.error("更新kmt_exercise_book版本数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "合并重复练习册数据", notes = "合并重复练习册数据")
	@IgnoreSecurity
	@ModifySecurity
	@RequestMapping(value = "/mergeSameExerciseBooks", method = RequestMethod.POST)
	public ResponseEntity delete() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			kmtExerciseBookService.mergeSameExerciseBooks();
			responseEntity.success("合并成功");
		} catch (CommonException e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		} catch (Exception e) {
			logger.error("合并重复练习册数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "合并失败");
		}
		return responseEntity;
	}

	@ApiOperation(value = "清除redis缓存", notes = "清除redis缓存")
	@ModifySecurity
	@RequestMapping(value = "/clearRedisCache", method = RequestMethod.POST)
	public ResponseEntity clearRedisCache(@RequestParam(name = "accessToken") String accessToken, @RequestParam String key) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			tokenManager.delString(key);
			responseEntity.success("清除成功");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}

	@ApiOperation(value = "添加出版社", notes = "添加出版社")
	@ModifySecurity
	@RequestMapping(value = "/addPress", method = RequestMethod.POST)
	public ResponseEntity addPress(@RequestParam(name = "accessToken") String accessToken, @RequestParam List<String> pressList) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			developerService.addPress(pressList);
			responseEntity.success("添加成功");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}

	@ApiOperation(value = "删除出版社", notes = "删除出版社")
    @ModifySecurity
	@RequestMapping(value = "/deletePress", method = RequestMethod.POST)
	public ResponseEntity deletePress(@RequestParam(name = "accessToken") String accessToken, @RequestParam List<String> pressList) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			developerService.deletePress(pressList);
			responseEntity.success("删除成功");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}

	@ApiOperation(value = "更新知识点", notes = "更新知识点")
	@ModifySecurity
	@RequestMapping(value = "/updateHowId", method = RequestMethod.POST)
	public ResponseEntity updateHowId(@RequestParam(name = "accessToken") String accessToken) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			recordQuestionService.updateHowId();
			responseEntity.success("更新成功");
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, e.getMessage());
		}
		return responseEntity;
	}

	@ApiOperation(value = "刷新练习册分配导出数据")
	@IgnoreSecurity
	@RequestMapping(value = "/refreshExerciseBookDistributionCount", method = RequestMethod.POST)
	public ResponseEntity refreshExerciseBookDistributionCount(@RequestParam(name = "exerciseBookId", required = false) String exerciseBookId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			developerService.refreshExerciseBookDistributionCount(exerciseBookId);
			responseEntity.success("更新成功");
		} catch (Exception e) {
			logger.error("刷新练习册分配导出数据异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
		}
		return responseEntity;
	}

    @ApiOperation(value = "更新练习册数据")
    @IgnoreSecurity
    @RequestMapping(value = "/updateKmtExerciseBookByKmtExerciseModify", method = RequestMethod.POST)
    public ResponseEntity updateKmtExerciseBookByKmtExerciseModify(@RequestParam(name = "exerciseBookId", required = false) String exerciseBookId) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            kmtExerciseBookService.updateKmtExerciseBookByKmtExerciseModify();
            responseEntity.success("更新成功");
        } catch (Exception e) {
            logger.error("更新练习册数据异常", e);
            responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
        }
        return responseEntity;
    }

    @ApiOperation(value = "更新更新反馈报告并通知家长")
    @IgnoreSecurity
    @RequestMapping(value = "/updateFeedbackReportAndNotifyParent", method = RequestMethod.POST)
    public ResponseEntity updateFeedbackReportAndNotifyParent(@RequestParam(name = "vipId") String vipId) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            developerService.updateFeedbackReportAndNotifyParent(vipId);
            responseEntity.success("更新成功");
        } catch (Exception e) {
            logger.error("更新更新反馈报告并通知家长异常", e);
            responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
        }
        return responseEntity;
    }


    @ApiOperation(value = "更新提分训练")
    @IgnoreSecurity
    @RequestMapping(value = "/regenerateTrainingRecommendQuestion", method = RequestMethod.POST)
    public ResponseEntity regenerateTrainingRecommendQuestion(@RequestParam(name = "studentWeeklyReportId") String studentWeeklyReportId) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
			if (StringUtils.isNotBlank(studentWeeklyReportId)) {
				int generateCount = developerService.regenerateTrainingRecommendQuestion(studentWeeklyReportId);
				responseEntity.success(generateCount, "更新成功");
			}
        } catch (Exception e) {
            logger.error("更新提分训练异常", e);
            responseEntity.failure(ResponseConstant.CODE_500, "更新失败");
        }
        return responseEntity;
    }
}