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

import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.service.project.ProjectJointPlanService;
import sun.security.rsa.RSAPadding;

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

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import cn.com.countrygarden.bi.main.model.test.Test;
import cn.com.countrygarden.bi.main.service.test.TestService;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.sys.Function;

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 org.springframework.web.bind.annotation.RequestParam;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaire;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblem;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblemClassification;
import cn.com.countrygarden.bi.main.model.review.ReviewQuestionnaireProblemOption;
import cn.com.countrygarden.bi.main.dao.review.*;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireEditVo;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemDTO;
import cn.com.countrygarden.bi.main.dto.ReviewQuestionnaireProblemEditVo;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.review.ReviewQuestionnaireProblemOptionService;
import cn.com.countrygarden.bi.main.dao.review.ReviewQuestionnaireProblemMapper;
import cn.com.countrygarden.bi.main.service.review.ReviewQuestionnaireProblemService;
import cn.com.countrygarden.bi.main.service.review.commonService.ClassificationVoService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;
import cn.com.countrygarden.bi.main.core.Response;

/**
 * 问题表-业务逻辑层实现
 *
 * @author 汤婷
 * @email www.justintoforest@gamail.com <<<<<<< HEAD
 * @url
 * @date 2018-06-25
 */
@Service
@Transactional
public class ReviewQuestionnaireProblemServiceImpl implements ReviewQuestionnaireProblemService {
	@Autowired
	private ReviewQuestionnaireProblemMapper reviewQuestionnaireProblemMapper;

	@Autowired
	private ReviewQuestionnaireMapper reviewQuestionnaireMapper;
	@Autowired
	private ReviewQuestionnaireProblemTypeMapper reviewQuestionnaireProblemTypeMapper;
	@Autowired
	private ReviewQuestionnaireProblemClassificationMapper reviewQuestionnaireProblemClassificationMapper;
	@Autowired
	private ReviewQuestionnaireProblemOptionMapper optionMapper;

	@Autowired
	private ClassificationVoService classificationVoService;

