package com.yihu.wlyy.service.survey;

import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.survey.*;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.dict.SystemDictDao;
import com.yihu.wlyy.repository.doctor.*;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.BaseService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.wechat.util.WeiXinAccessTokenUtils;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by Reece on 2017/3/9.
 */
@Service
@Transactional
public class ManagerQuestionnaireService extends BaseService {

    @Autowired
    private SurveyDao surveyDao;
    @Autowired
    private SurveyQuestionsDao surveyQuestionsDao;
    @Autowired
    private SurveyLabelInfoDao surveyLabelInfoDao;
    @Autowired
    private SurveyQuestionsOptionsDao surveyQuestionsOptionsDao;
    @Autowired
    private SurveyUserDao surveyUserDao;
    @Autowired
    private SurveyFilterDao surveyFilterDao;
    @Autowired
    private SurveyQuestionnaireOptionsDao surveyQuestionnaireOptionsDao;
    @Autowired
    private SurveyQuestionnaireDao surveyQuestionnaireDao;
    @Autowired
    private SurveyTemplateOptionsDao surveyTemplateOptionsDao;
    @Autowired
    private SurveyTemplateQuestionsDao surveyTemplateQuestionsDao;
    @Autowired
    private SurveyOptionAnswersDao surveyOptionAnswersDao;
    @Autowired
    private SurveyAnswersDao surveyAnswersDao;
    @Autowired
    private SurveyTemplatesDao surveyTemplatesDao;
    @Autowired
    private SurveyStatisticsDao surveyStatisticsDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SystemDictDao systemDictDao;
    @Autowired
    private SurveyDimensionDao surveyDimensionDao;
    @Autowired
    private SurveyDimensionDetailDao surveyDimensionDetailDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private WeiXinAccessTokenUtils weiXinAccessTokenUtils;
    @Autowired
    WeiXinOpenIdUtils weiXinOpenIdUtils;

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public String createSurvey(String doctor, JSONObject jsonStr, String accessToken) throws Exception {
//        问卷信息
        String surveyCode = getCode();
        String surveyName = jsonStr.getString("surveyName");
        String surveyComment = jsonStr.getString("comment");
        String templateCode = null;
        String send = jsonStr.get("send").toString();
        int status = 1;
//        自主创建
        int useType = 1;
        if (!StringUtils.isEmpty(jsonStr.getString("templateCode"))) {
//          模板创建
            useType = 0;
            templateCode = jsonStr.getString("templateCode");
        }
//      获取调查对象
        JSONObject surveyTarget = jsonStr.getJSONObject("surveyTarget");
        //            0不限 1男 2女
        int sex = Integer.parseInt(surveyTarget.get("sex").toString());
        JSONArray disease = surveyTarget.getJSONArray("disease");
        JSONArray service = surveyTarget.getJSONArray("service");
        JSONArray healthCondition = surveyTarget.getJSONArray("healthCondition");
        if (sex != 0) {
            String dimensionCode = surveyDimensionDao.findByName("性别");
            String dimensionDetailCode = getCode();
            SurveyDimensionDetail surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, sex == 1 ? "男" : "女", sex, "性别", 1, surveyCode);
            surveyDimensionDetailDao.save(surveyDimensionDetail);
//          保存到筛选表
            SurveyFilter surveyFilter = new SurveyFilter(getCode(), surveyCode, dimensionDetailCode);
            surveyFilterDao.save(surveyFilter);
        }
        for (Object serv : service) {
            if ("0".equals(serv.toString())) {
                break;
            } else {
//                       ===================================
                String dimensionCode = surveyDimensionDao.findByName("服务类型");
                String dimensionDetailCode = getCode();
                SurveyDimensionDetail surveyDimensionDetail = null;
                switch (Integer.parseInt(serv.toString())) {
//                1.普通人群 2.慢病人群 3.65岁以上人群
                    case 1:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "普通人群", 1, "服务类型", 3, surveyCode);
                        break;
                    case 2:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "慢病人群", 2, "服务类型", 3, surveyCode);
                        break;
                    case 3:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "65岁以上人群", 3, "服务类型", 3, surveyCode);
                        break;
                }

                surveyDimensionDetailDao.save(surveyDimensionDetail);

                SurveyFilter surveyFilter = new SurveyFilter(getCode(), surveyCode, dimensionDetailCode);
                surveyFilterDao.save(surveyFilter);
            }
        }
        for (Object health : healthCondition) {
            if ("0".equals(health.toString())) {
                break;
            } else {
                String dimensionCode = surveyDimensionDao.findByName("健康状况");
                String dimensionDetailCode = getCode();
                String surveyFilterCode = getCode();
                SurveyDimensionDetail surveyDimensionDetail = null;
                switch (Integer.parseInt(health.toString())) {
//                1.健康人群 2.患病人群 3.高危人群 4.恢复期人群
                    case 1:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "健康人群", 1, "健康状况", 4, surveyCode);
                        break;
                    case 2:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "患病人群", 2, "健康状况", 4, surveyCode);
                        break;
                    case 3:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "高危人群", 3, "健康状况", 4, surveyCode);
                        break;
                    case 4:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "恢复期人群", 4, "健康状况", 4, surveyCode);
                        break;
                }
                surveyDimensionDetailDao.save(surveyDimensionDetail);

                SurveyFilter surveyFilter = new SurveyFilter(surveyFilterCode, surveyCode, dimensionDetailCode);
                surveyFilterDao.save(surveyFilter);

            }
        }
        for (Object disea : disease) {
            if ("0".equals(disea.toString())) {
//                dise += ",";
                break;
            } else {
                String dimensionCode = surveyDimensionDao.findByName("疾病类型");
                String dimensionDetailCode = getCode();
                SurveyDimensionDetail surveyDimensionDetail = null;
                switch (Integer.parseInt(disea.toString())) {
//                  1.高血压 2糖尿病 3.高血压+糖尿病
                    case 1:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "高血压", 1, "疾病类型", 2, surveyCode);
                        break;
                    case 2:
                        surveyDimensionDetail = new SurveyDimensionDetail(dimensionDetailCode, dimensionCode, "糖尿病", 2, "疾病类型", 2, surveyCode);
                        break;
                }
                surveyDimensionDetailDao.save(surveyDimensionDetail);

                SurveyFilter surveyFilter = new SurveyFilter(getCode(), surveyCode, dimensionDetailCode);
                surveyFilterDao.save(surveyFilter);
            }
        }
        List<String> codes = getCount(surveyTarget.toString());
        int amount = codes.size();
        for (String code : codes) {
//            String code = patient.get("patient").toString();
            SurveyUser user = new SurveyUser(surveyCode, code, 0, 1, new Date(), new Date());
            surveyUserDao.save(user);
        }
        //            发送居民模板 send=1发送
        if ("1".equals(send)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String str = "{\"remark\":\"我们将按调查最终结果，优化健康服务。\",\"keyword1\":\"调查问卷\"}";
            JSONObject json = new JSONObject(str);
 /*           for (String code : codes) {
//            codes.stream().forEach(c -> {
//                Patient p = patientDao.findByCode(c);
                Patient p = patientDao.findByCode(code);
                String name = p.getName();
                String openId = p.getOpenid();
                json.put("keyword2", sdf.format(new Date()));
//                json.put("toUser", c);
                json.put("toUser", code);
                json.put("survey_id", surveyCode);
                json.put("first", name + "，您好！为了给您提供更好的家庭医生健康服务，现有一份问卷需要您填写。");
                logger.error("patient =======>" + code);
                logger.error("name =======>" + name);
                logger.error("openId =======>" + openId);

                //判断是否有openId,有发送没有则查找家人发送
                if (StringUtils.isNotBlank(p.getOpenid())) {
                    // 添加到发送队列
                    logger.error("json =======>" + json);
                    PushMsgTask.getInstance().putWxMsg(accessToken, 11, openId, name, json);
                } else {
                    JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getOpenid());
                    Patient member = (Patient) j.get("member");
                    if (StringUtils.isNotBlank(member.getOpenid())) {
                        String first = (String) json.get("first");
                        json.remove("first");
                        try {
                            json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()) + first);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        logger.error("没有opIn  json =======>" + json);
                        PushMsgTask.getInstance().putWxMsg(accessToken, 11, member.getOpenid(), member.getName(), json);
                    }
                }
//            });
            }*/
            new Thread() {
                public void run() {
                    for (String c : codes) {
                        Patient p = patientDao.findByCode(c);
                        String name = p.getName();
                        String openId = p.getOpenid();
                        json.put("keyword2", sdf.format(new Date()));
                        json.put("toUser", c);
                        json.put("represented", c);
                        json.put("survey_id", surveyCode);
                        String first = name + "，您好！为了给您提供更好的家庭医生健康服务，现有一份问卷需要您填写。";
                        json.put("first", first);
                        //判断是否判定openId,有没有发则查找家人发送
                        if (StringUtils.isNotBlank(p.getOpenid())) {
                            // 添加到发送队列
                            logger.error("json =======>" + json);
//                            PushMsgTask.getInstance().putWxMsg(accessToken, 11, openId, name, json);
                            PushMsgTask.getInstance().sendWeixinMessage(accessToken, 11, openId, name, json);
                        }
//                        else {
//                            JSONObject j = weiXinOpenIdUtils.getFamilyOpenId(p.getOpenid());
//                            Patient member = (Patient) j.get("member");
//                            if (StringUtils.isNotBlank(member.getOpenid())) {
//                                String first = (String) json.get("first");
//                                json.remove("first");
//                                try {
//                                    json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), member.getName()) + first);
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                logger.error("没有opIn  json =======>" + json);
////                                PushMsgTask.getInstance().putWxMsg(accessToken, 11, member.getOpenid(), member.getName(), json);
//                                PushMsgTask.getInstance().sendWeixinMessage(accessToken, 11, member.getOpenid(), member.getName(), json);
//                            }
//                        }
                        //发送代理人
                        JSONArray jsonArray = weiXinOpenIdUtils.getAgentOpenId(p.getCode(),p.getOpenid());
                        if(jsonArray!=null&&jsonArray.length()>0){
                            for (int i = 0;i<jsonArray.length();i++){
                                JSONObject j  = jsonArray.getJSONObject(i);
                                Patient member = (Patient) j.get("member");
                                if(StringUtils.isNotBlank(member.getOpenid())){
                                    json.remove("toUser");
                                    json.put("toUser",member.getCode());
                                    json.remove("first");
                                    try {
                                        json.put("first", weiXinOpenIdUtils.getTitleMes(p, j.getInt("relation"), p.getName()) + first);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    PushMsgTask.getInstance().sendWeixinMessage(weiXinAccessTokenUtils.getAccessToken(), 11, member.getOpenid(), p.getName(), json);
                                }
                            }
                        }
                    }
                }
            }.start();
        }
//       =====================================================
//     获取标签数组
        JSONArray lables = jsonStr.getJSONArray("label");
//        标签保存到wlyy_survey_label_info
        for (Object label : lables) {
            SurveyLabelInfo surveyLabelInfo = new SurveyLabelInfo();
            surveyLabelInfo.setCode(getCode());
            surveyLabelInfo.setRelationCode(surveyCode);
            surveyLabelInfo.setUseType(useType);
            surveyLabelInfo.setLabel(Integer.parseInt(label.toString()));
            SurveyLabelInfo ss = surveyLabelInfoDao.save(surveyLabelInfo);
        }
//        获取问题数组
        JSONArray questions = jsonStr.getJSONArray("questions");
        for (Object question : questions) {
            JSONObject tempQestion = new JSONObject(question.toString());
//            不分题型都有的属性
            String questionnaireCode = tempQestion.get("qstCode").toString();
            String title = tempQestion.get("title").toString();
            String comment = tempQestion.get("comment").toString();
            int type = Integer.parseInt(tempQestion.get("type").toString());
            int isRequired = Integer.parseInt(tempQestion.get("isRequired").toString());
            int sort = Integer.parseInt(tempQestion.get("sort").toString());
            int del = 1;
            String qstNextQuestion = null;
//            前提一定要有nextQuestion字段传入，没有为""
            if (!StringUtils.isEmpty(tempQestion.get("nextQuestion").toString())) {
//                            optionNextQuestion = tempOption.get("nextQuestion").toString();
                qstNextQuestion = surveyTemplateQuestionsDao.findBySort(templateCode, tempQestion.get("nextQuestion"));
                qstNextQuestion = (qstNextQuestion == null ? "0" : qstNextQuestion);
            }
            switch (type) {
                case 0:
//                    单选
                    SurveyQuestionnaire surveyQuestionnaire = new SurveyQuestionnaire();
                    surveyQuestionnaire.setCode(questionnaireCode);
                    surveyQuestionnaire.setTitle(title);
                    surveyQuestionnaire.setQuestionComment(comment);
                    surveyQuestionnaire.setQuestionType(type);
                    surveyQuestionnaire.setSurveyCode(surveyCode);
                    surveyQuestionnaire.setIsRequired(isRequired);
                    surveyQuestionnaire.setDel(del);
                    surveyQuestionnaire.setSort(sort);
                    surveyQuestionnaire.setCreateTime(new Date());
                    surveyQuestionnaire.setUpdateTime(new Date());
                    //                   单选没有最大最小选项数及题目逻辑跳转
                    surveyQuestionnaire.setMinNum(null);
                    surveyQuestionnaire.setMaxNum(null);
                    surveyQuestionnaire.setQuestionCodeNext(qstNextQuestion);

                    surveyQuestionnaireDao.save(surveyQuestionnaire);
                    //                        =======================选项保存=========================
                    //                选择题
                    JSONArray options = new JSONArray(tempQestion.get("options").toString());
                    for (Object option : options) {
//                        String optionCode = getCode();
                        JSONObject tempOption = new JSONObject(option.toString());
                        String optionCode = tempOption.get("optCode").toString();
                        int haveComment = Integer.parseInt(tempOption.get("haveComment").toString());
                        String optionComment = tempOption.get("content").toString();
                        int required = Integer.parseInt(tempOption.get("isRequired").toString());
                        int optionSort = Integer.parseInt(tempOption.get("sort").toString());
                        int optionDel = 1;
                        String optionNextQuestion = null;
                        if (!StringUtils.isEmpty(tempOption.get("nextQuestion").toString())) {
//                            optionNextQuestion = tempOption.get("nextQuestion").toString();
                            optionNextQuestion = surveyTemplateQuestionsDao.findBySort(templateCode, tempOption.get("nextQuestion"));
                            optionNextQuestion = (optionNextQuestion == null ? "0" : optionNextQuestion);
                        }
//                        自主创建，插入表
                        SurveyQuestionnaireOptions surveyQuestionnaireOptions = new SurveyQuestionnaireOptions(optionCode, haveComment, questionnaireCode, optionComment,
                                surveyCode, optionNextQuestion, required, optionSort, optionDel);
                       /* surveyQuestionnaireOptions.setCode(optionCode);
                        surveyQuestionnaireOptions.setHaveComment(haveComment);
                        surveyQuestionnaireOptions.setQuestionnaireCode(questionnaireCode);
                        surveyQuestionnaireOptions.setContent(optionComment);
                        surveyQuestionnaireOptions.setSurveyCode(surveyCode);
                        surveyQuestionnaireOptions.setQuestionCodeNext(optionNextQuestion);
                        surveyQuestionnaireOptions.setIsRequired(required);
                        surveyQuestionnaireOptions.setSort(optionSort);
                        surveyQuestionnaireOptions.setDel(optionDel);*/
                        surveyQuestionnaireOptionsDao.save(surveyQuestionnaireOptions);

                        //                单选题保存到统计表
                        String statisticsCode = getCode();
                        String questionTitle = surveyQuestionnaireDao.findByIdAndQstId(surveyCode, questionnaireCode).getTitle();
                        String optcontent = surveyQuestionnaireOptionsDao.findByRelationCode(surveyCode, questionnaireCode, optionCode).getContent();
                        SurveyStatistics statistics = new SurveyStatistics(statisticsCode, surveyCode, questionnaireCode, questionTitle, optionCode, 0, optcontent, haveComment, type, sort, optionSort);
                        surveyStatisticsDao.save(statistics);
                    }
                    break;
                case 1:
//            多选特有属性
                    Integer maxOptions = null;
                    Integer minOptions = null;
                    if (!StringUtils.isEmpty(tempQestion.get("minOptions").toString())) {
                        minOptions = Integer.parseInt(tempQestion.get("minOptions").toString());
                    }
                    if (!StringUtils.isEmpty(tempQestion.get("maxOptions").toString())) {
                        maxOptions = Integer.parseInt(tempQestion.get("maxOptions").toString());
                    }
                    SurveyQuestionnaire surveyQuestionnaire1 = new SurveyQuestionnaire();
                    surveyQuestionnaire1.setCode(questionnaireCode);
                    surveyQuestionnaire1.setTitle(title);
                    surveyQuestionnaire1.setQuestionComment(comment);
                    surveyQuestionnaire1.setQuestionType(type);
                    surveyQuestionnaire1.setSurveyCode(surveyCode);
                    surveyQuestionnaire1.setIsRequired(isRequired);
                    surveyQuestionnaire1.setMinNum(minOptions);
                    surveyQuestionnaire1.setMaxNum(maxOptions);
                    surveyQuestionnaire1.setSort(sort);
                    surveyQuestionnaire1.setQuestionCodeNext(qstNextQuestion);
                    surveyQuestionnaire1.setDel(del);
                    surveyQuestionnaire1.setCreateTime(new Date());
                    surveyQuestionnaire1.setUpdateTime(new Date());

                    surveyQuestionnaireDao.save(surveyQuestionnaire1);

//                        =======================选项保存=========================
                    //                选择题
                    JSONArray options1 = new JSONArray(tempQestion.get("options").toString());
                    for (Object option : options1) {
//                        String optionCode = getCode();
                        JSONObject tempOption = new JSONObject(option.toString());
                        String optionCode = tempOption.get("optCode").toString();
                        int haveComment = Integer.parseInt(tempOption.get("haveComment").toString());
                        String optionComment = tempOption.get("content").toString();
                        int required = Integer.parseInt(tempOption.get("isRequired").toString());
                        int optionSort = Integer.parseInt(tempOption.get("sort").toString());
                        int optionDel = 1;
                        String optionNextQuestion = null;
                        if (!StringUtils.isEmpty(tempOption.get("nextQuestion").toString())) {
//                            optionNextQuestion = tempOption.get("nextQuestion").toString();
                            optionNextQuestion = surveyTemplateQuestionsDao.findBySort(templateCode, tempOption.get("nextQuestion"));
                            optionNextQuestion = (optionNextQuestion == null ? "0" : optionNextQuestion);
                        }

//                        自主创建，插入表
                        SurveyQuestionnaireOptions surveyQuestionnaireOptions = new SurveyQuestionnaireOptions();
                        surveyQuestionnaireOptions.setCode(optionCode);
                        surveyQuestionnaireOptions.setHaveComment(haveComment);
                        surveyQuestionnaireOptions.setQuestionnaireCode(questionnaireCode);
                        surveyQuestionnaireOptions.setContent(optionComment);
                        surveyQuestionnaireOptions.setSurveyCode(surveyCode);
                        surveyQuestionnaireOptions.setQuestionCodeNext(optionNextQuestion);
                        surveyQuestionnaireOptions.setIsRequired(required);
                        surveyQuestionnaireOptions.setSort(optionSort);
                        surveyQuestionnaireOptions.setDel(optionDel);

                        surveyQuestionnaireOptionsDao.save(surveyQuestionnaireOptions);

                        //                多选题保存到统计表
                        String statisticsCode = getCode();
                        String questionTitle = surveyQuestionnaireDao.findByIdAndQstId(surveyCode, questionnaireCode).getTitle();
                        String optcontent = surveyQuestionnaireOptionsDao.findByRelationCode(surveyCode, questionnaireCode, optionCode).getContent();
                        SurveyStatistics statistics = new SurveyStatistics(statisticsCode, surveyCode, questionnaireCode, questionTitle, optionCode, 0, optcontent, haveComment, type, sort, optionSort);
                        surveyStatisticsDao.save(statistics);
                    }
//                        ===============================================================
                    break;
                case 2:
//            问答特有属性
                    /*String nextQuestion = null;
                    if (StringUtils.isEmpty(tempQestion.get("nextQuestion").toString())) {
                        nextQuestion = tempQestion.get("nextQuestion").toString();
                    }else {
                        nextQuestion = surveyTemplateQuestionsDao.findBySort(templateCode,tempQestion.get("nextQuestion"));
                    }*/
                    SurveyQuestionnaire surveyQuestionnaire2 = new SurveyQuestionnaire();
                    surveyQuestionnaire2.setCode(questionnaireCode);
                    surveyQuestionnaire2.setTitle(title);
                    surveyQuestionnaire2.setQuestionComment(comment);
                    surveyQuestionnaire2.setQuestionType(type);
                    surveyQuestionnaire2.setSurveyCode(surveyCode);
                    surveyQuestionnaire2.setIsRequired(isRequired);
//                   单选没有最大最小选项数
                    surveyQuestionnaire2.setMinNum(null);
                    surveyQuestionnaire2.setMaxNum(null);
                    surveyQuestionnaire2.setSort(sort);
                    surveyQuestionnaire2.setQuestionCodeNext(qstNextQuestion);
                    surveyQuestionnaire2.setDel(del);
                    surveyQuestionnaire2.setUpdateTime(new Date());
                    surveyQuestionnaire2.setCreateTime(new Date());

                    surveyQuestionnaireDao.save(surveyQuestionnaire2);

                    //                问答题保存到统计表(只负责更改数量不负责创建)
                    String statisticsCode = getCode();
                    String questionTitle = surveyQuestionnaireDao.findByIdAndQstId(surveyCode, questionnaireCode).getTitle();
                    SurveyStatistics statistics = new SurveyStatistics(statisticsCode, surveyCode, questionnaireCode, questionTitle, null, 0, null, null, type, sort, null);
                    surveyStatisticsDao.save(statistics);
                    break;
            }

        }
//        保存到问卷
        Survey survey = new Survey();
        survey.setCode(surveyCode);
        survey.setTitle(surveyName);
        survey.setSurveyComment(surveyComment);
        survey.setCreater(doctor);
        survey.setTemplateCode(templateCode);
        survey.setStatus(status);
        survey.setAmount(amount);
        survey.setCreateTime(new Date());
        survey.setUpdateTime(new Date());
        surveyDao.save(survey);
        return surveyCode;
    }

    public JSONArray getQuestionnaireList(int pageNo, int pageSize) throws Exception {
        JSONArray jsonArray = new JSONArray();
        // 排序
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = new PageRequest(pageNo - 1, pageSize, sort);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Page<Survey> surveys = surveyDao.findAll(pageRequest);
        List<Survey> arrays = surveys.getContent();
        for (Survey arr : arrays) {
            Map<String, Object> sur = new HashMap<>();
            String code = arr.getCode();
            String title = arr.getTitle();
            String doctor = arr.getCreater();
            String comment = arr.getSurveyComment();
            String createTime = sdf.format(arr.getCreateTime());
//            String updateTime = sdf.format(arr.getUpdateTime());
            //        查询医生信息
            Doctor doc = doctorDao.findByCode(doctor);
            String name = doc.getName();
            String photo = doc.getPhoto();
            String dept = doc.getDeptName();

            int amount = arr.getAmount();
            //查询居民回答的反馈率
            int complete = surveyUserDao.findBySurveyCode(code);

            sur.put("code", code);
            sur.put("name", name);
            sur.put("photo", photo);
            sur.put("deptName", dept);
            sur.put("percent", (Math.round(((float) complete / amount) * 100)) + "%");
            sur.put("title", title);
            sur.put("comment", comment);
            sur.put("createTime", createTime);
//            sur.put("updateTime", updateTime);
            sur.put("complete", complete);
            sur.put("amount", amount);
            jsonArray.put(sur);
        }

        return jsonArray;
    }

    public JSONObject getQuestionnaireSummary(String id) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Survey survey = surveyDao.findById(id);
        String creater = survey.getCreater();
        Date createTime = survey.getCreateTime();
        int amount = survey.getAmount();
        String comment = survey.getSurveyComment();
        String title = survey.getTitle();
        int status = survey.getStatus();
        List<String> targets = surveyDimensionDetailDao.findByCode(id);
        Map<String, Object> surveyTarget = new HashMap<>();
        for (String target : targets) {
            List<String> labels = surveyDimensionDetailDao.findByCode(id, target);
            List tags = new ArrayList();
            for (String label : labels) {
                tags.add(label);
            }
            switch (target) {
                case "疾病类型":
                    target = "disease";
                    break;
                case "服务类型":
                    target = "service";
                    break;
                case "健康状况":
                    target = "healthCondition";
                    break;
                case "性别":
                    target = "sex";
                    break;

            }
            surveyTarget.put(target, tags);
        }
        int[] label = surveyLabelInfoDao.findByRelationCode(id);
        String[] labels = new String[label.length];
        for (int i = 0; i < label.length; i++) {
            switch (label[i]) {
                case 1:
                    labels[i] = "满意度";
                    break;
                case 2:
                    labels[i] = "糖尿病";
                    break;
                case 3:
                    labels[i] = "高血压";
                    break;
                case 4:
                    labels[i] = "生活日常";
                    break;
            }
        }
