package com.bcxin.survey.service.wechat;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.bcxin.survey.communicate.sb.SBRspService;
import com.bcxin.survey.dao.report.BaseDao;
import com.bcxin.survey.dao.report.MaterialTaskDao;
import com.bcxin.survey.dao.report.TaskDao;
import com.bcxin.survey.domain.activity.Activity;
import com.bcxin.survey.domain.activity.Message;
import com.bcxin.survey.domain.data.MaterialTask;
import com.bcxin.survey.domain.data.SyncTask;
import com.bcxin.survey.domain.dynamic.DynamicTemplateConst;
import com.bcxin.survey.domain.report.Task;
import com.bcxin.survey.domain.security.Org;
import com.bcxin.survey.domain.security.User;
import com.bcxin.survey.domain.survey.*;
import com.bcxin.survey.domain.wechat.AccessToken;
import com.bcxin.survey.dto.SBDataDTO;
import com.bcxin.survey.enums.expert.ExpertTaskStatusEnum;
import com.bcxin.survey.enums.expert.ExpertTaskTypeEnum;
import com.bcxin.survey.enums.report.*;
import com.bcxin.survey.service.CommonService;
import com.bcxin.survey.service.ExpertOrderPublicService;
import com.bcxin.survey.service.NotifyService;
import com.bcxin.survey.service.UserService;
import com.bcxin.survey.service.log.SysLogService;
import com.bcxin.survey.service.report.ActivityService;
import com.bcxin.survey.utils.*;
import com.bcxin.survey.utils.sms.SMSUtil;
import com.bcxin.survey.vo.EmailModel;
import com.bcxin.survey.vo.MessageModel;
import com.bcxin.survey.wechat.utils.WeixinUtil;
import com.google.common.io.Files;
import net.sf.json.JSONObject;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
@Transactional
public class SurveyFeedBackServiceImpl implements SurveyFeedBackService {

	@Resource
	private BaseDao baseDao;
	
	@Resource
	private SurveyTaskService surveyTaskService;
	
	@Resource
	private SurveyInfoService surveyInfoService;

	@Resource
	private SurveyQuestionnaireService surveyQuestionnaireService;
	
	@Resource
	private SurveyPhotoService surveyPhotoService;
	
	@Resource
	private AccessTokenService accessTokenService;
	
	@Resource
	private SurveyPlanService surveyPlanService;
	
	@Resource
	private ActivityService activityService;

	@Resource
	private SBRspService sbRspService;

	@Resource
	private CommonService commonService;

	@Resource
	private SurveyManagerUtil surveyManagerUtil;

	@Resource
	private UserService userService;

	@Resource
	private TaskDao taskDao;

	@Resource
	private MaterialTaskDao materialTaskDao;
	@Autowired
	private SysLogService sysLogService;

	@Resource
	private NotifyService notifyService;

	@Autowired
	private ReportUtil reportUtil;
	@Autowired
	private ExpertOrderPublicService orderPublicService;

	/**
	 * 组装文件内容时，键值对的连接符
	 */
	private final static String V_CONNECT = "_v_";

	/**
	 * 同步勘查文件夹名称
	 */
	private final static String TK_FOLDER = "tk";

	/**
	 * 同步勘查文件，文件标识
	 */
	private final static String ST = "_st_";

	/**
	 * 同步勘查图片，文件标识
	 */
	private final static String SP = "_sp_";

	/**
	 * 同步勘查报告，文件标识
	 */
	private final static String SR = "_sr_";

	/**
	 * 文件加时间戳的连接符
	 */
	private final static String TI = "_t_";

	@Override
	public boolean saveOrUpdate(Survey_FeedBack feedBack){
		boolean flag = true;
		try {
			feedBack.setUpdateOn(new Date());
			baseDao.saveOrUpdate(feedBack);		
		}catch(Exception e) {
			flag = false;
		}
		return flag;
	}

	@Override
	public boolean delete(Survey_FeedBack feedBack) {
		boolean flag = true;
		try {
			baseDao.delete(feedBack);		
		}catch(Exception e) {
			flag = false;
		}
		return flag;
	}

	@Override
	public Survey_FeedBack findSurveyFeedBackByOid(long oid){
		return baseDao.get(Survey_FeedBack.class, oid);
	}
	
	@Override
	public List<Survey_FeedBack> findSurvey_FeedBackByTaskId(long taskId){
		List<Criterion> criterionList = new ArrayList<Criterion>();
		criterionList.add(Restrictions.eq("surveyTask.oid", taskId));
		List<Order> orderList = new ArrayList<Order>();
		orderList.add(Order.asc("surveyTask.oid"));
		orderList.add(Order.asc("surveyStep"));
		return baseDao.findByCriterion(Survey_FeedBack.class, criterionList,orderList);
		
	}

