package cn.com.countrygarden.bi.main.service.review.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.review.ReviewInvestigatedMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewJudgeMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireMapper;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireProblemMapper;
import cn.com.countrygarden.bi.main.dto.ReviewAnswerBeforeVo;
import cn.com.countrygarden.bi.main.dto.ReviewInvestigationVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemOptionVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemVo;
import cn.com.countrygarden.bi.main.dto.TemplateParamVo;
import cn.com.countrygarden.bi.main.dto.reviewInvestigatedIsRepeatVo;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.review.ReviewInvestigated;
import cn.com.countrygarden.bi.main.model.review.ReviewJudge;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaire;
import cn.com.countrygarden.bi.main.service.review.ReviewInvestigatedService;
import cn.com.countrygarden.bi.main.sms.SmsBaseManager;
import cn.com.countrygarden.bi.main.sms.SmsSend;
import cn.com.countrygarden.bi.main.util.provingMobileUtils;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 被调查人-业务逻辑层实现
 *
 * @author 汤婷
 * @email www.justintoforest@gamail.com
 * @url
 * @date 2018-06-25
 */

@Service
@Transactional
public class ReviewInvestigatedServiceImpl implements ReviewInvestigatedService {

	@Autowired
	private ReviewQuestionnaireMapper reviewQuestionnaireMapper;

	@Autowired
	private ReviewQuestionnaireProblemMapper ProblemMapper;

	@Autowired
	private ReviewInvestigatedMapper reviewInvestigatedMapper;

	@Autowired
	private ReviewJudgeMapper reviewjudgemapper;

	// 答题前返回的数据
	public Result selectAnswerBeforeVo(int investigatedId, int reviewJudgeId, int questionnaireId) {
		ReviewAnswerBeforeVo anserVo = new ReviewAnswerBeforeVo();
		reviewInvestigatedIsRepeatVo investigatedIsRepeatVo = reviewInvestigatedMapper
				.selectInvestigatedIsRepeatVo(investigatedId, reviewJudgeId);

		if (investigatedIsRepeatVo.getFlag() == 0) {
			if (investigatedIsRepeatVo.getIsSubmission() == 0) {
				//ReviewQuestionnaireProblemVo
				anserVo = reviewInvestigatedMapper.selectAnswerBeforeVo(investigatedId, questionnaireId);
				List<ReviewQuestionnaireProblemVo> queryQuestionnaireProblemVo=ProblemMapper.queryQuestionnaireProblemVo(anserVo.getQuestionnaireId());
				for (ReviewQuestionnaireProblemVo reviewQuestionnaireProblemVo : queryQuestionnaireProblemVo) {
					if(reviewQuestionnaireProblemVo.getType()==3) {
				    	List<ReviewQuestionnaireProblemOptionVo> option=ProblemMapper.option(reviewQuestionnaireProblemVo.getId());		    	
				    		reviewQuestionnaireProblemVo.setOption(option);			    		
				    }		
				}
				anserVo.setProblemVo(queryQuestionnaireProblemVo);
				
				anserVo.setProblemjianweVo(ProblemMapper.queryQuestionnaireProblemwendaVo(anserVo.getQuestionnaireId()));
			} else if (investigatedIsRepeatVo.getIsSubmission() == 1 && investigatedIsRepeatVo.getIsRepeat() == 1) {
				anserVo = reviewInvestigatedMapper.selectAnswerBeforeVo(investigatedId, questionnaireId);
				List<ReviewQuestionnaireProblemVo> queryQuestionnaireProblemVo=ProblemMapper.queryQuestionnaireProblemVo(anserVo.getQuestionnaireId());
				for (ReviewQuestionnaireProblemVo reviewQuestionnaireProblemVo : queryQuestionnaireProblemVo) {
					if(reviewQuestionnaireProblemVo.getType()==3) {
				    	List<ReviewQuestionnaireProblemOptionVo> option=ProblemMapper.option(reviewQuestionnaireProblemVo.getId());		    	
				    		reviewQuestionnaireProblemVo.setOption(option);			    		
				    }		
				}
				anserVo.setProblemVo(queryQuestionnaireProblemVo);
				anserVo.setProblemjianweVo(ProblemMapper.queryQuestionnaireProblemwendaVo(anserVo.getQuestionnaireId()));
			}
		}

		anserVo.setInvestigatedIsRepeatVo(investigatedIsRepeatVo);

		return Response.response(anserVo);
	}

