package com.ssj.aijia.common.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ssj.bean.common.files.domain.FileInfo;
import com.ssj.bean.weixin.problem.domain.Problem;
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.manager.TokenManager;
import com.ssj.framework.core.util.*;
import com.ssj.framework.files.service.FileInfoService;
import com.ssj.framework.idworker.IdWorker;
import com.ssj.service.conch.common.request.*;
import com.ssj.service.conch.common.service.AppCommonService;
import com.ssj.service.conch.conch.request.ConchSystemDerverReq;
import com.ssj.service.conch.conch.service.ConchSystemDerverService;
import com.ssj.service.conch.parents.v1.request.VipIdReq;
import com.ssj.service.conch.teacher.service.TeacherLibraryService;
import com.ssj.service.sys.appinfo.service.AppInfoService;
import com.ssj.service.sys.appinfo.service.dto.LastVersionAppInfoDto;
import com.ssj.service.sys.easemob.service.EasemobService;
import com.ssj.service.sys.push.service.SconXingeService;
import com.ssj.service.weixin.problem.service.ProblemService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @author yangcan
 * 类描述: 各端公共接口
 * 创建时间:2018年12月24日 下午4:10:18

 */
@Api(value = "各端公共接口", tags = "各端公共接口")
@RestController
@RequestMapping("/api/common/common")
public class AppCommonController 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;

	@Autowired
	private FileInfoService fileInfoService;

	@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 AppInfoService appInfoService;
	@Reference(version = "1.0" ,timeout = 60000)
	private ConchSystemDerverService conchSystemDerverService;

    @Reference(version = "1.0" ,timeout = 60000)
    private TeacherLibraryService teacherLibraryService;
	
	@ApiOperation(value = "环信语音推送", httpMethod = "POST")
	@RequestMapping(value = "/easemobAPNsPush", method = RequestMethod.POST)
	public ResponseEntity easemobAPNsPush(@RequestParam(name = "accessToken") String accessToken,@RequestBody EasemobAPNsRequest request) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			appCommonService.easemobAPNsPush(request);
			responseEntity.success();
		} catch (Exception e) {
			logger.error("环信语音推送异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "好友列表", httpMethod = "POST")
	@RequestMapping(value = "/findFriends", method = RequestMethod.POST)
	public ResponseEntity findFriends(@RequestParam(name = "accessToken") String accessToken) {
		ResponseEntity responseEntity;
		try {
			String userId = tokenManager.getUserId(accessToken);
			responseEntity = appCommonService.findFriends(userId);
		} catch (Exception e) {
			logger.error("好友列表", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "发送消息", httpMethod = "POST")
	@RequestMapping(value = "/onlineSendMessage", method = RequestMethod.POST)
	public ResponseEntity onlineSendMessage(@RequestParam(name = "accessToken") String accessToken,@RequestBody OnlineSendMessageRequest request) {
		ResponseEntity responseEntity;
		try {
			String userId = tokenManager.getUserId(accessToken);
			responseEntity = appCommonService.onlineSendMessage(userId,request);
		} catch (Exception e) {
			logger.error("发送消息", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "聊天消息列表", httpMethod = "POST")
	@RequestMapping(value = "/onlineMessages", method = RequestMethod.POST)
	public ResponseEntity onlineMessages(@RequestParam(name = "accessToken") String accessToken,@RequestBody OnlineMessagesRequest request) {
		ResponseEntity responseEntity;
		try {
			String userId = tokenManager.getUserId(accessToken);
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("sendUserId", userId);
         	params.put("receiveUserId", request.getReceiveUserId());
         	params.put("maxCreateTime", request.getMaxCreateTime());
			Pageable pageable = initPage(request.getPageNo(), request.getPageSize());
			responseEntity = appCommonService.onlineMessages(params,pageable);
		} catch (Exception e) {
			logger.error("聊天消息列表", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "设置聊天消息已读", httpMethod = "POST")
	@RequestMapping(value = "/setMessagesRead", method = RequestMethod.POST)
	public ResponseEntity setMessagesRead(@RequestParam(name = "accessToken") String accessToken,@RequestBody SetMessagesReadRequest request) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = tokenManager.getUserId(accessToken);
			 appCommonService.setMessagesRead(userId,request.getReceiveUserId());
			 responseEntity.success();
		} catch (Exception e) {
			logger.error("设置聊天消息已读", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "未读总消息数", httpMethod = "POST")
	@RequestMapping(value = "/onlineNoReadMessageSum", method = RequestMethod.POST)
	public ResponseEntity onlineNoReadMessageSum(@RequestParam(name = "accessToken") String accessToken) {
		ResponseEntity responseEntity;
		try {
			String userId = tokenManager.getUserId(accessToken);
			responseEntity = appCommonService.onlineNoReadMessageSum(userId);
		} catch (Exception e) {
			logger.error("未读总消息数", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@RequestMapping(value = "/updateXinGeToken", method = RequestMethod.POST)
	@ApiOperation(value = "贝壳登录后，保存信鸽ID", httpMethod = "POST", notes = "小塾上传信鸽Token")
	public ResponseEntity updateXinGeToken(@RequestParam(name = "accessToken") String accessToken,
			@RequestBody UpXinGeRequest request) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			String userId = tokenManager.getUserId(accessToken);
			sconXingeService.saveOrUpdate(userId, request.getXingeToken(), request.getPlatform(), request.getPlatformType());
			responseEntity.success();
		} catch (Exception e) {
			logger.error("小塾上传信鸽Token异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "小塾上传信鸽Token异常");
		}
		return responseEntity;
	}


	@ApiOperation(value = "获取阿里云OSS上传securityToken", httpMethod = "POST")
	@RequestMapping(value = "/getOssfsToken", method = RequestMethod.POST)
	public ResponseEntity getOssfsToken(@RequestParam(name = "accessToken") String accessToken) {
		ResponseEntity responseEntity  =new  ResponseEntity();
		try {
			String userId = tokenManager.getUserId(accessToken);
			Map<String,String>  stsMap= OSSUtils.getSTSSecurityToken();
			stsMap.put("uploadImgPath", DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd")+"/"+
                    IdWorker.generateId()+ ImageTools.SUFF_JPG);

            stsMap.put("bucket",PropertiesUtil.getValue("bucketName"));
          //  stsMap.put("EndPoint","https://oss-cn-shenzhen.aliyuncs.com");

			stsMap.put("endpoint",PropertiesUtil.getValue("img_url"));
            stsMap.put("endpointOSS","https://"+PropertiesUtil.getValue("bucketName")+".oss-cn-shenzhen.aliyuncs.com");
			responseEntity.success(stsMap,"成功");
		} catch (Exception e) {
			logger.error("获取阿里云OSS上传securityToken", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}


	@ApiOperation(value = "获取阿里云OSS上传securityToken，及文件后缀", httpMethod = "POST")
	@RequestMapping(value = "/getOssfsTokenFileExt", method = RequestMethod.POST)
	public ResponseEntity getOssfsToken(@RequestParam(name = "accessToken") String accessToken ,	@RequestBody OssfsTokenReq req) {
		ResponseEntity responseEntity  =new  ResponseEntity();
		try {
			String userId = tokenManager.getUserId(accessToken);
			Map<String,String>  stsMap= OSSUtils.getSTSSecurityToken();
			String preffix = "";
			if (StringUtils.isNotBlank(req.getMiddleDir())){
				preffix  = "/" + req.getMiddleDir();
			}
			stsMap.put("uploadImgPath", preffix + DateHelper.formatDateByFormat(new Date(), "yyyy/MM/dd")+"/"+
                    IdWorker.generateId()+req.getFileExt());


			stsMap.put("bucket",PropertiesUtil.getValue("bucketName"));
			//  stsMap.put("EndPoint","https://oss-cn-shenzhen.aliyuncs.com");

			stsMap.put("endpoint",PropertiesUtil.getValue("img_url"));
			stsMap.put("endpointOSS","https://"+PropertiesUtil.getValue("bucketName")+".oss-cn-shenzhen.aliyuncs.com");
			responseEntity.success(stsMap,"成功");
		} catch (Exception e) {
			logger.error("获取阿里云OSS上传securityToken", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}




	@ApiOperation(value = "from表单图片上传，可上传多张", httpMethod = "POST")
    @IgnoreSecurity
    @RequestMapping(value = "/uploadForm", method = RequestMethod.POST)
    public ResponseEntity uploadForm(@RequestParam(name = "accessToken") String accessToken, 
    		@RequestParam(name = "files") List<MultipartFile> files) throws Exception {
    	ResponseEntity responseEntity = new ResponseEntity();
    	  if (files !=null && files.size() > 0) {
              //文件信息入库
              List<FileInfo> fileInfos = fileInfoService.uploadFilePicture(tokenManager.getUserId(accessToken),files);
              if (files.size() == fileInfos.size()) {
                  Map<String, Object> data = new HashMap<String, Object>();
                  data.put("pics", fileInfos);
                  responseEntity.success(data, "上传图片成功 ");
              } else {
                  responseEntity.failure(ResponseConstant.CODE_000, "上传图片失败");
              }

          } else {
              responseEntity.failure(ResponseConstant.CODE_000, "上传图片失败");
          }
        return responseEntity;
    }
	
	@ApiOperation(value = "常见问题列表", httpMethod = "POST")
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	public ResponseEntity list(@RequestParam(name = "accessToken") String accessToken,@RequestBody (required=true) ProblemListReq req) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			Map<String, Object> params = new HashMap<String, Object>();
	    	if(req.getTitle()!=null &&req.getTitle().trim().length()>0){
	    		params.put("LIKE_title",req.getTitle());
	    	}
	    	if(req.getStat()!=null &&req.getStat()>0){
	    		params.put("EQ_stat",req.getStat());
	    	}
	    	if(req.getType()!=null &&req.getType()>0){
	    		params.put("EQ_type",req.getType());
	    	}
			Pageable pageable = initPage(req.getPageNo(), req.getPageSize(),Direction.ASC, new String[] { "num" });
		    Page<Problem>  pageMap= problemService.findByPage(params, pageable);
		    Map<String, Object> data = new HashMap<String, Object>();
		    data.put("pages", pageMap.getTotalElements());
   		    data.put("list", pageMap.getContent());
   		    data.put("pageSize", req.getPageSize());
   		    data.put("pageNo", req.getPageNo());
			
			responseEntity.success(data,"获取成功");
		} catch (Exception e) {
			e.printStackTrace();
			responseEntity.failure(ResponseConstant.CODE_000, "服务器发生异常，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "下线在线老师", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/offonlineTeacherAllot", method = RequestMethod.POST)
	public ResponseEntity offonlineTeacherAllot(@RequestParam(name = "teacherId") String teacherId) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			//teacherService.offonlineTeacherAllot(teacherId);
			responseEntity.success();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}
	
	@ApiOperation(value = "同步更新年级信息", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/syncRefreshGrade", method = RequestMethod.POST)
	public ResponseEntity syncRefreshGrade() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			//同步更新年级
			appCommonService.syncRefreshGrade();
			responseEntity.success();
		} catch (Exception e) {
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}

	@ApiOperation(value = "获取最新的包列表", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/findLastPackageList", method = RequestMethod.POST)
	public ResponseEntity findLastPackageList() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			List<LastVersionAppInfoDto> appInfos = appInfoService.findLastPackageByTypes(Arrays.asList(2, 5));
			Map<String, Object> data = new HashMap<>();
			data.put("list", appInfos);
			responseEntity.success(data, "请求成功");
		} catch (Exception e) {
			logger.error("异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}

	@ApiOperation(value = "获取最新的包", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/findNewLastPackage", method = RequestMethod.POST)
	public ResponseEntity findNewLastPackage(@RequestParam(name = "type") int type) {
		ResponseEntity responseEntity ;
		try {
			responseEntity=appInfoService.findNewLastNewPackageByType(type);
		} catch (Exception e) {
			logger.error("异常", e);
			 responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}


	@RequestMapping(value = "/upExceptionLog", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "前端日志上传公共接口", httpMethod = "POST", notes = "前端日志上传公共接口")
	public ResponseEntity upExceptionLog(@RequestParam(name = "files") List<MultipartFile> files,
										 @RequestParam(name = "mobileOS") String mobileOS,
										 @RequestParam(name = "platformType") int platformType) {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			//前端日志上传公共接口
			fileInfoService.upExceptionLog(files, mobileOS, platformType);
			responseEntity.success();
		} catch (Exception e) {
			logger.error("前端日志上传公共接口异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "前端日志上传公共接口上传异常");
		}
		return responseEntity;
	}

	@RequestMapping(value = "/getSystemTime", method = RequestMethod.POST)
	@IgnoreSecurity
	@ApiOperation(value = "获取服务器系统时间", httpMethod = "POST", notes = "获取服务器系统时间")
	public ResponseEntity getSystemTime() {
		ResponseEntity responseEntity = new ResponseEntity();
		try {
			Map<String, Object> data = new HashMap<>();
			data.put("systemTime", new Date());
			responseEntity.success(data, "成功");
		} catch (Exception e) {
			logger.error("获取服务器系统时间接口异常", e);
			responseEntity.failure(ResponseConstant.CODE_500, "获取服务器系统时间异常");
		}
		return responseEntity;
	}
	@ApiOperation(value = "获取系统生成小塾号", httpMethod = "POST")
	@IgnoreSecurity
	@RequestMapping(value = "/getSystemDerver", method = RequestMethod.POST)
	public ResponseEntity getSystemDerver(@RequestBody (required=true) ConchSystemDerverReq req ) {
		ResponseEntity responseEntity;
		try {
			responseEntity = conchSystemDerverService.findByImeiAndSimcardAndSimNumbeer(req);
		} catch (Exception e) {
			logger.error("获取系统生成小塾号接口异常", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;
	}

	@ApiOperation(value = "获取小孩的作业服务",httpMethod = "POST")
	@RequestMapping(value = "getChildService",method = RequestMethod.POST)
	public ResponseEntity getChildService(@RequestParam(name = "accessToken") String accessToken, @RequestBody (required=true) VipIdReq req){
		ResponseEntity responseEntity;
		try {
			responseEntity = appCommonService.getChildService(req.getVipId());
		} catch (Exception e) {
			logger.error("获取小孩的作业服务接口异常", e);
			responseEntity = new ResponseEntity();
			responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
		}
		return responseEntity;

	}
}