package com.yizhi.application.sign.controller;

import com.yizhi.core.application.context.ContextHolder;
import com.yizhi.core.application.context.RequestContext;
import com.yizhi.course.application.vo.RangeImportParamVo;
import com.yizhi.sign.application.constant.SignError;
import com.yizhi.sign.application.feign.SignManageClient;
import com.yizhi.sign.application.vo.SignIdVO;
import com.yizhi.sign.application.vo.SignQrcodeVO;
import com.yizhi.sign.application.vo.SignVO;
import com.yizhi.training.application.feign.TrainingProjectClient;
import com.yizhi.util.application.constant.ReturnCode;
import com.yizhi.util.application.domain.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * 签到主体表，入口在培训项目 前端控制器 管理端
 * </p>
 *
 * @author fanchunhui123
 * @since 2018-03-07
 */
@Api(tags = "签到-管理端", description = "签到-管理端")
@RestController
@RequestMapping("/manage/sign")
public class SignManageWebController {

	private static final Logger LOG = LoggerFactory.getLogger(SignManageWebController.class);

	@Autowired
	SignManageClient signManageClient;
	
//	@Autowired
//    SystemMessageClient systemMessageClient;
	
	 @Autowired
	 private TrainingProjectClient trainingProjectClient;
	 
	 @Autowired
	 private SignRecordImport signRecordImport;

	@ApiOperation(value = "新建签到信息", response = Response.class)
	@PostMapping(value = "/insert")
	public Response<Boolean> insert(@ApiParam(value = "签到主体表", required = true) @RequestBody SignVO signVO) {
		try {
	        RequestContext requestContext = ContextHolder.get();
	        if(null == requestContext){
	        	Response.fail();
	        }
	        
	        Long companyId = requestContext.getCompanyId();
	        Long siteId = requestContext.getSiteId();
	        Long orgId = requestContext.getOrgId();
	        Long accountId = requestContext.getAccountId();
	        String accountName = requestContext.getAccountName();
	        signVO.setCompanyId(companyId);
	        signVO.setSiteId(siteId);
	        signVO.setOrgId(orgId);
	        signVO.setAccountId(accountId);
	        signVO.setAccountName(accountName);
	        
	        boolean isOk = false;
			Long singId = signManageClient.insert(signVO);
			if(null != singId){
				//发送提醒信息
				signVO.setId(singId);
//				sendRemind(signVO);
				isOk = true;
			}
			return Response.ok(isOk);
		} catch (Exception e) {
			LOG.error("新建签到失败！", e);
			return Response.fail();
		}
	}

	@ApiOperation(value = "获取签到信息", response = SignVO.class)
	@PostMapping(value = "/view")
	public Response<SignVO> getSign(@ApiParam(value = "培训项目id", required = true) @RequestBody SignIdVO signIdVO) {
		SignVO signVO = null;
		try {
			signVO = signManageClient.getSign(signIdVO);
			return Response.ok(signVO);
		} catch (Exception e) {
			LOG.error("新建签到失败！", e);
			return Response.fail();
		}
	}

	@ApiOperation(value = "修改签到信息")
	@PostMapping("/update")
	public Response<Boolean> update(@ApiParam(value = "签到主体表", required = true) @RequestBody SignVO signVO) {
		try {
			RequestContext requestContext = ContextHolder.get();
	        if(null == requestContext){
	        	Response.fail();
	        }
	        
	        Long companyId = requestContext.getCompanyId();
	        Long siteId = requestContext.getSiteId();
	        Long orgId = requestContext.getOrgId();
	        Long accountId = requestContext.getAccountId();
	        String accountName = requestContext.getAccountName();
	        signVO.setCompanyId(companyId);
	        signVO.setSiteId(siteId);
	        signVO.setOrgId(orgId);
	        signVO.setAccountId(accountId);
	        signVO.setAccountName(accountName);
			boolean result = signManageClient.update(signVO);
			if(result){
				//发送提醒信息
//				sendRemind(signVO);
			}
			return Response.ok(result);
		} catch (Exception e) {
			LOG.error("编辑签到失败！", e);
			return Response.fail();
		}
	}

	@ApiOperation(value = "签到报表")
	@PostMapping("/report")
	public Response<String> report() {
		return Response.ok();
	}