//        查询该问卷回答人数
//        int complete = surveyUserDao.findBySurveyCode(id);
        int complete = surveyUserDao.findBySurveyCode(id);
        Map<String, Object> map = new HashMap<>();
//        获取创建者信息
        Doctor doctor = doctorDao.findByCode(creater);
        String name = doctor.getName();
        String deptName = doctor.getDeptName();
        String photo = doctor.getPhoto();
        map.put("name", name);
        map.put("deptName", deptName);
        map.put("photo", photo);
        map.put("createTime", sdf.format(createTime));
        map.put("amount", amount);
        map.put("complete", complete);
        map.put("percent", (Math.round(((float) complete / amount) * 100)) + "%");
        map.put("comment", comment);
        map.put("title", title);
        map.put("status", status);
        map.put("label", labels);
        map.put("surveyTarget", surveyTarget);
        JSONObject jsonObject = new JSONObject(map);
        return jsonObject;
    }

    public JSONObject getQuestionnaireDetail(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
//问卷信息
        Survey survey = surveyDao.findById(id);
        int[] label = surveyLabelInfoDao.findByRelationCode(id);
        String[] labels = new String[label.length];
        for (int i = 0; i < label.length; i++) {
            switch (label[i]) {
                case 1:
                    labels[i] = "满意度";
                    break;
                case 2:
                    labels[i] = "糖尿病";
                    break;
                case 3:
                    labels[i] = "高血压";
                    break;
                case 4:
                    labels[i] = "生活日常";
                    break;
            }
        }

//问题信息
        List<SurveyQuestionnaire> surveyQuestionnair = surveyQuestionnaireDao.findById(id);
        List questions = new ArrayList();
//        问题信息
        for (SurveyQuestionnaire questionnair : surveyQuestionnair) {
            Map<String, Object> question = new HashMap<>();
            String qstcode = questionnair.getCode();
            String title = questionnair.getTitle();
            int isRequired = questionnair.getIsRequired();
            int sort = questionnair.getSort();
            int type = questionnair.getQuestionType();
            if (questionnair.getMaxNum() != null) {
                int maxNum = questionnair.getMaxNum();
                question.put("maxNum", maxNum);
            }
            if (questionnair.getMinNum() != null) {
                int minNum = questionnair.getMinNum();
                question.put("minNum", minNum);
            }
            if (questionnair.getQuestionComment() != null) {
                String comment = questionnair.getQuestionComment();
                question.put("comment", comment);
            }
            if (questionnair.getQuestionCodeNext() != null) {
                String next = questionnair.getQuestionCodeNext();
                SurveyQuestionnaire sq = surveyQuestionnaireDao.findByIdAndQstId(id, next);
                question.put("nextQuestion", sq == null ? 0 : sq.getSort());
            }

//            List<SurveyQuestionnaireOptions> options = surveyQuestionnaireOptionsDao.findById(qstcode);
            List<SurveyQuestionnaireOptions> options = surveyQuestionnaireOptionsDao.findByIdAndQstCode(id, qstcode);
            List optList = new ArrayList();
            for (SurveyQuestionnaireOptions option : options) {
                Map<String, Object> opt = new HashMap<>();
                String conetent = option.getContent();
                int haveComment = option.getHaveComment();
                int required = option.getIsRequired();
                int st = option.getSort();
                if (option.getQuestionCodeNext() != null) {
                    String next = option.getQuestionCodeNext();
                    SurveyQuestionnaire sq = surveyQuestionnaireDao.findByIdAndQstId(id, next);
                    System.out.println("=============qstcode============== " + qstcode);
                    System.out.println("=============optCode============== " + option.getCode());
                    System.out.println("=============sq============== " + sq);
                    System.out.println("=============next============== " + next);
                    opt.put("nextQuestion", sq == null ? 0 : sq.getSort());
                }
                opt.put("content", conetent);
                opt.put("sort", st);
                opt.put("haveComment", haveComment);
                opt.put("isRequired", required);
                optList.add(opt);
            }

            question.put("title", title);
            question.put("type", type);
            question.put("isRequired", isRequired);
            question.put("sort", sort);
            question.put("options", optList);
            questions.add(question);
        }

        String surveyComment = survey.getSurveyComment();
        String surveyTitle = survey.getTitle();

        jsonObject.put("title", surveyTitle);
        jsonObject.put("comment", surveyComment);
        jsonObject.put("questions", questions);
        jsonObject.put("label", labels);
        return jsonObject;
    }

    public int modifyQuestionnaireStatus(String id) throws Exception {
        Survey survey = surveyDao.findById(id);
        int status = survey.getStatus();
        if (status > 1) {
            status = 1;
            surveyDao.modifyStatus(status, id);
        } else {
            status = 2;
            surveyDao.modifyStatus(status, id);
        }
        return status;
    }

    public JSONObject getAnswers(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
//一个问卷内的所有问题
        List<SurveyQuestionnaire> questions = surveyQuestionnaireDao.findById(id);
        if (questions.size() == 0) {
            return jsonObject;
        }
        List qstList = new ArrayList();
        for (SurveyQuestionnaire question : questions) {
//            新造对象
            Map<String, Object> qst = new HashMap<>();
            String qstcode = question.getCode();
            String title = question.getTitle();
            int type = question.getQuestionType();
//            有效答了该题的人数
            /*int amount = 0;
            int[] sum = surveyStatisticsDao.findByIdAndQstId(id, qstcode);
            for (int count : sum) {
                amount += count;
            }*/
            int amount = 0;
            if (type == 2) {
//          问卷答案表有效(去重)答题人数
                amount = surveyAnswersDao.countByRelationCode(id, qstcode);
            } else {
//          问卷选项答案表有效(去重)答题人数
                amount = surveyOptionAnswersDao.countByRelationCode(id, qstcode);
            }

            qst.put("amount", amount);
            qst.put("qstcode", qstcode);
            qst.put("title", title);
            qst.put("type", type);
//            一个问题内的所有选项
//            List<SurveyQuestionnaireOptions> options = surveyQuestionnaireOptionsDao.findById(qstcode);
            List<SurveyQuestionnaireOptions> options = surveyQuestionnaireOptionsDao.findByIdAndQstCode(id, qstcode);
            List optList = new ArrayList();
            for (SurveyQuestionnaireOptions option : options) {
                Map<String, Object> opt = new HashMap<>();
                String optcode = option.getCode();
                String optTitle = option.getContent();
                int haveComment = option.getHaveComment();
                int count = surveyStatisticsDao.findByAllId(id, qstcode, optcode);
                opt.put("optcode", optcode);
                opt.put("option", optTitle);
                opt.put("count", count);
                opt.put("percent", (Math.round(((float) count / amount) * 100)) + "%");
                opt.put("haveComment", haveComment);
                optList.add(opt);
            }
            qst.put("options", optList);
            qstList.add(qst);
        }
        jsonObject.put("questions", qstList);
        return jsonObject;
    }

    public JSONObject getOptionsComment(String id, String questionId, String optionId, int pageNo, int pageSize) throws Exception {
        JSONObject jsonObject = new JSONObject();
        SurveyQuestionnaire question = surveyQuestionnaireDao.findByIdAndQstId(id, questionId);
        Sort sort = new Sort(Sort.Direction.ASC, "createTime");
        PageRequest request = new PageRequest(pageNo - 1, pageSize, sort);

        if (!StringUtils.isEmpty(optionId)) {
//            查看选择题详细答案
            SurveyQuestionnaireOptions opt = surveyQuestionnaireOptionsDao.findByRelationCode(id, questionId, optionId);
            String option = opt.getContent();
            jsonObject.put("option", option);
//        获取同一个选项的所有回答的说明(分页？)
            Page<String> optionComment = surveyOptionAnswersDao.findByRelationCode(id, questionId, optionId, request);
            jsonObject.put("content", optionComment.getContent());
            int amount = surveyOptionAnswersDao.findByRelationCode(id, questionId, optionId);
            jsonObject.put("amount", amount);
        } else {
//            查看问答题答案(分页?)
            Page<String> answer = surveyAnswersDao.findByRelationCode(id, questionId, request);
            jsonObject.put("content", answer.getContent());
            int amount = surveyAnswersDao.findByRelationCode(id, questionId);
            jsonObject.put("amount", amount);
        }

        String title = question.getTitle();
        jsonObject.put("title", title);
        return jsonObject;
    }

    public List getTemplateList(int pageNo, int pageSize) throws Exception {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest request = new PageRequest(pageNo - 1, pageSize, sort);
        List<SurveyTemplates> templates = surveyTemplatesDao.findAlls(request);
        List list = new ArrayList();
        for (SurveyTemplates template : templates) {
            Map<String, Object> tempMap = new HashMap();
            String title = template.getTitle();
            String templateId = template.getCode();
            String comment = template.getTemplateComment();
            int[] label = surveyLabelInfoDao.findByRelationCode(templateId);


            String[] labels = new String[label.length];
            for (int i = 0; i < label.length; i++) {
                switch (label[i]) {
                    case 1:
                        labels[i] = "满意度";
                        break;
                    case 2:
                        labels[i] = "糖尿病";
                        break;
                    case 3:
                        labels[i] = "高血压";
                        break;
                    case 4:
                        labels[i] = "生活日常";
                        break;
                }
            }

            tempMap.put("templateId", templateId);
            tempMap.put("title", title);
            if (comment.length() > 50) {
                comment = comment.substring(0, 49);
            }
            tempMap.put("comment", comment);
            tempMap.put("label", labels);
            list.add(tempMap);
        }
        return list;
    }

    public List getTemplateLabel() throws Exception {
        List list = new ArrayList();
        List<SystemDict> labels = systemDictDao.findByDictName("SURVEY_LABEL");
        for (SystemDict label : labels) {
            Map<String, Object> map = new HashMap();
            String code = label.getCode();
            String value = label.getValue();
            map.put("code", code);
            map.put("value", value);
            list.add(map);
        }
        return list;
    }

    public JSONObject getQuestionList(String title, int pageNo, int pageSize) throws Exception {
        JSONObject jsonObject = new JSONObject();
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest request = new PageRequest(pageNo - 1, pageSize, sort);
        List<SurveyQuestions> questions = new ArrayList<>();
        if (StringUtils.isEmpty(title)) {
            questions = surveyQuestionsDao.findByTitle(request);
        } else {
            questions = surveyQuestionsDao.findByTitle("%" + title + "%", request);
        }
        List list = new ArrayList();
        for (SurveyQuestions question : questions) {
            Map<String, Object> map = new HashMap<>();
            String code = question.getCode();
            String qstTitle = question.getTitle();
            if (question.getQuestionComment() != null) {
                String comment = question.getQuestionComment();
                map.put("comment", comment);
            }
            int isRequired = question.getIsRequired();
            int questionType = question.getQuestionType();
            if (questionType != 2) {
//                获取选择题选项值
                List<SurveyQuestionsOptions> options = surveyQuestionsOptionsDao.findById(code);
                List opts = new ArrayList();
                for (SurveyQuestionsOptions option : options) {
                    Map<String, Object> opt = new HashMap<>();
                    opt.put("optCode", option.getCode());
                    opt.put("content", option.getContent());
                    opt.put("haveComment", option.getHaveComment());
                    opt.put("isRequired", option.getIsRequired());
                    opts.add(opt);

                }
                map.put("options", opts);
            }
            map.put("code", code);
            map.put("title", qstTitle);
            map.put("isRequired", isRequired);
            map.put("questionType", questionType);
            list.add(map);
        }
        jsonObject.put("questions", list);
        return jsonObject;
    }

    public List getTemplateByLabelOrTitle(String name, int pageNo, int pageSize) throws Exception {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest request = new PageRequest(pageNo - 1, pageSize, sort);
        String sql = "SELECT DISTINCT  s.code  " +
                " FROM System_dict s WHERE  s.dict_name ='SURVEY_LABEL' and s.value LIKE '%" + name +
                "%'";
        List<Map<String, Object>> labels = jdbcTemplate.queryForList(sql);
        List<SurveyTemplates> surveyTemplates = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (labels.size() == 0) {
//            模板标题
            String cql = "select  distinct t.* from wlyy_survey_templates t where t.del = 1 and t.title like '%" + name + "%' ";
            List<Map<String, Object>> surveyTemp = jdbcTemplate.queryForList(cql);
            for (Map<String, Object> temp : surveyTemp) {
                String create = temp.get("create_time").toString();
                String update = temp.get("update_time").toString();

                Date createTime = sdf.parse(create);
                Date updateTime = sdf.parse(update);
                SurveyTemplates tem = new SurveyTemplates(temp.get("code").toString(),
                        temp.get("title").toString(), temp.get("template_comment").toString(), temp.get("creater").toString(),
                        Integer.parseInt(temp.get("del").toString()), createTime, updateTime);
                surveyTemplates.add(tem);
            }
        } else {
            for (Map<String, Object> label : labels) {
//                if ("SURVEY_LABEL".equals(label.get("dict_name").toString())) {
                surveyTemplates = surveyLabelInfoDao.findByLabel(Integer.parseInt(label.get("code").toString()));
//                }

            }
        }

        List list = new ArrayList();
        for (SurveyTemplates template : surveyTemplates) {
            Map<String, Object> map = new HashMap<>();
            String tempCode = template.getCode();
            String title = template.getTitle();
            String comment = template.getTemplateComment();
            Date createTime = template.getCreateTime();
            int[] label = surveyLabelInfoDao.findByRelationCode(tempCode);
            String[] tags = new String[label.length];
            for (int i = 0; i < label.length; i++) {
                switch (label[i]) {
                    case 1:
                        tags[i] = "满意度";
                        break;
                    case 2:
                        tags[i] = "糖尿病";
                        break;
                    case 3:
                        tags[i] = "高血压";
                        break;
                    case 4:
                        tags[i] = "生活日常";
                        break;
                }
            }
            map.put("tempCode", tempCode);
            map.put("title", title);
            map.put("createTime", sdf.format(createTime));
            map.put("label", tags);
            map.put("comment", comment);
            list.add(map);
        }
        return list;
    }

    public List getTemplateByLabel(int pageNo, int pageSize, String labels) throws Exception {
        if (StringUtils.isEmpty(labels)) {
            Sort sort = new Sort(Sort.Direction.DESC, "createTime");
            PageRequest request = new PageRequest(pageNo - 1, pageSize, sort);
            List<SurveyTemplates> templates = surveyTemplatesDao.findAlls(request);
            List list = new ArrayList();
            for (SurveyTemplates template : templates) {
                Map<String, Object> tempMap = new HashMap();
                String title = template.getTitle();
                String templateId = template.getCode();
                String comment = template.getTemplateComment();
                int[] label = surveyLabelInfoDao.findByRelationCode(templateId);

                String[] tags = new String[label.length];
                for (int i = 0; i < label.length; i++) {
                    switch (label[i]) {
                        case 1:
                            tags[i] = "满意度";
                            break;
                        case 2:
                            tags[i] = "糖尿病";
                            break;
                        case 3:
                            tags[i] = "高血压";
                            break;
                        case 4:
                            tags[i] = "生活日常";
                            break;
                    }
                }

                tempMap.put("templateId", templateId);
                tempMap.put("title", title);
                if (comment.length() > 50) {
                    comment = comment.substring(0, 49);
                }
                tempMap.put("comment", comment);
                tempMap.put("label", tags);
                list.add(tempMap);
            }
            return list;
        } else {
            List list = new ArrayList();
            pageNo -= 1;
            String sql = "SELECT  DISTINCT t.* " +
                    " FROM wlyy_survey_templates t,wlyy_survey_label_info s  " +
                    " WHERE t.code = s.relation_code  " +
                    " AND s.use_type= 0 " +
                    " AND t.del = 1 " +
                    " AND s.label IN (" + labels +
                    ")  " +
                    " ORDER by t.create_time DESC " +
                    " limit " + pageNo +
                    "," + pageSize;
            List<Map<String, Object>> listMap = jdbcTemplate.queryForList(sql);
            for (Map<String, Object> template : listMap) {
                Map<String, Object> map = new HashMap();
                String code = template.get("code").toString();
                String title = template.get("title").toString();
                String comment = template.get("template_comment").toString();
                if (comment.length() > 50) {
                    comment = comment.substring(0, 49);
                }
//           查询标签
                int[] label = surveyLabelInfoDao.findByRelationCode(code);
                String[] tags = new String[label.length];
                for (int i = 0; i < label.length; i++) {
                    switch (label[i]) {
                        case 1:
                            tags[i] = "满意度";
                            break;
                        case 2:
                            tags[i] = "糖尿病";
                            break;
                        case 3:
                            tags[i] = "高血压";
                            break;
                        case 4:
                            tags[i] = "生活日常";
                            break;
                    }
                }
                map.put("title", title);
                map.put("templateId", code);
                map.put("comment", comment);
                map.put("label", tags);
                list.add(map);
            }
            return list;
        }

    }

    public Map<String, Object> getTemplateById(String code) throws Exception {
        Map<String, Object> tempMap = new HashMap();
        SurveyTemplates template = surveyTemplatesDao.findById(code);
        String title = template.getTitle();
        String comment = template.getTemplateComment();
        int[] label = surveyLabelInfoDao.findByRelationCode(code);
        String[] labels = new String[label.length];
        for (int i = 0; i < label.length; i++) {
            switch (label[i]) {
                case 1:
                    labels[i] = "满意度";
                    break;
                case 2:
                    labels[i] = "糖尿病";
                    break;
                case 3:
                    labels[i] = "高血压";
                    break;
                case 4:
                    labels[i] = "生活日常";
                    break;
            }
        }
        tempMap.put("templateId", code);
        tempMap.put("title", title);
        tempMap.put("comment", comment);
        tempMap.put("label", labels);
        return tempMap;
    }

    public JSONObject getTemplateDetail(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
//问卷信息
        SurveyTemplates template = surveyTemplatesDao.findById(id);

        int[] label = surveyLabelInfoDao.findByRelationCode(id);
        String[] labels = new String[label.length];
        for (int i = 0; i < label.length; i++) {
            switch (label[i]) {
                case 1:
                    labels[i] = "满意度";
                    break;
                case 2:
                    labels[i] = "糖尿病";
                    break;
                case 3:
                    labels[i] = "高血压";
                    break;
                case 4:
                    labels[i] = "生活日常";
                    break;
            }
        }
//问题信息
        List<SurveyTemplateQuestions> surveyQuestionnair = surveyTemplateQuestionsDao.findById(id);
        List questions = new ArrayList();
//        问题信息
        for (SurveyTemplateQuestions questionnair : surveyQuestionnair) {
            Map<String, Object> question = new HashMap<>();
            String qstcode = questionnair.getCode();
            String title = questionnair.getTitle();
            int isRequired = questionnair.getIsRequired();
            int sort = questionnair.getSort();
            String comment = questionnair.getQuestionComment();
            int type = questionnair.getQuestionType();

            List<SurveyTemplateOptions> options = surveyTemplateOptionsDao.findById(qstcode, id);
            List optList = new ArrayList();
            for (SurveyTemplateOptions option : options) {
                Map<String, Object> opt = new HashMap<>();
                String conetent = option.getContent();
                String optCode = option.getCode();
                int haveComment = option.getHaveComment();
                int required = option.getIsRequired();
                int optsort = option.getSort();
                if (!StringUtils.isEmpty(option.getQuestionCodeNext())) {
                    String next = option.getQuestionCodeNext();
                    SurveyTemplateQuestions tempQst = surveyTemplateQuestionsDao.findById(id, next);
//                    跳题结束
                    opt.put("nextQuestion", tempQst == null ? 0 : tempQst.getSort());
                }

                opt.put("optCode", optCode);
                opt.put("isRequired", required);
                opt.put("content", conetent);
                opt.put("sort", optsort);
                opt.put("haveComment", haveComment);
                optList.add(opt);
            }

            question.put("title", title);
//            增加返回模板问题编码
            question.put("qstCode", qstcode);
            question.put("isRequired", isRequired);
            question.put("comment", comment);
            question.put("type", type);
            question.put("options", optList);
            question.put("sort", sort);
            question.put("maxNum", questionnair.getMaxNum());
            question.put("minNum", questionnair.getMinNum());
            if (!StringUtils.isEmpty(questionnair.getQuestionCodeNext())) {
                String next = questionnair.getQuestionCodeNext();
                SurveyTemplateQuestions tempQst = surveyTemplateQuestionsDao.findById(id, next);
                question.put("nextQuestion", tempQst == null ? 0 : tempQst.getSort());
            }


            questions.add(question);
        }

        String tempComment = template.getTemplateComment();
        String tempTitle = template.getTitle();

        jsonObject.put("title", tempTitle);
        jsonObject.put("comment", tempComment);
        jsonObject.put("label", labels);
        jsonObject.put("questions", questions);
        return jsonObject;
    }

    /**
     * 保存为新模板
     *
     * @param code        问卷编码
     * @param modifyTitle 标题重复后修改后的标题（第一次为null）
     * @return
     * @throws Exception
     */
    public int savaSurveyAsTemplate(String code, String modifyTitle) throws Exception {
        String tempCode = getCode();
        Survey survey = surveyDao.findById(code);
        String title = survey.getTitle();
        String templateComment = survey.getSurveyComment();
        String creater = survey.getCreater();
        Date createTime = survey.getCreateTime();
        Date updateTime = survey.getUpdateTime();
        //        查询问卷标题重复情况
        int number = 0;
        if (StringUtils.isEmpty(modifyTitle)) {
            number = surveyTemplatesDao.distinctByTitle(title);
        } else {
            number = surveyTemplatesDao.distinctByTitle(modifyTitle);
            title = modifyTitle;
        }
        if (number != 0 && StringUtils.isEmpty(modifyTitle)) {
            int likeNum = surveyTemplatesDao.distinctLikeTitle(title + "%");
            return likeNum;
        }
        if (number != 0 && !StringUtils.isEmpty(modifyTitle)) {
            int likeNum = surveyTemplatesDao.distinctLikeTitle(modifyTitle + "%");
            return likeNum;
        }
        SurveyTemplates surveyTemplates = new SurveyTemplates(tempCode, title, templateComment, creater, 1, createTime, updateTime);
//        保存模板信息
        surveyTemplatesDao.save(surveyTemplates);
        List<SurveyLabelInfo> surveyLabelInfos = surveyLabelInfoDao.findByCode(code);
        for (SurveyLabelInfo surveyLabelInfo : surveyLabelInfos) {
//        保存模板标签信息
            SurveyLabelInfo surveyLabelInfo1 = new SurveyLabelInfo(getCode(), tempCode, 0, surveyLabelInfo.getLabel());
            surveyLabelInfoDao.save(surveyLabelInfo1);
        }
        List<SurveyQuestionnaire> surveyQuestionnaires = surveyQuestionnaireDao.findById(survey.getCode());
        for (SurveyQuestionnaire question : surveyQuestionnaires) {
            String qstCode = getCode();
            String qstTitle = question.getTitle();
            String qstComment = question.getQuestionComment();
            Integer qstType = question.getQuestionType();
            Integer isRequired = question.getIsRequired();
            Integer minNum = question.getMinNum();
            Integer maxNum = question.getMaxNum();
            Date createTiem = question.getCreateTime();
            Date updateTiem = question.getUpdateTime();
            Integer sort = question.getSort();
            Integer de = question.getDel();
            String next = question.getQuestionCodeNext();
            SurveyTemplateQuestions surveyTemplateQuestions = new SurveyTemplateQuestions(qstCode, qstTitle, qstComment, qstType, tempCode, isRequired, minNum, maxNum, sort, next, null, de, createTiem, updateTiem);
            //            保存问题到模板问题表
            surveyTemplateQuestionsDao.save(surveyTemplateQuestions);
            if (qstType != 2) {
                List<SurveyQuestionnaireOptions> surveyQuestionnaireOptions = surveyQuestionnaireOptionsDao.findByIdAndQstCode(code, question.getCode());
                for (SurveyQuestionnaireOptions option : surveyQuestionnaireOptions) {
                    SurveyTemplateOptions surveyTemplateOptions = new SurveyTemplateOptions(getCode(), option.getHaveComment(), qstCode, option.getContent(),
                            tempCode, option.getQuestionCodeNext(), null, option.getIsRequired(), option.getSort(), option.getDel());
                    //         保存到模板选项表   survey_template_options
                    surveyTemplateOptionsDao.save(surveyTemplateOptions);
                }

            }


        }
        return 0;
    }

    //根据模板创建的问卷再次保存为问卷时是修改模板
    public int modifyTemplate(String code, String templateCode, String modifyTitle) throws Exception {
        Survey survey = surveyDao.findById(code);
        String title = survey.getTitle();
        String templateComment = survey.getSurveyComment();
//        查询问卷标题重复情况
//       int number = surveyTemplatesDao.distinctByTitle(title);
        int number = 0;
        if (StringUtils.isEmpty(modifyTitle)) {
            number = surveyTemplatesDao.distinctByTitle(title);
        } else {
            number = surveyTemplatesDao.distinctByTitle(modifyTitle);
            title = modifyTitle;
        }
        if (number != 1 && StringUtils.isEmpty(modifyTitle)) {
            int likeNum = surveyTemplatesDao.distinctLikeTitle(title + "%");
            return likeNum;
        }
        if (number != 0 && !StringUtils.isEmpty(modifyTitle)) {
            int likeNum = surveyTemplatesDao.distinctLikeTitle(modifyTitle + "%");
            return likeNum;
        }
//        更改模板信息
        surveyTemplatesDao.modifyTemplate(templateCode, title, templateComment);
        List<SurveyLabelInfo> surveyLabelInfos = surveyLabelInfoDao.findByCode(code);
        for (SurveyLabelInfo surveyLabelInfo : surveyLabelInfos) {
//        更改模板标签信息
            surveyLabelInfoDao.modifyLabel(templateCode, surveyLabelInfo.getLabel());
        }
        List<SurveyTemplateQuestions> ques = surveyTemplateQuestionsDao.findById(templateCode);
        List questions = new ArrayList();
        for (SurveyTemplateQuestions que : ques) {
            questions.add(que.getCode());
        }
        List<SurveyQuestionnaire> surveyQuestionnaires = surveyQuestionnaireDao.findById(code);
        for (SurveyQuestionnaire question : surveyQuestionnaires) {
            String qstCode = question.getCode();
            String qstTitle = question.getTitle();
            String qstComment = question.getQuestionComment();
            Integer qstType = question.getQuestionType();
            Integer isRequired = question.getIsRequired();
            Integer minNum = question.getMinNum();
            Integer maxNum = question.getMaxNum();
            Integer sort = question.getSort();
            String next = question.getQuestionCodeNext();
            //            删除问题
            Boolean exist = questions.contains(qstCode);
            if (exist) {
//                除掉重复问题
                questions.remove(qstCode);
            }
            //            更改问题到模板问题表(修改模板新增的问题)
            int rows = surveyTemplateQuestionsDao.modifyQuestion(templateCode, qstCode, qstTitle, qstComment, qstType, isRequired, minNum, maxNum, sort, next);
//            新增问题直接保存
            if (rows == 0) {
                Integer de = question.getDel();
                Date createTiem = question.getCreateTime();
                Date updateTiem = question.getUpdateTime();
                SurveyTemplateQuestions surveyTemplateQuestions = new SurveyTemplateQuestions(qstCode, qstTitle, qstComment, qstType, templateCode, isRequired, minNum, maxNum, sort, next, null, de, createTiem, updateTiem);
                surveyTemplateQuestionsDao.save(surveyTemplateQuestions);
            }
            if (qstType != 2) {
                List<SurveyQuestionnaireOptions> surveyQuestionnaireOptions = surveyQuestionnaireOptionsDao.findByIdAndQstCode(code, question.getCode());
                List<SurveyTemplateOptions> templateOption = surveyTemplateOptionsDao.findById(qstCode,templateCode);
                List options = new ArrayList();
                for (SurveyTemplateOptions opt : templateOption) {
                    options.add(opt.getCode());
                }
                for (SurveyQuestionnaireOptions option : surveyQuestionnaireOptions) {
                    //         更改到模板选项表   survey_template_options
                    String optCode = option.getCode();
                    Integer have = option.getHaveComment();
                    String content = option.getContent();
                    String nextCode = option.getQuestionCodeNext();
                    Integer required = option.getIsRequired();
                    Integer optsort = option.getSort();
                    //                    删除选项
                    Boolean exists = options.contains(optCode);
                    if (exists) {
//                除掉重复问题
                        options.remove(optCode);
                    }
                    int row = surveyTemplateOptionsDao.modifyOption(templateCode, qstCode, optCode, have, content, nextCode, required, optsort);
//            新增问题的选项直接保存
                    if (row == 0) {
                        Integer del = option.getDel();
                        SurveyTemplateOptions surveyTemplateOptions = new SurveyTemplateOptions(optCode, have, qstCode, content,
                                templateCode, nextCode, null, required, optsort, del);
                        surveyTemplateOptionsDao.save(surveyTemplateOptions);
                    }
                }
//               删除选项更改选项状态
                for (Object opt:options) {
                    surveyTemplateOptionsDao.modifyOption(templateCode, qstCode, opt.toString());
                }
            }
        }
//            删除问题更改问题状态
        for (Object qst:questions) {
            surveyTemplateQuestionsDao.modifyQuestion(templateCode,qst.toString());
        }
        return 0;
    }

    public Map getFilter() {
        JSONObject jsonObject = new JSONObject();
//        List lis = new ArrayList();
        Iterable<SurveyDimension> surveyDimension = surveyDimensionDao.findAll();
        Map<String, Object> map = new HashMap<>();
        for (SurveyDimension dimension : surveyDimension) {
//            Map<String, Object> map = new HashMap<>();
            String name = dimension.getName();
            int value = dimension.getValue();
            switch (value) {
                case 1:
                    name = "sex";
                    break;
                case 2:
                    name = "disease";
                    break;
                case 3:
                    name = "service";
                    break;
                case 4:
                    name = "healthCondition";
                    break;
            }
            String sql = "SELECT t.value,t.`name` " +
                    " FROM wlyy_survey_dimension_option t\n" +
                    " WHERE t.`dimension_value`= " + value;
            List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
            List subLabel = new ArrayList();
            for (Map<String, Object> li : list) {
                Map<String, Object> map1 = new HashMap<>();
                int var = Integer.parseInt(li.get("value").toString());
                String nm = li.get("name").toString();
                map1.put("key", var);
                map1.put("value", nm);
                subLabel.add(map1);
            }
            map.put(name, subLabel);
//            lis.add(map);
        }
        return map;
    }

    public int getAmount(String json) {
        return getCount(json).size();
    }

    public List<String> getCount(String json) {
//        1.服务 2.健康 3疾病
        JSONObject jsonObject = new JSONObject(json);
        String sex = jsonObject.get("sex").toString();
        String str = "SELECT DISTINCT s.patient  FROM ( " +
                "SELECT t.patient,GROUP_CONCAT(t.label_name) label_name FROM wlyy_sign_patient_label_info t  " +
                "WHERE t.patient IN (SELECT a.patient FROM wlyy_sign_family a WHERE a.status IN(1,2,3)) and t.status = 1 AND t.patient IN (SELECT b.`code` FROM wlyy_patient b WHERE b.`openid` IS NOT NULL AND b.`openid`!='' ";
        if (!"0".equals(sex)) {
            str += " AND b.sex= " + sex + " ) GROUP BY t.patient ) s WHERE 1=1 ";
        } else {
            str += " ) GROUP BY t.patient ) s WHERE 1=1 ";
        }
        JSONArray service = jsonObject.getJSONArray("service");
        String ser = "";
        service:
        for (Object serv : service) {
            String type = serv.toString();
            switch (type) {
//                AND (s.label_name LIKE '%普通人群%'OR s.label_name LIKE '%慢病人群%'OR s.label_name LIKE '%65岁以上人群%')
                case "0":
                    break service;
                case "1":
                    ser += " s.label_name LIKE '%普通人群%' ";
                    break;
                case "2":
                    ser += " s.label_name LIKE '%慢病人群%' ";
                    break;
                case "3":
                    ser += " s.label_name LIKE '%65岁以上人群%' ";
                    break;
            }
            ser += " OR ";
        }
        if (!StringUtils.isEmpty(ser)) {
            str += " AND ( " + ser.substring(0, ser.lastIndexOf("OR")) + " ) ";
        }
        JSONArray healthCondition = jsonObject.getJSONArray("healthCondition");
        String heal = "";
        health:
        for (Object health : healthCondition) {
            String type = health.toString();
            switch (type) {
//                AND (s.label_name LIKE '%普通人群%'OR s.label_name LIKE '%慢病人群%'OR s.label_name LIKE '%65岁以上人群%')
                case "0":
                    break health;
                case "1":
                    heal += " s.label_name LIKE '%健康人群%' ";
                    break;
                case "2":
                    heal += " s.label_name LIKE '%患病人群%' ";
                    break;
                case "3":
                    heal += " s.label_name LIKE '%高危人群%' ";
                    break;
                case "4":
                    heal += " s.label_name LIKE '%恢复期人群%' ";
                    break;
            }
            heal += " OR ";
        }
        if (!StringUtils.isEmpty(heal)) {
            str += " AND ( " + heal.substring(0, heal.lastIndexOf("OR")) + " ) ";
        }
        JSONArray disease = jsonObject.getJSONArray("disease");
        String dis = "";
        disea:
        for (Object disea : disease) {
            String type = disea.toString();
            switch (type) {
//                AND (s.label_name LIKE '%普通人群%'OR s.label_name LIKE '%慢病人群%'OR s.label_name LIKE '%65岁以上人群%')
                case "0":
                    break disea;
                case "1":
                    dis += " s.label_name LIKE '%高血压%' ";
                    break;
                case "2":
                    dis += " s.label_name LIKE '%糖尿病%' ";
                    break;
            }
            dis += " OR ";
        }
        if (!StringUtils.isEmpty(dis)) {
            str += " AND ( " + dis.substring(0, dis.lastIndexOf("OR")) + " ) ";
        }
        System.out.println("=====query sql =======>>>>" + str);
        List<String> patients = jdbcTemplate.queryForList(str, String.class);
        return patients;
    }


}