	// 调查列表
	public Result selectInvestigationVoList(ReviewInvestigationVo reviewinvesti, int page, int size,boolean haseole,String getusercode) {

		Page<Object> pageList = PageHelper.startPage(page, size);
		reviewinvesti.setHaseole(haseole);
		reviewinvesti.setGetusercode(getusercode);
		List<ReviewInvestigationVo> list = reviewInvestigatedMapper.selectInvestigationVoList(reviewinvesti);
		PageData data = new PageData(pageList);
		data.setData(pageList.getResult());

		return Response.response(data);
	}

	@Override
	public Result queryPageList(ReviewInvestigated reviewInvestigated, int page, int size) {
		Page<Object> pageList = PageHelper.startPage(page, size);
		Condition condition = new Condition(ReviewInvestigated.class);
		Criteria criteria = condition.createCriteria();
		// TODO 添加条件
		reviewInvestigatedMapper.selectByCondition(condition);

		PageData data = new PageData(pageList);
		data.setData(pageList.getResult());
		return Response.response(data);
	}

	@Override
	public Result queryById(Integer id) {
		return Response.response(reviewInvestigatedMapper.selectByPrimaryKey(id));
	}

	// 重发短信
	@Override
	public Result resendSms(int investigatedId, String investigatedName, int questionnaireId,
			String questionnaireName) {

		TemplateParamVo templateParam = null;

		List<ReviewJudge> judgeList = reviewjudgemapper.selectJudgeTel(investigatedId, questionnaireId);
		List<TemplateParamVo> templateParamVolist = new ArrayList<TemplateParamVo>();
		for (ReviewJudge judge : judgeList) {
			templateParam = new TemplateParamVo();
			StringBuffer str = new StringBuffer("亲爱的" + judge.getName() + "，您有一份关于[" + investigatedName + "-"
					+ questionnaireName + "]的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppUrl()+"?id=" + investigatedId
					+ "&jd=" + judge.getId() + "&qd=" + questionnaireId + " 退订回复TD");
			templateParam.setUrl(str.toString());
			templateParam.setPhone(judge.getTel());
			templateParamVolist.add(templateParam);

		}
		// 发送短信
		if (templateParamVolist.size() != 0) {
			smsSend.getAllDepartments(templateParamVolist, 1);
		}

		return Response.response();
	}

	@Autowired
	SmsSend smsSend;