	public Result edit(ReviewQuestionnaireEditVo reviewQuestionnaireEditVo, String str, String qclassAryNew,
			AccessToken accessToken) throws ParseException {

		// 处理问题分类
		JSONArray qclassAry = (JSONArray) JSON.parseArray(qclassAryNew);
		ReviewQuestionnaireProblemClassification classification = null;
		List<Integer> classificationId = new ArrayList<Integer>();
		LinkedList<ReviewQuestionnaireProblemClassification> classificationList = new LinkedList<>();

		// 存放被当前问卷使用的问题分类id
		List<Integer> problemClassificationIds = new ArrayList<Integer>();

		for (int i = 0; i < qclassAry.size(); i++) {
			classification = new ReviewQuestionnaireProblemClassification();
			JSONObject classificationObj = qclassAry.getJSONObject(i);

			// 如果两个相等则为新增问题分类
			if (classificationObj.getString("id").equals(classificationObj.getString("label"))) {
				classification.setName(classificationObj.getString("label"));
				classification.setCreateBy(accessToken.getUserCode());
				classification.setFlag(1);
				classification.setInvestigationmanagementId(reviewQuestionnaireEditVo.getInvestigationmanagementId());
			
				classificationList.add(classification);

			} else {
				// 否则为数据库已经存在的数据，除了数据库已经存在的数据其他都进行删除
				classificationId.add(classificationObj.getInteger("id"));

			}
		}
		// 添加问题分类前除了没有被用户删除的问题分类其他全部进行删除
		if (classificationId.size() != 0) {
			classificationVoService.ClassificationFlagUpdateService(reviewQuestionnaireEditVo.getId());
			reviewQuestionnaireProblemClassificationMapper.deleteNotClassificationIds(classificationId);
		}

		// 添加问题分类
		if (classificationList.size() != 0) {
			if (reviewQuestionnaireProblemClassificationMapper.insertList(classificationList) <= 0) {
				throw new ServiceException("ReviewQuestionnaireProblemService异常");
			}
		}

		boolean sign = true;
		breakStr:

		if (reviewQuestionnaireEditVo != null && str != null && str != "") {
			// 根据问卷ID得到问题ID集合
			List<Integer> problemId = reviewQuestionnaireProblemMapper
					.selectProblemId(reviewQuestionnaireEditVo.getId());
			// 根据问题ID集合批量删除单选项
			if (problemId.size() != 0) {
				optionMapper.deleteproblemIds(problemId);
			}
			// 根据问卷ID删除问题
			if (reviewQuestionnaireProblemMapper.deleteQuestionnaireProblem(reviewQuestionnaireEditVo.getId()) > 0) {
				// 更新问卷ID
				ReviewQuestionnaire reviewQuestionnaire = new ReviewQuestionnaire();
				reviewQuestionnaire.setId(reviewQuestionnaireEditVo.getId());
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				reviewQuestionnaire.setName(reviewQuestionnaireEditVo.getQuestionnaireName());
				reviewQuestionnaire.setDescribed(reviewQuestionnaireEditVo.getQuestionnaireDescribed());
				reviewQuestionnaire.setCreateBy(reviewQuestionnaireEditVo.getCreateBy());
				reviewQuestionnaire.setCreateTime(dateFormat.parse(reviewQuestionnaireEditVo.getCreateTime()));
				reviewQuestionnaire.setUpdateBy(accessToken.getUserCode());
				reviewQuestionnaire.setUpdateTime(new Date());
				if (reviewQuestionnaireMapper.updateByPrimaryKeySelective(reviewQuestionnaire) > 0) {
					// 添加问题
					ReviewQuestionnaireProblem problem = new ReviewQuestionnaireProblem();
					String questionnaireProblems = "[" + str + "]";
					JSONArray ary = (JSONArray) JSON.parseArray(questionnaireProblems);
					for (int i = 0; i < ary.size(); i++) {
						problem = new ReviewQuestionnaireProblem();
						JSONObject obj = ary.getJSONObject(i);
						problem.setQuestionnaireId(reviewQuestionnaire.getId());
						// problem.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
						// 判断classification是否是新增的问题分类
						if (!obj.getString("classification").equals("")) {
							boolean flag = true;
							for (ReviewQuestionnaireProblemClassification classificatio : classificationList) {
								String strReplace=(obj.getString("classification")).replace(" ","");
								String classificatioName=(classificatio.getName()).replace(" ","");
								if (classificatioName.equals(strReplace)) {
						//		if (classificatio.getName().equals(obj.getString("classification"))) {
								problem.setQuestionnaireProblemClassificationId(classificatio.getId());
									flag = false;
									break;
								}

							}

							if (flag) {
								problem.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
							}
						} else {
							List<Integer> classificationid=reviewQuestionnaireProblemMapper.selectrqclassiid();
							System.out.println(classificationid.get(0));
							problem.setQuestionnaireProblemClassificationId(classificationid.get(0));							
							//problem.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
						}
						// 当问题分类被问卷使用后需要改变状态flag为不能再被删除
						problemClassificationIds.add(problem.getQuestionnaireProblemClassificationId());

						problem.setQuestionTypeId(obj.getInteger("type"));
						problem.setTitleDescription(obj.getString("title"));
						if (obj.getInteger("type") == 1) {
							if (obj.getInteger("score") > 0) {
								problem.setScore(obj.getInteger("score"));
							} else {
								// 当分数不大于0时
								sign = false;
								break breakStr;
							}
						}
						problem.setAnswerDescription(obj.getString("answerDescription"));
						// 如果在编辑时问题是新增的则创建人为编辑人，否则创建人不变
						if (obj.getString("id") != null && obj.getString("id") != "") {
							problem.setId(obj.getInteger("id"));
							problem.setCreateBy(reviewQuestionnaireEditVo.getCreateBy());

							problem.setCreateTime(dateFormat.parse(reviewQuestionnaireEditVo.getCreateTime()));
							problem.setUpdateBy(accessToken.getUserCode());
							problem.setUpdateTime(new Date());
						} else {
							problem.setCreateBy(accessToken.getUserCode());
							problem.setCreateTime(new Date());
						}
						// 添加问题成功后再添加单选项
						if (reviewQuestionnaireProblemMapper.insertSelective(problem) > 0) {
							ReviewQuestionnaireProblemOption option = new ReviewQuestionnaireProblemOption();
							JSONArray aryOption = (JSONArray) JSON.parseArray(obj.getString("option"));
							// 插入单选表
							for (int j = 0; j < aryOption.size(); j++) {
								JSONObject objOption = aryOption.getJSONObject(j);
								option = new ReviewQuestionnaireProblemOption();
								if (objOption.getString("name") != null && objOption.getString("name") != "") {
									option.setQuestionnaireProblemId(problem.getId());
									option.setName(objOption.getString("name"));
									option.setOptionScore(Integer.parseInt(objOption.getString("optionScore").trim()));
									// 如果在编辑单选时problemId为null则创建人为编辑人，否则创建人不变
									if (objOption.getString("problemId") != null && objOption.getString("id") != "") {
										// option.setId(objOption.getInteger("problemId"));
										option.setCreateBy(reviewQuestionnaireEditVo.getCreateBy());

										option.setCreateTime(
												dateFormat.parse(reviewQuestionnaireEditVo.getCreateTime()));
										option.setUpdateBy(accessToken.getUserCode());
										option.setUpdateTime(new Date());
									} else {
										option.setCreateBy(accessToken.getUserCode());
										option.setCreateTime(new Date());
									}
									if (optionMapper.insertSelective(option) <= 0) {
										// 添加单选项
										sign = false;
										break breakStr;
									}
								}
							}

						} else {
							// 添加问题
							sign = false;
							break breakStr;
						}
					}

				} else {
					// 更新问卷
					sign = false;
					break breakStr;
				}
			} else {
				// 删除问题
				sign = false;
				break breakStr;
			}
		}

		// 更改被当前问卷使用后的问题分类状态
		classificationVoService.ClassificationFlag(problemClassificationIds);

		if (!sign) {
			throw new ServiceException("ReviewQuestionnaireProblemService异常");
		}

		return Response.response();
	}

