package com.yihu.wlyy.service.survey;

import com.yihu.wlyy.entity.doctor.survey.*;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by Reece on 2017/3/14.
 */
@Service
@Transactional
public class PatientQuestionnaireService extends BaseService {
    @Autowired
    private SurveyQuestionnaireDao surveyQuestionnaireDao;
    @Autowired
    private SurveyQuestionnaireOptionsDao surveyQuestionnaireOptionsDao;
    @Autowired
    private SurveyDao surveyDao;
    @Autowired
    private SurveyUserDao surveyUserDao;
    @Autowired
    private SurveyOptionAnswersDao surveyOptionAnswersDao;
    @Autowired
    private SurveyAnswersDao surveyAnswersDao;
    @Autowired
    SurveyStatisticsDao surveyStatisticsDao;
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public JSONObject getSurveySummary(String patient, String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        Survey survey = surveyDao.findById(id);
        int complete = surveyUserDao.findByPatient(patient, id);
        String title = survey.getTitle();
        String comment = survey.getSurveyComment();
        int status = survey.getStatus();
        jsonObject.put("title", title);
        jsonObject.put("comment", comment);
        jsonObject.put("status", status);
        jsonObject.put("complete", complete == 0 ? 0 : 1);
        return jsonObject;
    }

    /**
     * @param id   问卷id
     * @param sort 当前问题的sort（初始为1）
     */
    public JSONObject getQuestions(String id, Integer sort) throws Exception {
        JSONObject jsonObject = new JSONObject();
        SurveyQuestionnaire question = null;
        //      该套问卷总题目数
        int total = surveyQuestionnaireDao.findTotalById(id);
        question = surveyQuestionnaireDao.findTotalByIdAndSort(id, sort);
        int sorts = question.getSort();
        String qstCode = question.getCode();
        String qstTitle = question.getTitle();
        int isRequired = question.getIsRequired();

        if (question.getQuestionCodeNext() != null) {
            String next = question.getQuestionCodeNext();
            SurveyQuestionnaire sq = surveyQuestionnaireDao.findByIdAndQstId(id, next);
            System.out.println("");
            jsonObject.put("nextQuestion", sq == null ? 0 : sq.getSort());
        }
        if (!StringUtils.isEmpty(question.getQuestionComment())) {
            jsonObject.put("comment", question.getQuestionComment());
        }
        int type = question.getQuestionType();
        switch (type) {
            case 0:
                List<SurveyQuestionnaireOptions> options = surveyQuestionnaireOptionsDao.findByIdAndQstCode(id, qstCode);
                List list = new ArrayList();
                for (SurveyQuestionnaireOptions option : options) {
//                        可构造集合，返回选项特定值
                    Map<String, Object> map = new HashMap<>();
                    String content = option.getContent();
                    int optSort = option.getSort();
                    int required = option.getIsRequired();
                    String surCod = option.getSurveyCode();
                    int del = option.getDel();
                    int havaComment = option.getHaveComment();
                    String code = option.getCode();
                    String questionCode = option.getQuestionnaireCode();
                    long optid = option.getId();
                    map.put("content", content);
                    map.put("isRequired", required);
                    map.put("code", code);
                    map.put("del", del);
                    map.put("sort", optSort);
                    map.put("surveyCode", surCod);
                    map.put("havaComment", havaComment);
                    map.put("questionnaireCode", questionCode);
                    map.put("id", optid);
                    if (option.getQuestionCodeNext() != null) {
                        String next = option.getQuestionCodeNext();
                        SurveyQuestionnaire sq = surveyQuestionnaireDao.findByIdAndQstId(id, next);
                        map.put("nextQuestion", sq == null ? 0 : sq.getSort());
                    }
                    list.add(map);
                }
                jsonObject.put("options", list);
                break;
            case 1:
                List<SurveyQuestionnaireOptions> optionss = surveyQuestionnaireOptionsDao.findByIdAndQstCode(id, qstCode);
                List lis = new ArrayList();
                for (SurveyQuestionnaireOptions option : optionss) {
//                        可构造集合，返回选项特定值
                    Map<String, Object> map = new HashMap<>();
                    String content = option.getContent();
                    int optSort = option.getSort();
                    int required = option.getIsRequired();
                    String surCod = option.getSurveyCode();
                    int del = option.getDel();
                    int havaComment = option.getHaveComment();
                    String code = option.getCode();
                    String questionCode = option.getQuestionnaireCode();
                    long optid = option.getId();
                    map.put("content", content);
                    map.put("isRequired", required);
                    map.put("code", code);
                    map.put("del", del);
                    map.put("sort", optSort);
                    map.put("surveyCode", surCod);
                    map.put("havaComment", havaComment);
                    map.put("questionnaireCode", questionCode);
                    map.put("id", optid);
                    if (option.getQuestionCodeNext() != null) {
                        String next = option.getQuestionCodeNext();
                        SurveyQuestionnaire sq = surveyQuestionnaireDao.findByIdAndQstId(id, next);
                        map.put("nextQuestion", sq == null ? 0 : sq.getSort());
                    }
                    lis.add(map);
                }
                jsonObject.put("options", lis);
                Integer maxNum = question.getMaxNum();
                Integer minNum = question.getMinNum();
                jsonObject.put("maxNum", maxNum);
                jsonObject.put("minNum", minNum);
//                jsonObject.put("options", optionss);
                break;
           /* case 2:
                if (question.getQuestionCodeNext() != null) {
                    String next = question.getQuestionCodeNext();
                    SurveyQuestionnaire sq = surveyQuestionnaireDao.findByIdAndQstId(id, next);
                    jsonObject.put("nextQuestion", sq.getSort());
                }
                break;*/
        }
        jsonObject.put("qstCode", qstCode);
        jsonObject.put("qstTitle", qstTitle);
        jsonObject.put("isRequired", isRequired);
        jsonObject.put("type", type);
        jsonObject.put("sort", sorts);
//        题目数量是变量
        jsonObject.put("totalNum", total);
        logger.error("居民获取题目信息==》" + jsonObject);
        return jsonObject;
    }