	@Override
	public List<Survey_FeedBack> findSurvey_FeedBackListBySurveyTaskId(long taskId) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		criterionList.add(Restrictions.eq("surveyTask.oid", taskId));	
		List<Order> orderList = new ArrayList<Order>();
		orderList.add(Order.asc("surveyStep"));
		return baseDao.findByCriterion(Survey_FeedBack.class, criterionList, orderList);
	}

	@Override
	public Survey_FeedBack findSurveyFeedBackByTaskAndStep(SurveyTask task, SurveyStep surveyStep){
		List<Criterion> criterionList = new ArrayList<Criterion>();
		criterionList.add(Restrictions.eq("surveyTask.oid", task.getOid()));
		criterionList.add(Restrictions.eq("surveyStep", surveyStep));
		List<Survey_FeedBack> list = baseDao.findByCriterion(Survey_FeedBack.class, criterionList);
		if(list != null && list.size() > 0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	public JSONObject createQuestion(User user, long questionnaireId,HttpServletRequest request) {
		JSONObject json = new JSONObject();
		String message = "";
		String status = "300";
		long sort=1;
		Survey_Questionnaire questionnaire = surveyQuestionnaireService.findQuestionnaireByOid(questionnaireId);
		List<Survey_Info> oldQuestionList = questionnaire.getSurveyInfos();
		Activity activity = questionnaire.getFeedBack().getSurveyTask().getActivity();
		String addressType = "";
		String activityType = "";
		if (activity != null) {
			addressType = activity.getAddressType();
		}
		if (activity != null) {
			activityType = activity.getActivityType();
		}
		List<Survey_Info> surveyInfoList= surveyInfoService.getSurveyInfoFormCMSForFix(questionnaire.getSurveyStep(),activityType,addressType);
		
		//遗留问题
		String[] questionIds = request.getParameterValues("nextSurveys");
		
		List<String> lastSurveyIds = new ArrayList<String>();
		if(questionIds!= null && questionIds.length > 0) {
			lastSurveyIds = new ArrayList<String>(Arrays.asList(questionIds));
		}
		for(Survey_Info info:oldQuestionList){
			if(surveyInfoList != null && surveyInfoList.size() >0){
				if(info.getQuestionType().equals(QuestionType.FIXED)){
					boolean include= false;
					for(Survey_Info surveyInfo:surveyInfoList){
						if(info.getAid().equals(surveyInfo.getAid())){
							include = true;
							surveyInfo.setExistence(true);
							break;
						}
					}
					if(!include) {
						surveyInfoService.delete(info);//删除不存在的原来固定勘查问题
					}
				}
			}
			if (lastSurveyIds != null && lastSurveyIds.size() >0) {
				if (info.getQuestionType().equals(QuestionType.CARRYOVER)) {
					boolean include = false;
					for (String lastSurveyId : lastSurveyIds) {
						if (info.getLastSurveyInfoId().equals(lastSurveyId)) {
							lastSurveyIds.remove(lastSurveyId);
							include = true;
							break;
						}
					}
					if (!include) {
						surveyInfoService.delete(info);//删除不存在的遗留勘查问题
					}
				}
			}
		}
		
		//添加固定勘查问题
		if(surveyInfoList != null && surveyInfoList.size() >0) {
			for (Survey_Info surveyInfo : surveyInfoList) {
				if (surveyInfo.isExistence() == false) {
					surveyInfo.setNextSurvey(false);
					surveyInfo.setQuestionnaire(questionnaire);
					surveyInfoService.saveOrUpdate(surveyInfo);
				}
				sort = surveyInfo.getSort();
			}
		}
		
		/*添加遗留问题begin*/
		if(lastSurveyIds != null && lastSurveyIds.size() >0) {
			for (String lastSurveyId : lastSurveyIds) {
				Survey_Info surveyInfo = surveyInfoService.findSurveyInfoByOid(Long.parseLong(lastSurveyId));
				if (surveyInfo == null) {
					continue;
				}
				Survey_Info newInfo = new Survey_Info();
				newInfo.setCreateOn(new Date());
				newInfo.setQuestionnaire(questionnaire);
				newInfo.setQuestion(surveyInfo.getQuestion());

				newInfo.setQuestionType(QuestionType.CARRYOVER);
				newInfo.setNextSurvey(false);
				newInfo.setSort(++sort);
				newInfo.setLastSurveyInfoId(lastSurveyId);
				newInfo.setSurveyStep(questionnaire.getSurveyStep());

				if (StringUtil.isNotEmpty(surveyInfo.getAid())) {
					newInfo.setAid(surveyInfo.getAid());
				}
				if (StringUtil.isNotEmpty(surveyInfo.getAnswer())) {
					newInfo.setAnswer(StringUtil.deleteAllCRLF(surveyInfo.getAnswer()));
				}
				if (StringUtil.isNotEmpty(surveyInfo.getAnswerTip())) {
					newInfo.setAnswerTip(surveyInfo.getAnswerTip());
				}
				surveyInfoService.saveOrUpdate(newInfo);
			}

		}
		/*添加遗留问题end*/
		
		/*重新排序begin*/
		for (Survey_Info survey_Info : oldQuestionList) {
			if(survey_Info.getQuestionType().equals(QuestionType.UNFIXED) || survey_Info.getQuestionType().equals(QuestionType.SUPPLEMENT)){
				survey_Info.setSort(++sort);
				surveyInfoService.saveOrUpdate(survey_Info);
			}
		}
		/*重新排序end*/
		
		String[] questions = request.getParameterValues("questions");
		if(questions != null && questions.length >0){
			for (String question : questions){
				if(StringUtil.isNotEmpty(question)){
					Survey_Info surveyQuestion = surveyInfoService.findSurveyInfoByquestionnaireIdAndQuestion(questionnaire.getOid(),question);
					if(surveyQuestion == null)	{
						surveyQuestion = new Survey_Info();
						surveyQuestion.setCreateOn(new Date());
						surveyQuestion.setQuestion(question);
						surveyQuestion.setQuestionType(QuestionType.SUPPLEMENT);
						surveyQuestion.setQuestionnaire(questionnaire);
						surveyQuestion.setNextSurvey(false);
						surveyQuestion.setSort(++sort);
						surveyInfoService.saveOrUpdate(surveyQuestion);
					}
				}
			}
		}
		questionnaire.setGenerate(true);
		
		message = "保存成功！";
		status="200";
		json.put("message", message);
		json.put("status", status);
		json.put("questionnaireId", questionnaire.getOid());
		return json;
	}


	@Override
	public JSONObject finishSurveyNew(HttpServletRequest request){
		JSONObject json = new JSONObject();
		String surveyReport="";
		// 计划id
		String planId = request.getParameter("planId");
		//勘查人员签名
		String signImgPath = request.getParameter("signImgPath");
		//承办方签名
		String purveyorSignPath = request.getParameter("purveyorSignPath");

		if(StringUtil.isEmpty(planId)){
			json.put("message", "提交失败，请刷新重试！");
			json.put("status", "300");
			sysLogService.saveLog(this.getClass().getName()+".finishSurveyNew","planId为空",true);
			return json;
		}

		if(StringUtil.isEmpty(signImgPath) || StringUtil.isEmpty(purveyorSignPath)){
			json.put("message", "请确认签名！");
			json.put("status", "300");
			return json;
		}

		System.out.println("========> finishSurveyNew.步骤：1-------------");
		// 修改勘查计划状态并设置签名路径
		SurveyPlan surveyPlan = surveyPlanService.findSurveyPlanByOid(Long.parseLong(planId));
		Survey_FeedBack surveyFeedBack = findSurveyFeedBackByOid(surveyPlan.getFeedBack().getOid());
		Survey_Questionnaire questionnaire = surveyPlan.getQuestionnaire();
		surveyPlan.setTaskStatus(PlanStatusEnum.COMPLETE);
		String feedBackPath= surveyFeedBack.getOid() +"/"+questionnaire.getOid();
		signImgPath = generateImage(signImgPath,feedBackPath,request);
		surveyPlan.setSignImgPath(signImgPath);
		surveyPlan.setPurveyorSignPath(generateImage(purveyorSignPath,feedBackPath,request));
		// 1.生成勘查报告,并保存到问卷
		surveyReport = reportUtil.createSurveyReport1(questionnaire);
		if(StringUtil.isEmpty(surveyReport)){
			json.put("message", "勘查报告生成失败");
			json.put("status", "300");
			return json;
		}
		questionnaire.setReportPath(surveyReport);
		surveyQuestionnaireService.saveOrUpdate(questionnaire);

		// 2.修改勘查计划状态并设置签名路径
		if(!surveyPlanService.saveOrUpdate(surveyPlan)) {
			json.put("message", "提交失败");
			json.put("status", "300");
			return json;
		}

		// 3.修改踏勘计划状态，修改踏勘任务状态
		Activity activity = surveyFeedBack.getSurveyTask().getActivity();
		// 该问卷下的所有计划都完成了
		if(validFinishQuestionnaire(questionnaire.getOid())){
			// 设置问卷状态为已完成
			questionnaire.setTaskStatus(QuestionStatusEnum.COMPLETE);

			if(validFinishFeeBack(surveyPlan.getSurveyStep(),surveyFeedBack)){
				// 更新反馈状态为已经完成
				surveyFeedBack.setTaskStatus(FeedBackStatusEnum.COMPLETE);
				saveOrUpdate(surveyFeedBack);

				String activitySubStep = "";
				String activityMaterialType = "";
				if (SurveyStep.FIRST.equals(surveyFeedBack.getSurveyStep())) {
					activitySubStep = DictConst.ACTIVITYSUBSTEP_DYJDTKYWC;
					activityMaterialType = DictConst.ACTIVITYMATERIALTYPE_DYJDTKBG;
				} else if (SurveyStep.SECOND.equals(surveyFeedBack.getSurveyStep())) {
					activitySubStep = DictConst.ACTIVITYSUBSTEP_DRJDTKYWC;
					activityMaterialType = DictConst.ACTIVITYMATERIALTYPE_DEJDTKBG;
				} else if (SurveyStep.THIRD.equals(surveyFeedBack.getSurveyStep())) {
					activitySubStep = DictConst.ACTIVITYSUBSTEP_DSJDTKYWC;
					activityMaterialType = DictConst.ACTIVITYMATERIALTYPE_DSJDTKBG;
				}

				// 验证踏勘任务是否结束
				if(validFinishSurveyTask(surveyPlan)){
					SurveyTask task = surveyPlan.getSurveyTask();
					task.setSurveyTaskStatus(SurveyTaskStatus.DONE);
					surveyTaskService.saveOrUpdate(task);

					// 修改任务状态为已经完成
					Task riskTask=task.getTask();
					riskTask.setTaskStatus(TaskStatus.FINISH.getKey());
					riskTask.setFinishDate(new Date());
					taskDao.saveOrUpdate(riskTask);

					// 更新专家订单
					orderPublicService.updateStatus(activity.getOid(),riskTask.getAssgin().getOid(),
							ExpertTaskTypeEnum.SURVEY.getKey(),ExpertTaskStatusEnum.FINISH.getKey());
				}

				activityService.dateRecord(surveyFeedBack.getSurveyTask().getActivity(),activitySubStep,surveyFeedBack.getOid().toString());
				//将勘查报告保存到activityMaterial表中
				activityService.activityMaterial(activityMaterialType,surveyReport,activity);
			}
		}else{
			// 未完成
			questionnaire.setTaskStatus(QuestionStatusEnum.CONTINUE);
			surveyQuestionnaireService.saveOrUpdate(questionnaire);
		}

		// 4.同步勘查报告到子站
		MaterialTask materialTask = commonService.mtInstance(activity.getActivityNo(),null,DictConst.MATERIALTASK_TKXQ);
		syncSurvey(activity,surveyPlan,materialTask);

		// 5.发送通知
		sendNotify(surveyPlan,surveyReport,activity);

		// 记录生成成功日志
		sysLogService.saveLog(this.getClass().getName()+".finishSurveyNew","提交踏勘成功，planId="+planId,false);
		json.put("message", "提交成功");
		json.put("status", "200");
		return json;
	}


	/**
	 * 发送通知给勘查项目经理和勘查区域经理+动态看板
	 * @param surveyPlan
	 */
	private void sendNotify(SurveyPlan surveyPlan,String surveyReport, Activity activity){
		//发送通知给勘查项目经理和勘查区域经理

		Survey_Questionnaire questionnaire = surveyPlan.getQuestionnaire();
		//获取第几阶段
		String step = "";
		if (surveyPlan.getSurveyStep().equals(SurveyStep.FIRST)) {
			step = SurveyStep.FIRST.getName();
		} else if (surveyPlan.getSurveyStep().equals(SurveyStep.SECOND)) {
			step = SurveyStep.SECOND.getName();
		} else if (surveyPlan.getSurveyStep().equals(SurveyStep.THIRD)) {
			step = SurveyStep.THIRD.getName();
		}

		SurveyTask surveyTask = surveyPlan.getSurveyTask();
		if (surveyTask != null) {

			Task task = surveyManagerUtil.selectTaskBySurveyTask(surveyTask);
			User user = userService.getCurrentUser();

			if (activity != null) {

				activity = activityService.findActivityByOid(activity.getOid());

				//活动承办方
				User activityUser = activity.getUser();

				//通知承办方
				if (activityUser != null) {
					//手机短信通知
					String content = user.getRealName() + "已完成活动" + activity.getName() + "的" + step + "任务，请及时反馈整改情况。";
					notifyService.sendHuaWeiSMS(activityUser.getPhone(),content, Const.ENVI_TK, DictConst.SMSCODE_B08,new String[]{user.getRealName(),activity.getName()});

					//邮件通知
					EmailModel model = new EmailModel();
					model.setSubject("" + activity.getName() + "的" + step + "任务已完成");
					model.setEmailType(EmailMsgType.SURVEYTASK);
					model.setContent(user.getRealName() + "已完成活动" + activity.getName() + "的" + step + "任务，请及时反馈整改情况。【" + SMSUtil.platFormName() + "】");
					model.setTo(activityUser.getEmail());
					notifyService.sendEmail(model);

					//消息通知
					Message msg = new Message();
					msg.setUser_id(activityUser.getOid());
					msg.setReadStatus("0");
					msg.setContent(user.getRealName() + "已完成活动" + activity.getName() + "的" + step + "任务，请及时反馈整改情况。");
					msg.setTitle("" + activity.getName() + "的" + step + "任务已完成");
					msg.setKeyword("立即查看");
					msg.setCreateOn(new Date());
					msg.setUrl("/survey/task/detail/" + task.getOid());
					baseDao.saveOrUpdate(msg);
				}

				//查询服务机构多类人员信息
				List<String> userTypeList = new ArrayList<>();
				userTypeList.add(DictConst.USERTYPE_DSFFWJGYH_ZG);
				userTypeList.add(DictConst.USERTYPE_DSFFWJGYH_TKXMJL);
				userTypeList.add(DictConst.USERTYPE_DSFFWJGYH_TKQYJL);

				// 共享专家没有org，需要通过活动获取风评机构id
				Org org=commonService.getOrg(activity);
				List<User> serviceOrgPersonList = userService.selectServiceOrgPersonByList(userTypeList, org.getOid());

				//查询服务机构注册人员信息
				User serviceOrgRegister = userService.selectServiceOrgRegister(org);

				serviceOrgPersonList.add(serviceOrgRegister);


				//风评机构/机构主管/勘查项目经理/勘查区域经理 消息通知
				for (User user1 : serviceOrgPersonList) {

					//手机短信通知
					String content = user.getRealName() + "已完成活动" + activity.getName() + "的" + step + "任务。";
					notifyService.sendHuaWeiSMS(user1.getPhone(),content, Const.ENVI_TK, DictConst.SMSCODE_B08,new String[]{user.getRealName(),activity.getName()});

					//邮件通知
					EmailModel model = new EmailModel();
					model.setSubject("" + activity.getName() + "的" + step + "任务已完成");
					model.setEmailType(EmailMsgType.SURVEYTASK);
					model.setContent(user.getRealName() + "已完成活动" + activity.getName() + "的" + step + "任务。【" + SMSUtil.platFormName() + "】");
					model.setTo(user1.getEmail());
					notifyService.sendEmail(model);

					//消息通知
					Message msg = new Message();
					msg.setUser_id(user1.getOid());
					msg.setReadStatus("0");
					msg.setContent(user.getRealName() + "已完成活动" + activity.getName() + "的" + step + "任务。");
					msg.setTitle("" + activity.getName() + "的" + step + "任务已完成");
					msg.setKeyword("立即查看");
					msg.setCreateOn(new Date());
					msg.setUrl("/survey/task/detail/" + task.getOid());
					baseDao.saveOrUpdate(msg);
				}
			}
			if (user != null && activity != null) {
				// 保存踏勘报告到动态看板
				DynamicUtil.getBean().saveTKReportData(user,DynamicTemplateConst.DYNAMIC_TEMP_KANCHA_400011,activity,step,surveyReport,questionnaire.getOid());
			}
		}
	}

	/**
	 * 验证该问卷的踏勘计划是否全部完成
	 * @param questionnaireId
	 * @return
	 */
	private boolean validFinishQuestionnaire(Long questionnaireId){
		boolean flag=true;
		List<SurveyPlan> surveyPlans = surveyPlanService.findSurveyPlanListByQuestionnaireId(questionnaireId);
		for(SurveyPlan plan : surveyPlans){
			if(!plan.getTaskStatus().equals(PlanStatusEnum.COMPLETE)){
				flag = false;
				break;
			}
		}
		return flag;
	}

	/**
	 * 验证整改活动的踏勘是否结束
	 * @param currentStep
	 * @param surveyFeedBack
	 * @return
	 */
	private boolean validFinishFeeBack(SurveyStep currentStep,Survey_FeedBack surveyFeedBack){
		boolean flag=true;
		List<SurveyPlan> surveyPlans = surveyPlanService.findSurveyPlanListByFeedBackId(surveyFeedBack.getOid());
		for(SurveyPlan plan : surveyPlans){
			if(!plan.getTaskStatus().equals(PlanStatusEnum.COMPLETE)){
				flag = false;
				break;
			}
		}
		if(currentStep.equals(SurveyStep.THIRD)){
			List<Survey_Questionnaire> questionnaires = surveyFeedBack.getQuestionnaires();
			for (Survey_Questionnaire survey_Questionnaire : questionnaires) {
				if(survey_Questionnaire.getTaskStatus().equals(QuestionStatusEnum.CONTINUE) || survey_Questionnaire.getTaskStatus().equals(QuestionStatusEnum.NON)){
					flag = false;
					break;
				}
			}
		}
		return flag;
	}

	/**
	 * 验证勘查任务是否结束
	 * @param surveyPlan
	 * @return
	 */
	public boolean validFinishSurveyTask(SurveyPlan surveyPlan){
		boolean flag=true;
		SurveyTask task = surveyPlan.getSurveyTask();
		for(Survey_FeedBack feedBack:task.getFeedBacks()){
			if(!feedBack.getTaskStatus().equals(FeedBackStatusEnum.COMPLETE)){
				flag = false;
				break;
			}
		}
		return flag;
	}

	/**
	 * 提价勘查结果，并生成勘查报告
	 * @param request
	 * @return
	 */
	@Override
	public JSONObject finishSurvey(HttpServletRequest request){
		JSONObject json = new JSONObject();
		String message = "";
		String status ="300";
		// 踏勘报告
		String surveyReport="";
		String planId = request.getParameter("planId");
		if(StringUtil.isNotEmpty(planId)){
			SurveyPlan surveyPlan = surveyPlanService.findSurveyPlanByOid(Long.parseLong(planId));
			Survey_FeedBack surveyFeedBack = findSurveyFeedBackByOid(surveyPlan.getFeedBack().getOid());
			Survey_Questionnaire questionnaire = surveyPlan.getQuestionnaire();
			//勘查人员签名
			String signImgPath = request.getParameter("signImgPath");
			//承办方签名
			String purveyorSignPath = request.getParameter("purveyorSignPath");
			if(StringUtil.isNotEmpty(signImgPath) && StringUtil.isNotEmpty(purveyorSignPath)){
				surveyPlan.setTaskStatus(PlanStatusEnum.COMPLETE);
				String feedBackPath= surveyFeedBack.getOid() +"/"+questionnaire.getOid();
				signImgPath = generateImage(signImgPath,feedBackPath,request);
				surveyPlan.setSignImgPath(signImgPath);
				surveyPlan.setPurveyorSignPath(generateImage(purveyorSignPath,feedBackPath,request));
				if(surveyPlanService.saveOrUpdate(surveyPlan)){
					message = "提交成功！";
					status="200";

					Activity activity = surveyFeedBack.getSurveyTask().getActivity();

					/* 踏勘报告任务 */
					MaterialTask materialTask1 = commonService.mtInstance(activity.getActivityNo(),questionnaire.getOid().toString(),DictConst.MATERIALTASK_TKBG);

					/* 生成踏勘报告 */
					surveyReport = surveyQuestionnaireService.createSurveyReport(questionnaire,materialTask1);

					MaterialTask materialTask2 = commonService.mtInstance(activity.getActivityNo(),surveyPlan.getOid().toString(),DictConst.MATERIALTASK_TKXQ);


                    syncSurvey(activity,surveyPlan,materialTask2);
					boolean finishSurvey_Questionnaire = true;
					
					List<Survey_Questionnaire> questionnaires = null;
					List<SurveyPlan> surveyPlans = surveyPlanService.findSurveyPlanListByQuestionnaireId(questionnaire.getOid());
					for(SurveyPlan plan : surveyPlans){
						if(!plan.getTaskStatus().equals(PlanStatusEnum.COMPLETE)){
							finishSurvey_Questionnaire = false;
							break;
						}
					}
					if(finishSurvey_Questionnaire){
						questionnaire.setTaskStatus(QuestionStatusEnum.COMPLETE);
						String activitySubStep = "";
						String activityMaterialType = "";

						boolean finishSurvey_FeedBack= true;
						surveyPlans = surveyPlanService.findSurveyPlanListByFeedBackId(surveyFeedBack.getOid());
						for(SurveyPlan plan : surveyPlans){
							if(!plan.getTaskStatus().equals(PlanStatusEnum.COMPLETE)){
								finishSurvey_FeedBack = false;
								break;
							}
						}
						if(surveyPlan.getSurveyStep().equals(SurveyStep.THIRD)){
							questionnaires = surveyFeedBack.getQuestionnaires();
							for (Survey_Questionnaire survey_Questionnaire : questionnaires) {
								if(survey_Questionnaire.getTaskStatus().equals(QuestionStatusEnum.CONTINUE) || survey_Questionnaire.getTaskStatus().equals(QuestionStatusEnum.NON)){
									finishSurvey_FeedBack = false;
									break;
								}
							}
						}
						if(finishSurvey_FeedBack){
							surveyFeedBack.setTaskStatus(FeedBackStatusEnum.COMPLETE);
							saveOrUpdate(surveyFeedBack);
							
							if (SurveyStep.FIRST.equals(surveyFeedBack.getSurveyStep())) {
								activitySubStep = DictConst.ACTIVITYSUBSTEP_DYJDTKYWC;
								activityMaterialType = DictConst.ACTIVITYMATERIALTYPE_DYJDTKBG;
							} else if (SurveyStep.SECOND.equals(surveyFeedBack.getSurveyStep())) {
								activitySubStep = DictConst.ACTIVITYSUBSTEP_DRJDTKYWC;
								activityMaterialType = DictConst.ACTIVITYMATERIALTYPE_DEJDTKBG;
							} else if (SurveyStep.THIRD.equals(surveyFeedBack.getSurveyStep())) {
								activitySubStep = DictConst.ACTIVITYSUBSTEP_DSJDTKYWC;
								activityMaterialType = DictConst.ACTIVITYMATERIALTYPE_DSJDTKBG;
							}
							activityService.dateRecord(surveyFeedBack.getSurveyTask().getActivity(),activitySubStep,surveyFeedBack.getOid().toString());
							//将勘查报告保存到activityMaterial表中
							String reportPath = questionnaire.getReportPath();
							activityService.activityMaterial(activityMaterialType,reportPath,activity);

							status="200";
							boolean finishTask = true;
							SurveyTask task = surveyPlan.getSurveyTask();
							for(Survey_FeedBack feedBack:task.getFeedBacks()){
								if(!feedBack.getTaskStatus().equals(FeedBackStatusEnum.COMPLETE)){
									finishTask = false;
									break;
								}
							}
							if(finishTask){
								task.setSurveyTaskStatus(SurveyTaskStatus.DONE);
								surveyTaskService.saveOrUpdate(task);

								// 修改任务状态为已经完成
								Task riskTask=task.getTask();
								riskTask.setTaskStatus(TaskStatus.FINISH.getKey());
								riskTask.setFinishDate(new Date());
								taskDao.saveOrUpdate(riskTask);

								// 更新专家订单
								orderPublicService.updateStatus(activity.getOid(),riskTask.getAssgin().getOid(),
										ExpertTaskTypeEnum.SURVEY.getKey(),ExpertTaskStatusEnum.FINISH.getKey());
							}
						}
						
					} else {
						questionnaire.setTaskStatus(QuestionStatusEnum.CONTINUE);
						surveyQuestionnaireService.saveOrUpdate(questionnaire);
					}

					//发送通知给勘查项目经理和勘查区域经理

					//获取第几阶段
					String step = "";
					if (surveyPlan.getSurveyStep().equals(SurveyStep.FIRST)) {
						step = SurveyStep.FIRST.getName();
					} else if (surveyPlan.getSurveyStep().equals(SurveyStep.SECOND)) {
						step = SurveyStep.SECOND.getName();
					} else if (surveyPlan.getSurveyStep().equals(SurveyStep.THIRD)) {
						step = SurveyStep.THIRD.getName();
					}

					SurveyTask surveyTask = surveyPlan.getSurveyTask();
					if (surveyTask != null) {

						Task task = surveyManagerUtil.selectTaskBySurveyTask(surveyTask);
						User user = userService.getCurrentUser();

						if (user != null && activity != null && task != null) {
							Message msg = new Message();
							msg.setContent(user.getRealName() + "已完成" + activity.getName() + "" + step + "任务。");
							msg.setTitle("" + activity.getName() + "已完成" + step + "任务。");
							msg.setKeyword("立即查看");
							msg.setUrl("/survey/task/detail/" + task.getOid());
							surveyManagerUtil.saveMessage(surveyTask, msg);

							// 保存踏勘报告到动态看板
							DynamicUtil.getBean().saveTKReportData(user,DynamicTemplateConst.DYNAMIC_TEMP_KANCHA_400011,activity,step,surveyReport,questionnaire.getOid());
						}
					}

				} else {
					message = "提交失败！";
					status="300";
				}
			} else {
				message = "请确认签名！";
				status="300";
			}
			
		} else {
			message ="提交失败，请刷新重试！";
			sysLogService.saveLog(this.getClass().getName()+".finishSurvey","planId为空",true);
		}
		json.put("message", message);
		json.put("status", status);
		return json;
	}


	private Object safeTransfor(Object obj){
        if ( obj == null ) {
            return "无";
        }
        return obj;
    }
	
	@Override
	public void syncSurvey(Activity activity, SurveyPlan surveyPlan,MaterialTask materialTask) {
		Survey_Questionnaire questionnaire = surveyPlan.getQuestionnaire();

		System.out.println("开始组装勘查文件");

		//组装文件夹路径： /data/pss/material/shanxi/20170101/tk/
		String[] folerPath = new String[]{ConfigUtil.material(),ConfigUtil.envi(),DateUtil.getCurrentDate(),TK_FOLDER};
		String dir = FileUtils.appendFolderPath(folerPath);
		System.out.println("勘查文件路径："+dir);

		/* 获得子站的活动id */
		SBDataDTO dto = new SBDataDTO();
		dto.setChannel(activity.getChannel());
		dto.setActivityNo(activity.getActivityNo());
		dto.setSyncTaskType(DictConst.SYNCTASKTYPE_ACTID);
		String activityId = sbRspService.activityIdGet(dto);

		StringBuffer content = new StringBuffer();
		String mark = DateUtil.generatorRadomNumber(); //文件标记，主要用于审批系统判断是否已经读取
		content.append("pssId"+V_CONNECT+safeTransfor(activityId)+"\r\n");
		content.append("address"+V_CONNECT+safeTransfor(questionnaire.getVenue().getName())+"\r\n");
		content.append("step"+V_CONNECT+safeTransfor(questionnaire.getSurveyStep().getValue())+"\r\n");
		content.append("startDate"+V_CONNECT+DateUtil.convertDateToString( questionnaire.getCreateOn(),DateUtil.FORMAT1)+"\r\n");
		content.append("endDate"+V_CONNECT+ DateUtil.convertDateToString( questionnaire.getUpdateOn(),DateUtil.FORMAT1)+"\r\n");
		content.append("sr"+V_CONNECT+ syncSurveyReport(questionnaire.getReportPath(),activity,questionnaire.getSurveyStep().getValue()) +"\r\n");

		System.out.println("开始组装勘查图片");
		int i = 0;

		for (Survey_Info info : questionnaire.getSurveyInfos()) {
			/* 需要进行整改的问题 */
			if (!info.isNextSurvey()) {
				continue;
			}
			i++;
			List<Survey_Photo> opinionPicList = info.getPhotos(); //整改图片

			content.append("infoId"+(i)+V_CONNECT + info.getOid() +"\r\n");
			content.append("opinion"+(i)+V_CONNECT+info.getAnswer() +"\r\n");
			content.append("solve"+(i)+V_CONNECT+info.getSurveyReform().getResult()+"\r\n");

			if (CollectionUtil.isEmpty(opinionPicList)) {
				continue;
			}
			StringBuffer opinionPic = new StringBuffer();
			for (Survey_Photo photo:opinionPicList) {
				String fileName = FileUtils.filterSingleFilePath(photo.getPath()); //解析后：1111.jpg
				String fileType = Files.getFileExtension(fileName);
				String onlyName = Files.getNameWithoutExtension(fileName);
				String newName = FileUtils.packTimestamp(SP + onlyName);
				FileUtils.downLoadFromUrl(photo.getPath(), newName, dir); //从原目录下复制到同步目录下
				opinionPic.append( newName + Const.DOT + fileType).append("&&");

				//将文件发给子站
				if (StringUtil.isNotEmpty(activity.getChannel())){
					SBDataDTO dataDTO1 = packSBDataDTO(activity.getChannel(), dir ,newName + Const.DOT + fileType);
					dataDTO1.setFileUrl(ConfigUtil.getValue("tk_url"));
					SyncTask task1 = commonService.instance(DictConst.SYNCTASKTYPE_FILE, JSON.toJSONString(dataDTO1));
					dataDTO1.setTask(task1);
					/* 异步同步图片 */
					sbRspService.sbAsync(dataDTO1);
				}
			}
			if (opinionPic.length()>0 && opinionPic.toString().endsWith("&&")) {
				opinionPic.substring(0,opinionPic.length()-2);
			}
			content.append("opinionPic" + (i) + V_CONNECT + opinionPic.toString() + "\r\n");
			opinionPic.setLength(0);

			List<Survey_Photo> solvePicList = info.getSurveyReform().getCorrectionPhotos();//整改图片
			if (CollectionUtil.isEmpty(solvePicList)) {
				continue;
			}
			StringBuffer solvePic = new StringBuffer();
			for (Survey_Photo photo:solvePicList) {
				String fileName = FileUtils.filterSingleFilePath(photo.getPath()); //解析后：1111.jpg
				String fileType = Files.getFileExtension(fileName);
				String onlyName = Files.getNameWithoutExtension(fileName);
				String newName = FileUtils.packTimestamp(SP + onlyName);
				FileUtils.downLoadFromUrl(photo.getPath(), newName, dir); //从原目录下复制到同步目录下
				solvePic.append( newName + Const.DOT + fileType).append("&&");

				//将文件发给子站
				if (StringUtil.isNotEmpty(activity.getChannel())){
					SBDataDTO dataDTO = packSBDataDTO(activity.getChannel(), dir ,newName + Const.DOT + fileType);
					dataDTO.setFileUrl(ConfigUtil.getValue("tk_url"));
					SyncTask task = commonService.instance(DictConst.SYNCTASKTYPE_FILE,JSON.toJSONString(dataDTO));
					dataDTO.setTask(task);
					/* 异步同步文件 */
					sbRspService.sbAsync(dataDTO);
				}
			}
			if (solvePic.length()>0 && solvePic.toString().endsWith("&&")) {
				solvePic.substring(0,solvePic.length()-2);
			}
			content.append("solvePic" + (i) + V_CONNECT + solvePic.toString() + "\r\n");
			solvePic.setLength(0);
		}
		System.out.println("开始组装勘查文件2");
		String fileName = ST + TI + mark + ".txt";
		String detailUrl = dir + fileName;
		File detailDir = new File(dir);
		if(!detailDir.exists()) {
			detailDir.mkdirs();
		}
		Path path = Paths.get(detailUrl);
		try (BufferedWriter writer = java.nio.file.Files.newBufferedWriter(path))  {
			writer.write(content.toString());
			/* 任务标记为成功 */
			materialTask.setSuccess(DictConst.Y);
			materialTaskDao.update(materialTask);
			System.out.println("勘查文件生成，地址："+ detailUrl);
		} catch (IOException e) {
			e.printStackTrace();
			return;
		}

		//将文件发给子站
		if (StringUtil.isNotEmpty(activity.getChannel())){
			SBDataDTO dataDTO = packSBDataDTO(activity.getChannel(), dir ,fileName);
			dataDTO.setFileUrl(ConfigUtil.getValue("tk_url"));
			SyncTask task = commonService.instance(DictConst.SYNCTASKTYPE_FILE,JSON.toJSONString(dataDTO));
			dataDTO.setTask(task);
            /* 异步同步文件 */
			sbRspService.sbAsync(dataDTO);
		}

    }

	/**
	 * 同步勘查报告
	 *  参数
	 *  http://bcxin-risk-extranet-test.oss-cn-shanghai.aliyuncs.com/wechat/report/458752.doc
	 *  或 goResources?path=2010-01-01/123123211.doc
	 */
	private String syncSurveyReport(String filePath,Activity activity,String step) {
		System.out.println("开始组装勘查报告");
		if (StringUtil.isEmpty(filePath)) {
			return Const.BLANK_CHAR;
		}
		//组装文件夹路径： /data/pss/material/shanxi/20170101/tk/
		String[] folderPath = new String[]{ConfigUtil.material(),ConfigUtil.envi(),DateUtil.getCurrentDate(),TK_FOLDER};
		String dir = FileUtils.appendFolderPath(folderPath);
		System.out.println("勘查报告路径："+dir);

		/* 获得子站的活动id */
		SBDataDTO dto = new SBDataDTO();
		dto.setChannel(activity.getChannel());
		dto.setActivityNo(activity.getActivityNo());
		dto.setSyncTaskType(DictConst.SYNCTASKTYPE_ACTID);
		String activityId = sbRspService.activityIdGet(dto);

		List<String> fileDirs = FileUtils.filterMultiFilePath(filePath);
		for (String fileDir:fileDirs) {
			//重新命名文件，两段式 (_sr_1498201966631_t_20170101221100)
			String finalFileName = SR + FileUtils.packTimestamp(activityId);
			FileUtils.downLoadFromUrl(filePath, finalFileName, dir); //从原目录下复制到同步目录下
			String filePathName = finalFileName + Const.DOT + Files.getFileExtension(fileDir);

			if (StringUtil.isNotEmpty(activity.getChannel())){
				SBDataDTO dataDTO = packSBDataDTO(activity.getChannel(), dir ,filePathName);
				dataDTO.setFileUrl(ConfigUtil.getValue("tk_url"));
				SyncTask task = commonService.instance(DictConst.SYNCTASKTYPE_FILE,JSON.toJSONString(dataDTO));
				dataDTO.setTask(task);

				/* 异步同步报告文件 */
				sbRspService.sbAsync(dataDTO);

				SBDataDTO dataDTO2 = new SBDataDTO();
				dataDTO2.setChannel(activity.getChannel());
				dataDTO2.setActivityNo(activity.getActivityNo());
				dataDTO2.setStep(step);
				dataDTO2.setReportUrl(filePath);
				dataDTO2.setSyncTaskType(DictConst.SYNCTASKTYPE_TKBG);
				dataDTO2.setFileUrl(ConfigUtil.getValue("tk_url"));
				SyncTask task2 = commonService.instance(activity.getActivityNo(),DictConst.SYNCTASKTYPE_TKBG,JSON.toJSONString(dataDTO2));
				dataDTO2.setTask(task2);

                /* 异步同步报告 */
				sbRspService.sbAsync(dataDTO2);
			}

			System.out.println("勘查报告同步文件：" + filePathName);
			/* 支持一个场地，一个勘查阶段，一份勘查报告*/
			return filePathName;
		}

		return Const.BLANK_CHAR;
	}
	
	/**
	 * 上传签名图片
	 * @param signImgPath
	 * @param request
	 * @return
	 */
	public String generateImage(String signImgPath, String feedBackPath, HttpServletRequest request){
		String materialFilePath = GlobalResources.WECHAT_SURVEY_UPLOADPATH + feedBackPath;
		String newFileName =  System.currentTimeMillis() + ".jpg";//随机生成新文件名
		
		String imgPath = FileUtils.huaweiOBSFileUpload_base64(signImgPath.split(";base64,")[1], materialFilePath, newFileName);
		System.out.println(imgPath);
		return imgPath;
	}

	public String generateImageFile(MultipartFile multipartFile, String feedBackPath, HttpServletRequest request){
//		String materialFilePath = GlobalResources.WECHAT_SURVEY_UPLOADPATH + feedBackPath;
//		String newFileName =  System.currentTimeMillis() + ".jpg";//随机生成新文件名

		String imgPath = FileUtils.huaweiOBSFileUpload(multipartFile, feedBackPath);
		System.out.println(imgPath);
		return imgPath;
	}

	@Override
	public boolean uploadSurveyImg(String mediaId, Survey_Info surveyInfo,HttpServletRequest request) {
//		Survey_Info surveyInfo = surveyInfoService.findSurveyInfoByOid(surveyInfoId);
		if(surveyInfo == null) {
			return false;
		} else{
			String imgUrl = (String)request.getSession().getAttribute(mediaId);
			String fileName = "";
			if(StringUtil.isNotEmpty(imgUrl)){
				imgUrl = imgUrl.replaceAll("%2F","/");
				fileName = imgUrl.substring(imgUrl.lastIndexOf("/")+1);
			}else{
				return false;
			}
			/*AccessToken accessToken = accessTokenService.getAccessToken();
			String fileName =  System.currentTimeMillis() + ".jpg";//随机生成新文件名				

			String path = ConfigUtil.envi() + "/survey/" + DateUtil.getCurrentDate(DateUtil.FORMAT2)+"/";
			String savePath = ConfigUtil.material() + path;

			boolean result = WeixinUtil.downloadImg(accessToken, mediaId, fileName, savePath);

			String imgUrl = "";
			if(result){
				imgUrl = GlobalResources.WEB_URL + "/getResource.do?path=" + path + fileName;
			}*/
			Survey_Photo photo = new Survey_Photo();
			photo.setCreateOn(new Date());
			photo.setSurveyInfo(surveyInfo);
			photo.setPath(imgUrl);
			photo.setOssKey(fileName);
			photo.setMediaId(mediaId);
			return surveyPhotoService.saveOrUpdate(photo);
		}
	}
	
	@Override
	public Survey_FeedBack findSurvey_FeedBackListBySurveyTaskIdAndStep(long taskId, SurveyStep surveyStep) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		criterionList.add(Restrictions.eq("surveyTask.oid", taskId));
		criterionList.add(Restrictions.eq("surveyStep", surveyStep));
		List<Survey_FeedBack> feedBacks = baseDao.findByCriterion(Survey_FeedBack.class, criterionList);
		if(feedBacks != null && feedBacks.size() > 0) {
			return feedBacks.get(0);
		}
		return null;
	}

	@Override
	public void checkFeedBackStatusByFeedBackId(long feedBackId) {
		Survey_FeedBack surveyFeedBack = findSurveyFeedBackByOid(feedBackId);
		boolean finishSurvey= true;
		if(surveyFeedBack.getSurveyPlans() == null || surveyFeedBack.getSurveyPlans().size()<1) {
			finishSurvey = false;
		} else {
			/*for(SurveyPlan plan : surveyFeedBack.getSurveyPlans()){
				if(plan.getTaskStatus().equals(TaskStatus.CONTINUE) || plan.getTaskStatus().equals(TaskStatus.NON)){
					finishSurvey = false;
				}
			}*/
			if (surveyFeedBack.getSurveyStep().equals(SurveyStep.THIRD)) {
				for(Survey_Questionnaire questionnaire : surveyFeedBack.getQuestionnaires()){
					if(!questionnaire.getTaskStatus().equals(QuestionStatusEnum.COMPLETE)){
						finishSurvey = false;
						break;
					}
				}
			} else {
				for(SurveyPlan plan : surveyFeedBack.getSurveyPlans()){
					if(plan.getTaskStatus().equals(PlanStatusEnum.CONTINUE) || plan.getTaskStatus().equals(PlanStatusEnum.NON)){
						finishSurvey = false;
					}
				}
			}
		}
		if (finishSurvey) {
//			surveyFeedBack.setTaskStatus(TaskStatus.COMPLETE);
			surveyFeedBack.setTaskStatus(FeedBackStatusEnum.COMPLETE);
			saveOrUpdate(surveyFeedBack);
			for(Survey_Questionnaire questionnaire : surveyFeedBack.getQuestionnaires()){
				if(!questionnaire.getTaskStatus().equals(QuestionStatusEnum.COMPLETE)){
//					questionnaire.setTaskStatus(TaskStatus.COMPLETE);
					questionnaire.setTaskStatus(QuestionStatusEnum.COMPLETE);
					surveyQuestionnaireService.saveOrUpdate(questionnaire);
				}
			}
		} else {
//			surveyFeedBack.setTaskStatus(TaskStatus.NON);
			surveyFeedBack.setTaskStatus(FeedBackStatusEnum.NON);
			saveOrUpdate(surveyFeedBack);
		}
	}

	@Override
	public void checkFeedBackStatusByQuestionnaireId(long questionnaireId) {
		Survey_Questionnaire questionnaire =surveyQuestionnaireService.findQuestionnaireByOid(questionnaireId);
		boolean finishSurvey= true;
		if(questionnaire.getSurveyPlans() == null || questionnaire.getSurveyPlans().size()<1) {
			finishSurvey = false;
		} else{
			for(SurveyPlan plan : questionnaire.getSurveyPlans()){
				if(plan.getTaskStatus().equals(PlanStatusEnum.CONTINUE) || plan.getTaskStatus().equals(PlanStatusEnum.NON)){
					finishSurvey = false;
				}
			}
		}
		if(finishSurvey){
//			questionnaire.setTaskStatus(TaskStatus.COMPLETE);
			questionnaire.setTaskStatus(QuestionStatusEnum.COMPLETE);
			surveyQuestionnaireService.saveOrUpdate(questionnaire);
			checkFeedBackStatusByFeedBackId(questionnaire.getFeedBack().getOid());
		}
	}

	/**
	 * 包装请求data
	 * @param channel
	 * @param dir
	 * @param fileName
	 * @return
	 */
	private SBDataDTO packSBDataDTO(String channel, String dir ,String fileName) {
		SBDataDTO dataDTO = new SBDataDTO();
		dataDTO.setEnvi(ConfigUtil.getValue("envi"));
		dataDTO.setChannel(channel);
		dataDTO.setMaterialBasePath(ConfigUtil.getValue("materialUpload_path"));
		dataDTO.setDir(dir);
		dataDTO.setFileName(fileName);
		dataDTO.setSyncTaskType(DictConst.SYNCTASKTYPE_FILE);
		return dataDTO;
	}

}