	public Result add(ReviewInvestigated reviewInvestigated, String upJsonStr, String sameJsonStr, String downJsonStr,
			AccessToken accessToken) {
		reviewInvestigated.setCreateBy(accessToken.getUserCode());
		ReviewQuestionnaire questionnaire = reviewQuestionnaireMapper
				.selectByPrimaryKey(reviewInvestigated.getQuestionnaireId());
		int i = reviewInvestigatedMapper.insertSelective(reviewInvestigated);
		if (i == 0) {
			throw new ServiceException();
		}
		ReviewJudge review;
		// 发送短信
		// 1.获得评选人姓名，被评选人姓名，被评选人电话
		TemplateParamVo templateParam = null;
		List<TemplateParamVo> templateParamVolist = new ArrayList<TemplateParamVo>();

		if (StringUtils.isNotBlank(upJsonStr)) {
			JSONObject jsonObjectup = JSONObject.parseObject(upJsonStr);
			JSONArray reviewers = jsonObjectup.getJSONArray("reviewers");

			for (Object object : reviewers) {
				review = new ReviewJudge();
				review.setInvestigatedId(reviewInvestigated.getId());
				review.setQuestionnaireId(reviewInvestigated.getQuestionnaireId());
				review.setGradeId(Integer.parseInt(jsonObjectup.getString("id")));
				review.setIssubmission(0);
				review.setIsPartake(0);
				review.setFlag(0);
				review.setCreateBy(accessToken.getUserCode());
				JSONObject jo =(JSONObject) object;
				String name = jo.getString("name");
				String tel = jo.getString("phone");
				if (name != null && !name.equals("") && tel != null && !tel.equals("")) {
					review.setName(name);
					review.setTel(tel);

					reviewjudgemapper.insertSelective(review);

					// 获得评选人姓名as_user，被评选人姓名,url到templateParam
					if (provingMobileUtils.isMobile(tel)) {

						templateParam = new TemplateParamVo();

						StringBuffer str = new StringBuffer("亲爱的" + review.getName() + "，您有一份关于"
								+ reviewInvestigated.getName() + "-" + questionnaire.getName()
								+ "的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppUrl()+"?id="
								+ reviewInvestigated.getId() + "&jd=" + review.getId() + "&qd="
								+ review.getQuestionnaireId() + " 退订回复TD");
						templateParam.setUrl(str.toString());
						templateParam.setPhone(tel);
						templateParamVolist.add(templateParam);
					}
				}

			}

		}

		if (StringUtils.isNotBlank(sameJsonStr)) {
			JSONObject jsonObjectsame = JSONObject.parseObject(sameJsonStr);
			JSONArray reviewers = jsonObjectsame.getJSONArray("reviewers");

			for (Object object : reviewers) {
				review = new ReviewJudge();
				review.setInvestigatedId(reviewInvestigated.getId());
				review.setQuestionnaireId(reviewInvestigated.getQuestionnaireId());
				review.setGradeId(Integer.parseInt(jsonObjectsame.getString("id")));
				review.setIssubmission(0);
				review.setFlag(0);
				review.setIsPartake(0);
				review.setCreateBy(accessToken.getUserCode());
				JSONObject jo = (JSONObject) object;
				String name = jo.getString("name");
				String tel = jo.getString("phone");
				if (name != null && !name.equals("") && tel != null && !tel.equals("")) {
					review.setName(name);
					review.setTel(tel);
					reviewjudgemapper.insertSelective(review);

					// 获得评选人姓名as_user，被评选人姓名,url到templateParam
					if (provingMobileUtils.isMobile(tel)) {
						templateParam = new TemplateParamVo();
						StringBuffer str = new StringBuffer(
								"亲爱的" + review.getName() + "，您有一份关于[" + reviewInvestigated.getName()
										+ "]的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppUrl()+"?id="
										+ reviewInvestigated.getId() + "&jd=" + review.getId() + "&qd="
										+ review.getQuestionnaireId() + " 退订回复TD");
						templateParam.setUrl(str.toString());
						templateParam.setPhone(tel);

						templateParamVolist.add(templateParam);
					}
				}

			}
		}

		if (StringUtils.isNotBlank(downJsonStr)) {
			JSONObject jsonObjectdown = JSONObject.parseObject(downJsonStr);
			JSONArray reviewers = jsonObjectdown.getJSONArray("reviewers");

			for (Object object : reviewers) {
				review = new ReviewJudge();
				review.setInvestigatedId(reviewInvestigated.getId());
				review.setQuestionnaireId(reviewInvestigated.getQuestionnaireId());
				review.setGradeId(Integer.parseInt(jsonObjectdown.getString("id")));
				review.setIssubmission(0);
				review.setFlag(0);
				review.setIsPartake(0);
				review.setCreateBy(accessToken.getUserCode());
				JSONObject jo = (JSONObject) object;
				String name = jo.getString("name");
				String tel = jo.getString("phone");
				if (name != null && !name.equals("") && tel != null && !tel.equals("")) {
					review.setName(name);
					review.setTel(tel);
					review.setIsPartake(1);

					reviewjudgemapper.insertSelective(review);

					// 获得评选人姓名as_user，被评选人姓名,url到templateParam
					if (provingMobileUtils.isMobile(tel)) {
						templateParam = new TemplateParamVo();
						StringBuffer str = new StringBuffer(
								"亲爱的" + review.getName() + "，您有一份关于[" + reviewInvestigated.getName()
										+ "]的调查问卷，请点击链接参与评价："+SmsBaseManager.getAppUrl()+"?id="
										+ reviewInvestigated.getId() + "&jd=" + review.getId() + "&qd="
										+ review.getQuestionnaireId() + " 退订回复TD");
						templateParam.setUrl(str.toString());
						templateParam.setPhone(tel);
						templateParamVolist.add(templateParam);
					}
				}

			}
		}

		/**
		 * 发送短信 templateParamVolist：需要发送短信的信息集合 3 ：发送失败后需要重新发送的次数
		 * syncApiClientSmsService：注入
		 */

		if (templateParamVolist.size() != 0) {
			smsSend.getAllDepartments(templateParamVolist, 1);
		}

		return Response.response();

	}

	// 结束问卷调查
	public Result edit(ReviewInvestigated reviewInvestigated, AccessToken accessToken) {
		reviewInvestigated.setFlag(1);

		reviewInvestigatedMapper.updateByPrimaryKeySelective(reviewInvestigated);
		return Response.response();
	}

	@Override
	public Result del(Integer id) {
		int count = reviewInvestigatedMapper.deleteByPrimaryKey(id);
		return Response.response(count);
	}

}