    public void saveAnswer(String patient, JSONObject jsonData) throws Exception {
        System.out.println("********jsonData********* " + jsonData);
        //解析json保存各种答案
        String surveyCode = jsonData.get("surveyCode").toString();
        Date createTime = new Date();
//        获取一维数组
        JSONArray questions = jsonData.getJSONArray("questions");
        for (int i = 0; i < questions.length(); i++) {
//            获取每一道题的信息
            JSONObject question = new JSONObject(questions.get(i).toString());

            String qstCode = question.get("qstCode").toString();
            int qstsort = Integer.parseInt(question.get("sort").toString());
            int type = Integer.parseInt(question.get("type").toString());


            if (type != 2) {
                if (question.has("options")) {
//               获取每道题的所有选项
                    JSONArray options = question.getJSONArray("options");
                    for (int j = 0; j < options.length(); j++) {
                        JSONObject option = new JSONObject(options.get(j).toString());
                        String code = getCode();
                        String optionCode = option.get("optionCode").toString();
                        int optsort = Integer.parseInt(option.get("sort").toString());
                        String comment = null;
                        int haveComment = 0;
                        if (option.has("comment")) {
                            comment = option.get("comment").toString();
                            haveComment = 1;
                        }
//                 保存到选择题答案表
                        SurveyOptionAnswers optionAnswer = new SurveyOptionAnswers(code, patient, surveyCode, qstCode, optionCode, comment, type, createTime);
                        surveyOptionAnswersDao.save(optionAnswer);
//                选择题修改统计表数量
                        surveyStatisticsDao.modifyAmount(surveyCode, qstCode, optionCode);
                    }
                }

            } else {
                String content = question.get("content").toString();
                if (!StringUtils.isEmpty(content)) {
//                    保存到问答题答案表
                    String code = getCode();
                    SurveyAnswers surveyAnswer = new SurveyAnswers(code, surveyCode, patient, qstCode, content, createTime);
                    surveyAnswersDao.save(surveyAnswer);
//                问答题保存到统计表(只负责更改数量不负责创建)
                    surveyStatisticsDao.modifyAmount(surveyCode, qstCode);
                }
            }
        }
//        更改调查对象表答题状态为已答
        surveyUserDao.modifyStatus(surveyCode, patient);
    }

}