	// 添加问题前先返回问题分类列表与题型列表
	public Result queryProblemTypeAndProblemClass(int investigationmanagementId) {
		ReviewQuestionnaireProblemEditVo typeAndClassList = new ReviewQuestionnaireProblemEditVo();
		typeAndClassList.setQtypeAry(reviewQuestionnaireProblemTypeMapper.selectQuestionnaireProblemTypeVo(investigationmanagementId));
		typeAndClassList.setQclassAry(
				reviewQuestionnaireProblemClassificationMapper.queryQuestionnaireProblemClassificationVo(investigationmanagementId));

		return Response.response(typeAndClassList);
	}

	/**
	 * 添加问卷
	 */
	public Result add(ReviewQuestionnaire reviewQuestionnaire, String str, String qclassAryNew,
			AccessToken accessToken) {
        if(reviewQuestionnaire.getInvestigationmanagementId()==null) {
        	reviewQuestionnaire.setId(1);//添加360评测问卷
        }
		// 处理问题分类
		JSONArray qclassAry = (JSONArray) JSON.parseArray(qclassAryNew);
		ReviewQuestionnaireProblemClassification classification = null;
		List<Integer> classificationId = new ArrayList<Integer>();
		LinkedList<ReviewQuestionnaireProblemClassification> classificationList = new LinkedList<>();
		// 存放Flag为2的classficationId
		List<Integer> classificationFlagId = new ArrayList<Integer>();

		for (int i = 0; i < qclassAry.size(); i++) {
			classification = new ReviewQuestionnaireProblemClassification();
			JSONObject classificationObj = qclassAry.getJSONObject(i);

			// 如果两个相等则为新增问题分类
			if (classificationObj.getString("id").equals(classificationObj.getString("label"))) {
				classification.setName(classificationObj.getString("label"));
				classification.setCreateBy(accessToken.getUserCode());
				classification.setFlag(1);
				classification.setInvestigationmanagementId(reviewQuestionnaire.getInvestigationmanagementId());
				classificationList.add(classification);

			} else {
				// 否则为数据库已经存在的数据，除了数据库已经存在的数据其他都进行删除
				classificationId.add(classificationObj.getInteger("id"));

			}

		}

		// 添加问题分类前除了没有被用户删除的问题分类其他全部进行删除
		if (classificationId.size() != 0) {
			reviewQuestionnaireProblemClassificationMapper.deleteNotClassificationIds(classificationId);
		}

		// 添加问题分类
		if (classificationList.size() != 0) {
			if (reviewQuestionnaireProblemClassificationMapper.insertList(classificationList) <= 0) {
				throw new ServiceException("ReviewQuestionnaireProblemService异常");
			}
		}
		boolean sign = true;
		breakStr:

		// 插入问卷表
		if (reviewQuestionnaire != null && str != null && str != "") {

			reviewQuestionnaire.setCreateBy(accessToken.getUserCode());
			if (reviewQuestionnaireMapper.insertSelective(reviewQuestionnaire) > 0) {

				String param = "[" + str + "]";
				JSONArray ary = (JSONArray) JSON.parseArray(param);
				ReviewQuestionnaireProblem problems = null;
				// 插入问题表
				for (int i = 0; i < ary.size(); i++) {
					JSONObject obj = ary.getJSONObject(i);
					problems = new ReviewQuestionnaireProblem();
					problems.setQuestionnaireId(reviewQuestionnaire.getId());

					// 判断classification是否是新增的问题分类
					
					if (!obj.getString("classification").equals("")) {
						boolean flag = true;
						for (ReviewQuestionnaireProblemClassification classificatio : classificationList) {
							String strReplace=(obj.getString("classification")).replace(" ","");
							String classificatioName=(classificatio.getName()).replace(" ","");
							if (classificatioName.equals(strReplace)) {
								problems.setQuestionnaireProblemClassificationId(classificatio.getId());
								flag = false;
								break;
							}
						}
						if (flag) {
							problems.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));
						}
					} else {
						List<Integer> classificationid=reviewQuestionnaireProblemMapper.selectrqclassiid();
							System.out.println(classificationid.get(0));
							problems.setQuestionnaireProblemClassificationId(classificationid.get(0));
						//problems.setQuestionnaireProblemClassificationId(obj.getInteger("classification"));						
					}

					// 当问题分类被问卷使用后改变状态flag为不能再被删除
					classificationFlagId.add(problems.getQuestionnaireProblemClassificationId());
					problems.setQuestionTypeId(obj.getInteger("type"));
					if (obj.getInteger("type") == 1) {
						if (obj.getInteger("score") > 0) {
							problems.setScore(obj.getInteger("score"));
						} else {
							sign = false;
							break breakStr;
						}
					}
					problems.setAnswerDescription(obj.getString("answerDescription"));
					problems.setTitleDescription(obj.getString("title").trim());
					problems.setCreateBy(accessToken.getUserCode());
					ReviewQuestionnaireProblemOption option = null;
					int count = reviewQuestionnaireProblemMapper.insertSelective(problems);
					JSONArray aryOption = (JSONArray) JSON.parseArray(obj.getString("option"));
					if (count > 0) {
						// 插入单选表
						for (int j = 0; j < aryOption.size(); j++) {
							JSONObject objOption = aryOption.getJSONObject(j);
							option = new ReviewQuestionnaireProblemOption();
							if (objOption.getString("name") != null && objOption.getString("name") != "") {
								option.setQuestionnaireProblemId(problems.getId());
								option.setName(objOption.getString("name"));
								option.setOptionScore(objOption.getInteger("optionScore"));
								option.setCreateBy(accessToken.getUserCode());
								if (optionMapper.insertSelective(option) <= 0) {
									sign = false;
									break breakStr;
								}
							}

						}
					} else {
						sign = false;
						break breakStr;
					}
				}
			} else {
				sign = false;
				break breakStr;
			}
		}

		if (!sign) {
			throw new ServiceException("ReviewQuestionnaireProblemService异常");
		}
		// 被当前问卷使用的更改问卷分类id状态
		classificationVoService.ClassificationFlag(classificationFlagId);

		return Response.response();
	}

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

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

	@Override
	public Result queryById(Integer id) {
		// TODO Auto-generated method stub
		return Response.response(reviewQuestionnaireProblemMapper.selectByPrimaryKey(id));
	}

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

	@Override
	public Result add(ReviewQuestionnaireProblem reviewQuestionnaireProblem, AccessToken accessToken) {
		reviewQuestionnaireProblem.setCreateBy(accessToken.getUserCode());
		reviewQuestionnaireProblemMapper.insert(reviewQuestionnaireProblem);
		return Response.response();
	}

	@Override
	public Result edit(ReviewQuestionnaireProblem reviewQuestionnaireProblem, AccessToken accessToken) {
		reviewQuestionnaireProblemMapper.updateByPrimaryKey(reviewQuestionnaireProblem);
		return Response.response();
	}

	@Override
	public List<ReviewQuestionnaireProblemDTO> questionoblemsex(Integer questionnaireId,
			Integer investigationmanagementId) {
		
		return reviewQuestionnaireProblemMapper.questionoblemsex(questionnaireId,investigationmanagementId);
	}

	@Override
	public List<ReviewQuestionnaireProblemDTO> questionoblemswenex(Integer questionnaireId,
			Integer investigationmanagementId) {
		
		return reviewQuestionnaireProblemMapper.questionoblemswenex(questionnaireId,investigationmanagementId);
	}

}