	@ApiOperation(value = "签到报表导出")
	@PostMapping("/report/export")
	public Response<String> reportExport(@ApiParam(value = "培训项目ID", required = true) String trainingProjectId) {
		return Response.ok();
	}

	@ApiOperation(value = "签到删除")
	@PostMapping("/delete")
	public Response<Boolean> deleteByProjectId(@RequestBody SignIdVO signIdVO) {
		RequestContext requestContext = ContextHolder.get();
        if(null == requestContext){
        	Response.fail();
        }
        
        Long companyId = requestContext.getCompanyId();
        Long siteId = requestContext.getSiteId();
        Long orgId = requestContext.getOrgId();
        Long accountId = requestContext.getAccountId();
        String accountName = requestContext.getAccountName();
        signIdVO.setCompanyId(companyId);
        signIdVO.setSiteId(siteId);
        signIdVO.setOrgId(orgId);
        signIdVO.setAccountId(accountId);
        signIdVO.setAccountName(accountName);
        
        boolean isOk = signManageClient.deleteSignByProjectId(signIdVO);
		return Response.ok(isOk);
	}

	@ApiOperation(value = "生成的二维码信息", notes = "生成的二维码信息")
	@PostMapping("/qrcode/get")
	public Response<Object> qrcode(@ApiParam(value = "项目ID", required = true)@RequestBody SignIdVO signIdVO) {
		try {

			Map<String, Object> respMap = new HashMap<String, Object>();

			// 校验培训项目id
			Long trainingProjectId = signIdVO.getId();
			if (null == trainingProjectId) {
				return Response.fail(SignError.SIGN_QRCODE_PARAM_NOT_FOUND, SignError.SIGN_QRCODE_PARAM_NOT_FOUND_MSG);
			}

			// TODO 目前没有项目
			// 查询生成二维码必需参数
			List<SignQrcodeVO> resultList = signManageClient.qrcode(signIdVO);
			if(null == resultList){
				return Response.fail(SignError.SIGN_QRCODE_ERROR, SignError.SIGN_QRCODE_ERROR_MSG);
			}
			
			LOG.info("成功获取生成二维码必需数据");

			respMap.put("type", "sign");
			respMap.put("trainingProjectId", trainingProjectId);
			respMap.put("signTimeIds", resultList);
			return Response.ok(respMap);

		} catch (Exception e) {
			LOG.error("", e);
			return Response.fail(ReturnCode.SERVICE_UNAVAILABLE.getCode(),ReturnCode.SERVICE_UNAVAILABLE.getMsg());
		}

	}
	
//	/**
//	 * 发送提醒信息
//	 * @param signVO
//	 */
//	private void sendRemind(SignVO signVO){
//		//调用提醒服务发送服务
//        try{
//        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        	LOG.info("签到调用提醒服务，开始");
//        	TrainingProject trainingProject = trainingProjectClient.getOne(signVO.getTrainingProjectId());
//        	if(trainingProject == null){
//        		LOG.info("签到调用提醒服务，失败。没获取到项目信息");
//        		return;
//        	}
//
//        	//判断是否设置了提醒（0否 1是）
//        	Integer remindTime = signVO.getRemindTime();
//        	if(remindTime != null && remindTime == 1){
//        		 MessageReceiverVO messageReceiverVO = null;
//                 List<Integer> sendTypes = null;
//                 List<MessageReceiverVO> messageReceiverVOS = null;
//                 MessageVO messageVO = null;
//                 List<SignTimeVO> trExamRemindTimeVoList = signVO.getTrSignTimeVOs();
//                 List<MessageVO> messageVOS = new ArrayList<MessageVO>();
//                 List<TpAuthorizationRange> authorizationRanges = null;
//
//                 //循环发送提醒
//                 Date startDate = null;
//                 Date endDate = null;
//                 String content = null;
//                 String singStartTime = null;
//                 String singEndTime = null;
//                 for (SignTimeVO trExamRemindTimeVO : trExamRemindTimeVoList) {
//                	 sendTypes = new ArrayList<Integer>();
//                     messageVO = new MessageVO();
//                     messageVO.setSubject(trainingProject.getName());             //消息标题
//                     messageVO.setMessageType(Integer.valueOf(MessageType.QD.getKey())); //消息类型(0自定义消息1学习计划2考试3调研4投票5报名6作业7签到8项目)
//                     messageVO.setTaskId(signVO.getId());                                    //关联业务id,自定义消息为0
//                     int type = remindTime;
//
//
//                     // 拼接签到开始时间
//                     String sTime = trExamRemindTimeVO.getStartTime();
//                     String sHour = trExamRemindTimeVO.getStartHour();
//                     String sMinute = trExamRemindTimeVO.getStartMinute();
//                     singStartTime = sTime + " " + sHour + ":" + sMinute;
//                     startDate = sdf.parse(singStartTime + ":00");
//
//                     // 拼接签到结束时间
//                     // 判断是否是按时间段生成多张二维码
//                     if (signVO.getType() == 0) {
//                    	 sTime = trExamRemindTimeVO.getEndTime();
//                     }
//                     sHour = trExamRemindTimeVO.getEndHour();
//                     sMinute = trExamRemindTimeVO.getEndMinute();
//                     singEndTime = sTime + " " + sHour + ":" + sMinute;
//                     endDate = sdf.parse(singEndTime + ":00");
//
//                     //消息内容
//                     content = signVO.getRemindContent();
//                     content = replaceContent(content, singStartTime + " - " + singEndTime);
//                     messageVO.setContext(content);
//
//                     //1开始前发送  2结束前发送  3自定义时间  (发生时间)
//                     messageVO.setAheadType(remindTime);
//                     if(type == 1){
//                         messageVO.setHappenTime(startDate);
//                     }else if(type == 2){
//                         messageVO.setHappenTime(endDate);
//                     }
//
//                     Integer visibleRange = trainingProject.getVisibleRange();	//获取项目可见范围
//                     //1全平台可见 2指定用户可见
//                     if(visibleRange == 1){
//                         messageVO.setVisibleRange(Integer.valueOf(VisibleRange.ALL.getKey()));
//                     }else if(visibleRange == 2){
//                    	 authorizationRanges = trainingProjectClient.VisibleRange(signVO.getTrainingProjectId());
//                         if (!CollectionUtils.isEmpty(authorizationRanges)) {
//                             messageReceiverVOS = new ArrayList<>();
//                             for (TpAuthorizationRange range : authorizationRanges) {
//                                 messageReceiverVO = new MessageReceiverVO();
//                                 messageReceiverVO.setType(range.getType());
//                                 messageReceiverVO.setReceiverId(range.getRelationId());
//                                 messageReceiverVOS.add(messageReceiverVO);
//                             }
//                             messageVO.setReceiverVOs(messageReceiverVOS);
//                         }
//                     }
//
//                     //添加提醒消息类型
//                     if(signVO.getEnableRemindMail() == 1){
//                    	 sendTypes.add(Integer.parseInt(SendType.MAIL.getCode()));
//                     }
//                     if(signVO.getEnableRemindNote() == 1){
//                    	 sendTypes.add(Integer.parseInt(SendType.INSITE.getCode()));
//                     }
//
//                     messageVOS.add(messageVO);
//                 }
//
//                 systemMessageClient.add(messageVOS);
//                 LOG.info("签到调用提醒服务，成功");
//        	} else {
//        		//删除提醒服务的内容
//        	}
//        } catch(Exception e){
//        	LOG.info("签到调用提醒服务，失败");
//        	e.printStackTrace();
//        }
//	}
	
	/**
     * 提醒关键字替换
     * @param value
     * @param singTime
     * @return
     */
    private String replaceContent(String value, String singTime){
    	if(!StringUtils.isBlank(value)){
    		value = value.replace("{签到时间}", singTime);
        }
    	return value;
    }
    
    @ApiOperation(value = "导入线下签到", notes = "导入线下签到")
    @PostMapping("/signRecord/import")
    public Response<String> importSignRecord(@RequestBody RangeImportParamVo importParam) {
        Map<String, Object> map = new HashMap<>();
        RequestContext res = ContextHolder.get();
        Date date = new Date();
        Long taskId = date.getTime();
        String serialNo = "EXPERIENCE-IMPORT-" + taskId.toString();
        String taskName = "线下签到导入-" + taskId.toString();
        String url = importParam.getOssUrl();
        Long signId = importParam.getBizdId();
        map.put("taskId", taskId);
        map.put("taskName", taskName);
        map.put("serialNo", serialNo);
        map.put("res", res);
        map.put("url", url);
        map.put("signId", signId);
        signRecordImport.execute(map, true);
        return Response.ok(serialNo);
    }

}
