package com.yihu.jw.hospital.survey.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientBusinessDO;
import com.yihu.jw.entity.hospital.survey.*;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.survey.dao.*;
import com.yihu.jw.patient.dao.BasePatientBusinessDao;
import com.yihu.jw.restmodel.hospital.consult.WlyyHospitalSysDictVO;
import com.yihu.jw.restmodel.hospital.survey.*;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.hospital.BaseHospitalRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.common.PercentageUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.http.HttpClientUtil;
import com.yihu.jw.utils.EntityUtils;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.xpath.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Trick on 2019/9/6
 */
@Service
@Transactional
public class SurveyService extends BaseJpaService<WlyySurveyQuestionDO, SurveyQuestionDao> {

    @Autowired
    private WlyyHospitalSysDictDao sysDictDao;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SurveyQuestionDao surveyQuestionDao;
    @Autowired
    private SurveyQuestionsOptionDao surveyQuestionsOptionDao;
    @Autowired
    private SurveyTemplateDao surveyTemplateDao;
    @Autowired
    private SurveyTemplateQuestionDao surveyTemplateQuestionDao;
    @Autowired
    private SurveyTemplateOptionDao surveyTemplateOptionDao;
    @Autowired
    private SurveyLabelInfoDao surveyLabelInfoDao;
    @Autowired
    private SurveyInspLabelInfoDao surveyInspLabelInfoDao;
    @Autowired
    private SurveyDeptDao surveyDeptDao;
    @Autowired
    private SurveyUserDao surveyUserDao;
    @Autowired
    private SurveyUserAnswerDao surveyUserAnswerDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private BasePatientBusinessDao basePatientBusinessDao;
    @Value("${wechat.id}")
    private String wxId;


    @Value("${wechat.flag}")
    private boolean flag;
    @Autowired
    private HttpClientUtil HttpClientUtil;

    @Value("${im.im_list_get}")
    private String im_host;
    /**
     * 查询字典
     * 1.surveyLabel；2.surveyScreenLabel
     * @param name
     * @return
     */
    public List<WlyyHospitalSysDictVO> findSurveyLabel(String name){
        List<WlyyHospitalSysDictVO> list = new ArrayList<>();
        return convertToModels(sysDictDao.findByDictName(name),list,WlyyHospitalSysDictVO.class);
    }

    /**
     * 查询问题
     * @param title
     * @param questionType
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findSurveyQuestion(String title,String creater, Integer questionType,Integer page,Integer size)throws Exception{

        //计算总数
        String totalSql ="SELECT" +
                " COUNT(1) AS \"total\"" +
                " FROM" +
                " wlyy_survey_question q " +
                " WHERE q.del = '1' ";
        if(StringUtils.isNotBlank(title)){
            totalSql+=" AND q.title like '%"+title+"%'";
        }
        if(questionType!=null){
            totalSql+=" AND q.question_type ="+questionType;
        }

        if (StringUtils.isNoneBlank(creater)){
            totalSql+=" AND q.creater ='"+creater+"' ";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = hibenateUtils.objTransformLong(rstotal.get(0).get("total"));
        }

        //计算总数
        String sql ="SELECT " +
                " q.id AS \"id\", " +
                " q.title AS \"title\", " +
                " q.question_comment AS \"questionComment\", " +
                " q.question_type AS \"questionType\", " +
                " q.is_required AS \"isRequired\", " +
                " q.min_num AS \"minNum\", " +
                " q.max_num AS \"maxNum\", " +
                " q.del as \"del\", " +
                " q.create_time AS \"createTime\", " +
                " q.update_time AS \"updateTime\" " +
                " FROM " +
                " wlyy_survey_question q " +
                " WHERE q.del = '1' ";

        if(StringUtils.isNotBlank(title)){
            sql+=" AND q.title like '%"+title+"%'";
        }
        if(questionType!=null){
            sql+=" AND q.question_type ="+questionType;
        }

        if (StringUtils.isNoneBlank(creater)){
            sql+=" AND q.creater ='"+creater+"' ";
        }
        sql += " ORDER BY q.create_time DESC  ";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (!flag){
                sql ="SELECT * FROM\n" +
                        "( SELECT A.*, ROWNUM RN FROM\n" +
                        "    ("+sql+") A \n" +
                        "    WHERE ROWNUM <= "+page*size+" ) \n" +
                        "       WHERE RN >= "+((page-1)*size+1);

            }else {
                sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

            }
        } else {
            sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

        }
        List<WlyySurveyQuestionVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyySurveyQuestionVO.class));

        if(list!=null&&list.size()>0){
            for(WlyySurveyQuestionVO sq:list){
                List<WlyySurveyQuestionsOptionDO> optionDOs = surveyQuestionsOptionDao.findByQuestionCodeAndDelOrderBySortAsc(sq.getId(),"1");
                if(optionDOs!=null&&optionDOs.size()>0){
                    List<WlyySurveyQuestionsOptionVO> optionVOs = new ArrayList<>();
                    sq.setOptionVOs(convertToModels(optionDOs,optionVOs,WlyySurveyQuestionsOptionVO.class));
                }
            }
        }

        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    /**
     * 查询问题单条
     * @param surveyId
     * @return
     */
    public WlyySurveyQuestionVO findBySurveyId(String surveyId){
        WlyySurveyQuestionDO sq = surveyQuestionDao.findOne(surveyId);
        WlyySurveyQuestionVO surveyQuestionVO = convertToModel(sq,WlyySurveyQuestionVO.class);
        List<WlyySurveyQuestionsOptionDO> optionDOs = surveyQuestionsOptionDao.findByQuestionCodeAndDelOrderBySortAsc(sq.getId(),"1");
        if(optionDOs!=null&&optionDOs.size()>0){
            List<WlyySurveyQuestionsOptionVO> optionVOs = new ArrayList<>();
            surveyQuestionVO.setOptionVOs(convertToModels(optionDOs,optionVOs,WlyySurveyQuestionsOptionVO.class));
        }
        return surveyQuestionVO;
    }

    /**
     * 保存问题
     * @param sqOptionJson
     * @return
     * @throws Exception
     */
    public Boolean saveSurveyQuestion(String sqjsons,String sqOptionJson)throws Exception{

        //保存问题
        List<WlyySurveyQuestionDO> surveys = EntityUtils.jsonToList(sqjsons, WlyySurveyQuestionDO.class);
        for (WlyySurveyQuestionDO wlyySurveyQuestionDO:surveys){
            wlyySurveyQuestionDO.setCreateTime(new Date());
            wlyySurveyQuestionDO.setUpdateTime(new Date());
        }

        surveyQuestionDao.save(surveys);

        if(surveys!=null&&surveys.size()>0){
            for(WlyySurveyQuestionDO sq:surveys){
                List<WlyySurveyQuestionsOptionDO> optionDOs = surveyQuestionsOptionDao.findByQuestionCodeAndDelOrderBySortAsc(sq.getId(),"1");
                if(optionDOs!=null&&optionDOs.size()>0){
                    surveyQuestionsOptionDao.delete(optionDOs);
                }
                if(StringUtils.isNotBlank(sqOptionJson)){
                    List<WlyySurveyQuestionsOptionDO> options = EntityUtils.jsonToList(sqOptionJson, WlyySurveyQuestionsOptionDO.class);
                    surveyQuestionsOptionDao.save(options);
                }
            }
        }
        return true;
    }

    /**
     * 单个编辑问题
     * @param sqjson
     * @param sqOptionJson
     * @return
     * @throws Exception
     */
    public Boolean updataSurveyQuestion(String sqjson,String sqOptionJson) throws Exception{
        WlyySurveyQuestionDO sq = objectMapper.readValue(sqjson,WlyySurveyQuestionDO.class);
        sq.setUpdateTime(new Date());
        surveyQuestionDao.save(sq);

        List<WlyySurveyQuestionsOptionDO> optionDOs = surveyQuestionsOptionDao.findByQuestionCodeAndDelOrderBySortAsc(sq.getId(),"1");
        if(optionDOs!=null&&optionDOs.size()>0){
            surveyQuestionsOptionDao.delete(optionDOs);
        }
        if(StringUtils.isNotBlank(sqOptionJson)){
            List<WlyySurveyQuestionsOptionDO> options = EntityUtils.jsonToList(sqOptionJson, WlyySurveyQuestionsOptionDO.class);
            surveyQuestionsOptionDao.save(options);
        }
        return true;
    }

    /**
     * 删除问题
     * @param ids
     * @return
     */
    public Boolean delSurveyQuestion(String ids){

        String sids[] =ids.split(",");
        if(sids!=null&&ids.length()>0){
            for(String id:sids){
                WlyySurveyQuestionDO del = surveyQuestionDao.findOne(id);
                if(del!=null){
                    surveyQuestionDao.delete(del);
                }
                List<WlyySurveyQuestionsOptionDO> optionDOs = surveyQuestionsOptionDao.findByQuestionCodeAndDelOrderBySortAsc(id,"1");
                if(optionDOs!=null&&optionDOs.size()>0){
                    surveyQuestionsOptionDao.delete(optionDOs);
                }
            }
        }
        return true;
    }

    //=====================问卷模板=====================================

    /**
     *  查询模板列表
     * @param title
     * @param label
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findSurveyTemplate(String title,String creater,String label,Integer page,Integer size){

        String totalSql ="SELECT " +
                " COUNT(1) AS \"total\"" +
                " FROM " +
                " wlyy_survey_template t ";
        if(StringUtils.isNotBlank(label)){
            totalSql+=" JOIN wlyy_survey_label_info i ON t.id = i.survey_temp_code";
        }
        totalSql += " WHERE " +
                    " t.del = '1'";
        if(StringUtils.isNotBlank(title)){
            totalSql += " AND t.title like '%"+title+"%' ";
        }
        if(StringUtils.isNotBlank(label)){
            totalSql += " AND i.label_code ='"+label+"'";
        }
        if (StringUtils.isNoneBlank(creater)){
            totalSql +=" AND  t.creater_code = '"+creater+"' ";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = hibenateUtils.objTransformLong(rstotal.get(0).get("total"));
        }


        String sql = "SELECT " +
                " t.id as \"id\",  " +
                " t.title as \"title\", " +
                " t.template_comment AS \"templateComment\", " +
                " t.organization AS \"organization\", " +
                " t.creater AS \"creater\", " +
                " t.creater_code AS \"createrCode\", " +
                " t.create_time AS \"createTime\", " +
                " t.del AS \"del\", " +
                " t.update_time AS \"updateTime\"" +
                " FROM " +
                " wlyy_survey_template t ";
        if(StringUtils.isNotBlank(label)){
            sql += " JOIN wlyy_survey_label_info i ON t.id = i.survey_temp_code";
        }
            sql += " WHERE " +
                   " t.del = '1'";
        if(StringUtils.isNotBlank(title)){
            sql += " AND t.title like '%"+title+"%' ";
        }
        if(StringUtils.isNotBlank(label)){
            sql += " AND  i.label_code ='"+label+"'";
        }
        if (StringUtils.isNoneBlank(creater)){
            sql +=" AND  t.creater_code = '"+creater+"' ";
        }
        sql += " ORDER BY t.create_time DESC  ";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (!flag){
                sql ="SELECT * FROM\n" +
                        "( SELECT A.*, ROWNUM RN FROM\n" +
                        "    ("+sql+") A \n" +
                        "    WHERE ROWNUM <= "+page*size+" ) \n" +
                        "       WHERE RN >= "+((page-1)*size+1);
                System.out.println(sql);
            }else {
                sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

            }
        } else {
            sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

        }

        List<WlyySurveyTemplateVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyySurveyTemplateVO.class));

        if(list!=null&&list.size()>0){
            //设置标签
            for(WlyySurveyTemplateVO templateVO : list){
                String templateCode = templateVO.getId();
                String sqlUsed = "select t.used as \"used\" from wlyy_knowledge_article_user t where t.relation_code = '"+templateCode +"'";
                if(StringUtils.isNotEmpty(creater)){
                    sqlUsed += " and t.user_code = '"+creater+"'";
                }
                List<Map<String,Object>> listUsed = hibenateUtils.createSQLQuery(sqlUsed);
                for (Map<String,Object> map:listUsed){
                    Integer in = null;
                    if (listUsed.size()>0){
                        if (null!=listUsed.get(0)){
                            Object object = map.get("used");
                            if(object!=null){
                                if(object instanceof Integer){
                                    in = (Integer)object;
                                }else if(object instanceof String){
                                    in = Integer.parseInt((String)object);
                                }else if(object instanceof Double){
                                    in = (int)((double)object);
                                }else if(object instanceof Float){
                                    in = (int)((float)object);
                                }else if(object instanceof BigDecimal){
                                    in = ((BigDecimal)object).intValue();
                                }else if(object instanceof Long){
                                    in = ((Long)object).intValue();
                                }
                            }
                        }
                        templateVO.setUsed(in);
                    }
                }



                templateVO.setLabels(findSurveyTemplateLabel(templateVO.getId()));
            }
        }

        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    /**
     * 获取问卷模板详情
     * @param tempId
     * @return
     */
    public WlyySurveyTemplateVO findSurveyTemplateById(String tempId,String userCode ){
        WlyySurveyTemplateDO templateDO = surveyTemplateDao.findOne(tempId);
        WlyySurveyTemplateVO templateVO = convertToModel(templateDO,WlyySurveyTemplateVO.class);
        templateVO.setLabels(findSurveyTemplateLabel(tempId));
        templateVO.setInsplabels(findSurveyInspTemplateLabel(tempId));
        String templateCode = templateDO.getId();
        String sqlUsed = "select t.used as \"used\" from wlyy_knowledge_article_user t where t.relation_code = '"+templateCode +"'";
        if(StringUtils.isNotEmpty(userCode)){
            sqlUsed += " and t.user_code = '"+userCode+"'";
            System.out.println(sqlUsed);
            List<Map<String,Object>> listUsed = hibenateUtils.createSQLQuery(sqlUsed);
            if (listUsed.size()>0){
                String used = null!=listUsed.get(0).get("used")?listUsed.get(0).get("used").toString():"0";
                templateVO.setUsed(Integer.valueOf(used));
            }
        }

        List<WlyySurveyTemplateQuestionDO> tqDOs = surveyTemplateQuestionDao.findByTemplateCodeAndDelOrderBySortAsc(tempId,"1");
        if(tqDOs!=null&&tqDOs.size()>0){
            //设置问题
            List<WlyySurveyTemplateQuestionVO> tqVOs = new ArrayList<>();
            convertToModels(tqDOs,tqVOs,WlyySurveyTemplateQuestionVO.class);

            //设置选项
            for(WlyySurveyTemplateQuestionVO tq:tqVOs){
                List<WlyySurveyTemplateOptionDO> optionDOs  = surveyTemplateOptionDao.findByQuestionCodeAndDelOrderBySortAsc(tq.getCode(),tq.getTemplateCode(),"1");
                List<WlyySurveyTemplateOptionVO> optionVOs = new ArrayList<>();
                convertToModels(optionDOs,optionVOs,WlyySurveyTemplateOptionVO.class);
                for (WlyySurveyTemplateOptionVO optionVO:optionVOs){
                    optionVO.setId(optionVO.getCode());
                }
                tq.setOptionVOs(optionVOs);
                tq.setId(tq.getCode());
            }
            templateVO.setTemplateQuestionVOs(tqVOs);
        }
        return templateVO;
    }

    public List<WlyySurveyLabelInfoVO> findSurveyTemplateLabel(String tempId){
        List<WlyySurveyLabelInfoDO> list = surveyLabelInfoDao.findBySurveyTempCode(tempId);
        List<WlyySurveyLabelInfoVO> rs = new ArrayList<>();
        return convertToModels(list,rs,WlyySurveyLabelInfoVO.class);
    }

    public List<WlyySurveyInspLabelInfoVO> findSurveyInspTemplateLabel(String tempId){
        List<WlyySurveyInspLabelInfoDO> list = surveyInspLabelInfoDao.findBySurveyTempCode(tempId);
        List<WlyySurveyInspLabelInfoVO> rs = new ArrayList<>();
        return convertToModels(list,rs,WlyySurveyInspLabelInfoVO.class);
    }

    /**
     * 保存，更新模板
     * @param tempJson
     * @param tempQJson
     * @param tempOpJson
     * @return
     * @throws Exception
     */
    public Boolean saveSurveyTemplate(String tempJson,String tempQJson,String tempOpJson,String labelJson,String labelInspJson)throws Exception{

        WlyySurveyTemplateDO temp = objectMapper.readValue(tempJson,WlyySurveyTemplateDO.class);
        if (StringUtils.isNotEmpty(temp.getId())){
            WlyySurveyTemplateDO templateDO = surveyTemplateDao.findOne(temp.getId());
            if(null!=templateDO){
                temp.setCreater(templateDO.getCreater());
                temp.setCreaterCode(templateDO.getCreaterCode());
                temp.setUpdateTime(new Date());
            }
        }
        temp.setCreateTime(new Date());
        temp.setUpdateTime(new Date());
        temp = surveyTemplateDao.save(temp);
        //删除原有问题
        List<WlyySurveyTemplateQuestionDO> questionDODels = surveyTemplateQuestionDao.findByTemplateCodeAndDelOrderBySortAsc(temp.getId(),"1");
        if(questionDODels!=null&&questionDODels.size()>0){
            surveyTemplateQuestionDao.delete(questionDODels);
        }
        //新增问题
        if(StringUtils.isNotBlank(tempQJson)){
            List<WlyySurveyTemplateQuestionDO> questions = EntityUtils.jsonToList(tempQJson, WlyySurveyTemplateQuestionDO.class);
            for (WlyySurveyTemplateQuestionDO wlyySurveyTemplateQuestionDO:questions){
                wlyySurveyTemplateQuestionDO.setTemplateCode(temp.getId());
                wlyySurveyTemplateQuestionDO.setCode(wlyySurveyTemplateQuestionDO.getId());
                wlyySurveyTemplateQuestionDO.setId(UUID.randomUUID().toString());
                wlyySurveyTemplateQuestionDO.setCreateTime(new Date());
                wlyySurveyTemplateQuestionDO.setUpdateTime(new Date());

            }
            surveyTemplateQuestionDao.save(questions);
        }

        //删除原有问题选项
        List<WlyySurveyTemplateOptionDO> optionDODels = surveyTemplateOptionDao.findByTemplateCodeAndDelOrderBySortAsc(temp.getId(),"1");
        if(optionDODels!=null&&optionDODels.size()>0){
            surveyTemplateOptionDao.delete(optionDODels);
        }

        //保存新问题选项
        if(StringUtils.isNotBlank(tempOpJson)){
            List<WlyySurveyTemplateOptionDO> options = EntityUtils.jsonToList(tempOpJson, WlyySurveyTemplateOptionDO.class);
            for (WlyySurveyTemplateOptionDO wlyySurveyTemplateOptionDO:options){
                wlyySurveyTemplateOptionDO.setTemplateCode(temp.getId());
                wlyySurveyTemplateOptionDO.setCode(wlyySurveyTemplateOptionDO.getId());
                wlyySurveyTemplateOptionDO.setId(UUID.randomUUID()+"");

            }
            surveyTemplateOptionDao.save(options);
        }

        //保存标签
        List<WlyySurveyLabelInfoDO> labelDels = surveyLabelInfoDao.findBySurveyTempCode(temp.getId());
        if(labelDels!=null&&labelDels.size()>0){
            surveyLabelInfoDao.delete(labelDels);
        }
        if(StringUtils.isNotBlank(labelJson)){
            List<WlyySurveyLabelInfoDO> labels = EntityUtils.jsonToList(labelJson, WlyySurveyLabelInfoDO.class);
            surveyLabelInfoDao.save(labels);
        }

        //删除检查标签
        List<WlyySurveyInspLabelInfoDO> labelInspDels = surveyInspLabelInfoDao.findBySurveyTempCode(temp.getId());
        if(labelDels!=null&&labelDels.size()>0){
            surveyInspLabelInfoDao.delete(labelInspDels);
        }
        //保存检查标签
        if(StringUtils.isNotBlank(labelInspJson)){
            List<WlyySurveyInspLabelInfoDO> labels = EntityUtils.jsonToList(labelInspJson, WlyySurveyInspLabelInfoDO.class);
            surveyInspLabelInfoDao.save(labels);
        }

        return true;
    }

    /**
     * 删除
     * @param tempId
     * @return
     */
    public Boolean delSurveyTemplate(String tempId){
        WlyySurveyTemplateDO temp = surveyTemplateDao.findOne(tempId);
        if(temp!=null){
            //删除原有问题
            List<WlyySurveyTemplateQuestionDO> questionDODels = surveyTemplateQuestionDao.findByTemplateCodeAndDelOrderBySortAsc(temp.getId(),"1");
            if(questionDODels!=null&&questionDODels.size()>0){
                surveyTemplateQuestionDao.delete(questionDODels);
            }
            //删除原有问题选项
            List<WlyySurveyTemplateOptionDO> optionDODels = surveyTemplateOptionDao.findByTemplateCodeAndDelOrderBySortAsc(temp.getId(),"1");
            if(optionDODels!=null&&optionDODels.size()>0){
                surveyTemplateOptionDao.delete(optionDODels);
            }
            surveyTemplateDao.delete(temp);
        }
        return true;
    }

    //=======================调查问卷发送=====================

    /**
     * 保存问卷科室关系
     * @param tempId
     * @param sdJsons
     * @return
     * @throws Exception
     */
    public Boolean saveSurveyDept(String tempId,String sdJsons)throws Exception{

        //删除之前关系
        List<WlyySurveyDeptDO> dels = surveyDeptDao.findBySurveyTempCode(tempId);
        if(dels!=null&&dels.size()>0){
            surveyDeptDao.delete(dels);
        }

        if(StringUtils.isNotBlank(sdJsons)){
            List<WlyySurveyDeptDO> list = EntityUtils.jsonToList(sdJsons,WlyySurveyDeptDO.class);
            if(list!=null&&list.size()>0){
                surveyDeptDao.save(list);
            }
        }
        return true;
    }

    /**
     * 保存部门问卷关系
     * @param dept
     * @param sdJsons
     * @return
     * @throws Exception
     */
    public Boolean saveDeptSurvey(String dept,String sdJsons)throws Exception{

        //删除之前关系
        List<WlyySurveyDeptDO> dels = surveyDeptDao.findByDept(dept);
        if(dels!=null&&dels.size()>0){
            surveyDeptDao.delete(dels);
        }

        if(StringUtils.isNotBlank(sdJsons)){
            List<WlyySurveyDeptDO> list = EntityUtils.jsonToList(sdJsons,WlyySurveyDeptDO.class);
            if(list!=null&&list.size()>0){
                surveyDeptDao.save(list);
            }
        }
        return true;
    }

    /**
     * 查询科室下问卷列表
     * @param dept
     * @return
     */
    public List<Map<String,Object>> findSurveyByDept(String dept){
        String sql = "SELECT " +
                " t.id as \"id\", " +
                " t.title as \"title\", " +
                " t.template_comment AS \"templateComment\" " +
                " FROM " +
                " wlyy_survey_template t " +
                " JOIN wlyy_survey_dept d ON t.id = d.survey_temp_code " +
                " WHERE " +
                " d.dept = '"+dept+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }

    public List<Map<String,Object>> findSurveyByDeptAndPatient(String dept,String patient) {
        List<Map<String,Object>> result = findSurveyByDept(dept);

        if(result!=null&&result.size()>0){
            for(Map<String,Object> map:result){
                String tempId = (String)map.get("id");
                List<WlyySurveyUserDO> list = surveyUserDao.findBySurvey(tempId,patient);
                if(list!=null&&list.size()>0){
                    map.put("isAnswer",true);
                }else{
                    map.put("isAnswer",false);
                }
            }
        }
        return result;
    }

    /**
    * 查询问卷下科室
    * @param tempId
    * @return
    */
    public List<Map<String,Object>> findDeptBySurvey(String tempId){
        String sql ="SELECT " +
                " d.survey_temp_code AS \"surveyTempCode\"," +
                " d.dept AS \"dept\", " +
                " d.dept_name AS \"deptName\" " +
                " FROM " +
                " wlyy_survey_template t " +
                " JOIN wlyy_survey_dept d ON t.id = d.survey_temp_code " +
                " WHERE " +
                " t.id = '"+tempId+"'";
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql);
        return list;
    }


    /**
     *
     * @param suJson
     * @param suaJsons
     * @return
     * @throws Exception
     */
    public Boolean saveSurveyAnswer(String suJson,String suaJsons)throws Exception{

        WlyySurveyUserDO surveyUserDO = objectMapper.readValue(suJson,WlyySurveyUserDO.class);
        surveyUserDO.setFixDate(DateUtil.dateToStr(new Date(),"yyyy-MM-dd"));
        surveyUserDO.setId(UUID.randomUUID().toString());
        surveyUserDO = surveyUserDao.save(surveyUserDO);

        //删除问题答案
        List<WlyySurveyUserAnswerDO> dels = surveyUserAnswerDao.findBySurverUserId(surveyUserDO.getId());
        if(dels!=null&&dels.size()>0){
            surveyUserAnswerDao.delete(dels);
        }

        //保存答案
        if(StringUtils.isNotBlank(suaJsons)){
            List<WlyySurveyUserAnswerDO> answerDOs = EntityUtils.jsonToList(suaJsons,WlyySurveyUserAnswerDO.class);
            for(WlyySurveyUserAnswerDO answerDO : answerDOs){
                answerDO.setSurverUserId(surveyUserDO.getId());
                answerDO.setCreateTime(new Date());
                /*WlyySurveyTemplateOptionDO surveyTemplateOptionDO = surveyTemplateOptionDao.findOne(answerDO.getTempOptionCode());
                answerDO.setTempQuestionCode(surveyTemplateOptionDO.getQuestionCode());
                answerDO.setTempOptionCode(surveyTemplateOptionDO.getCode());*/
            }
            surveyUserAnswerDao.save(answerDOs);
            BasePatientBusinessDO basePatientBusinessDO = basePatientBusinessDao.findByDoctorPatientRelationCode(surveyUserDO.getPatient(),surveyUserDO.getSurveyTempCode(),surveyUserDO.getDoctor());
            JSONObject object = new JSONObject();
            if (null!=basePatientBusinessDO){
                object.put("title",surveyUserDO.getSurveyTempTitle());
                object.put("content",answerDOs);
                object.put("id",surveyUserDO.getSurveyTempCode());
            }
            this.sendImMsg(basePatientBusinessDO.getPatient(), basePatientBusinessDO.getPatientName(), basePatientBusinessDO.getSessionId(), "36", object.toJSONString(),"1");
        }
        return true;
    }

    public List<WlyySurveyUserAnswerDO> findAnswerBySurveyTempCode(String surverUserId,String patient,String tempId){
        List<WlyySurveyUserAnswerDO> list = null;
        if(StringUtils.isNotBlank(surverUserId)){
            list = surveyUserAnswerDao.findBySurverUserId(surverUserId);
        }else{
            List<WlyySurveyUserDO> surveys = surveyUserDao.findBySurvey(tempId,patient);
            System.out.println(surveys);
            if(surveys!=null&&surveys.size()>0){
                WlyySurveyUserDO wlyySurveyUserDO = surveys.get(0);
                System.out.println(wlyySurveyUserDO);
                list = surveyUserAnswerDao.findBySurverUserId(wlyySurveyUserDO.getId());
            }
        }
        return list;
    }

    /**
     * 查询问题情况
     * @param tempId
     * @return
     */
    public WlyySurveyTemplateVO findSurveyTemplateResult(String tempId) {

        WlyySurveyTemplateDO templateDO = surveyTemplateDao.findOne(tempId);
        WlyySurveyTemplateVO templateVO = convertToModel(templateDO,WlyySurveyTemplateVO.class);
        templateVO.setLabels(findSurveyTemplateLabel(tempId));
        templateVO.setInsplabels(findSurveyInspTemplateLabel(tempId));
        BaseDoctorDO doctor = baseDoctorDao.findById(templateDO.getCreaterCode());
        if (null!=doctor){
            templateVO.setVisitDept(doctor.getVisitDept());
            templateVO.setVisitDeptName(doctor.getVisitDeptName());
        }
        //查询所有答题过的用户,计算答题总数
        List<WlyySurveyUserDO> surveyUsers = surveyUserDao.findBySurveyTempCodeAndStatus(tempId,1);
        Integer total =0;
        if(surveyUsers!=null&&surveyUsers.size()>0){
            total = surveyUsers.size();
        }
        templateVO.setAnswerCount(total);

        List<WlyySurveyTemplateQuestionDO> tqDOs = surveyTemplateQuestionDao.findByTemplateCodeAndDelOrderBySortAsc(tempId,"1");
        if(tqDOs!=null&&tqDOs.size()>0){
            //设置问题
            List<WlyySurveyTemplateQuestionVO> tqVOs = new ArrayList<>();
            convertToModels(tqDOs,tqVOs,WlyySurveyTemplateQuestionVO.class);

            //设置选项
            for(WlyySurveyTemplateQuestionVO tq:tqVOs){
                List<WlyySurveyTemplateOptionDO> optionDOs  = surveyTemplateOptionDao.findByQuestionCodeAndDelOrderBySortAsc(tq.getCode(),tq.getTemplateCode(),"1");
                List<WlyySurveyTemplateOptionVO> optionVOs = new ArrayList<>();
                convertToModels(optionDOs,optionVOs,WlyySurveyTemplateOptionVO.class);
                int tpCount = 0;
                List<WlyySurveyUserAnswerDO> answerQuestionDOs = surveyUserAnswerDao.findByTempQuestionCodeDistinctPatient(tq.getCode(),tempId);
                if(answerQuestionDOs!=null&&answerQuestionDOs.size()>0){
                    tpCount = answerQuestionDOs.size();
                }
                tq.setTqCount(tpCount);
                /**
                 * 统计每个选项选择的百分比
                 */
                if(optionVOs!=null&&optionVOs.size()>0){
                    for(WlyySurveyTemplateOptionVO vo:optionVOs){
                        Integer answerCount =0;
                        List<WlyySurveyUserAnswerDO> answerDOs = surveyUserAnswerDao.findBytempOptionCode(vo.getCode(),vo.getTemplateCode());
                        if(answerDOs!=null&&answerDOs.size()>0){
                            answerCount = answerDOs.size();
                        }
                        vo.setPercentage(PercentageUtil.bs(answerCount,total)+"%");
                        vo.setOptCount(answerCount);
                        vo.setId(vo.getCode());
                    }
                }
                tq.setOptionVOs(optionVOs);
                tq.setId(tq.getCode());
            }
            templateVO.setTemplateQuestionVOs(tqVOs);
        }
        return templateVO;
    }

    /**
     * 综合查询问题答案
     * @param comment
     * @param content
     * @param tempQuestionCode
     * @param tempOptionCode
     * @param page
     * @param size
     * @return
     */
    public MixEnvelop findQuestionInfoList(String comment, String tempId,String content, String tempQuestionCode,String tempOptionCode,Integer page,Integer size){

        String totalSql ="SELECT " +
                " COUNT(1) AS \"total\"" +
                " FROM " +
                " wlyy_survey_user_answer t " +
                " WHERE 1=1";
        if(StringUtils.isNotBlank(comment)){
            totalSql += " AND t.comment like '%"+comment+"%' ";
        }
        if(StringUtils.isNotBlank(content)){
            totalSql += " AND t.content  like '%"+content+"%'";
        }
        if(StringUtils.isNotBlank(tempQuestionCode)){
            totalSql += " AND t.temp_question_code ='"+tempQuestionCode+"'";
        }
        if(StringUtils.isNotBlank(tempOptionCode)){
            totalSql += " AND t.temp_option_code ='"+tempOptionCode+"'";
        }
        if(StringUtils.isNotBlank(tempId)){
            totalSql += " AND t.survey_temp_code ='"+tempId+"'";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = hibenateUtils.objTransformLong(rstotal.get(0).get("total"));
        }


        String sql = "SELECT " +
                " t.id as \"id\", " +
                " t.survey_temp_code AS \"surveyTempCode\", " +
                " t.temp_question_code AS \"tempQuestionCode\", " +
                " t.question_type AS \"questionType\", " +
                " t.temp_option_code AS \"tempOptionCode\", " +
                " t.user_comment AS \"comment\", " +
                " t.user_content AS \"content\", " +
                " t.patient AS \"patient\"," +
                " t.patient_name AS \"patientName\"," +
                " t.score AS \"score\"," +
                " t.create_time AS \"createTime\"" +
                " FROM " +
                " wlyy_survey_user_answer t " +
                " WHERE 1=1";
        if(StringUtils.isNotBlank(comment)){
            sql += " AND t.user_comment like '%"+comment+"%' ";
        }
        if(StringUtils.isNotBlank(content)){
            sql += " AND t.user_content  like '%"+content+"%'";
        }
        if(StringUtils.isNotBlank(tempQuestionCode)){
            sql += " AND t.temp_question_code ='"+tempQuestionCode+"'";
        }
        if(StringUtils.isNotBlank(tempOptionCode)){
            sql += " AND t.temp_option_code ='"+tempOptionCode+"'";
        }
        if(StringUtils.isNotBlank(tempId)){
            sql += " AND t.survey_temp_code ='"+tempId+"'";
        }
        sql += " ORDER BY t.create_time DESC  ";
        if ("xm_ykyy_wx".equals(wxId)) {
            if (!flag){
                sql ="SELECT * FROM\n" +
                        "( SELECT A.*, ROWNUM RN FROM\n" +
                        "    ("+sql+") A \n" +
                        "    WHERE ROWNUM <= "+page*size+" ) \n" +
                        "       WHERE RN >= "+((page-1)*size+1);

            }else {
                sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

            }
        } else {
            sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

        }
        List<WlyySurveyUserAnswerDO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyySurveyUserAnswerDO.class));

        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    /**
     * 查询
     * @param
     * @param
     * @param
     * @return
     */
    public MixEnvelop findAnswerList(String tempId,String patient,String patientName,String title,Integer page,Integer size){

        String totalSql ="SELECT " +
                " COUNT(1) AS \"total\"" +
                " FROM " +
                " wlyy_survey_user t " +
                " WHERE 1=1 and t.status = 1 ";
        if(StringUtils.isNotBlank(title)){
            totalSql += " AND t.survey_temp_title like '%"+title+"%' ";
        }
        if(StringUtils.isNotBlank(patient)){
            totalSql += " AND t.patient = '"+patient+"' ";
        }
        if(StringUtils.isNotBlank(tempId)){
            totalSql += " AND t.survey_temp_code = '"+tempId+"' ";
        }
        if(StringUtils.isNotBlank(patientName)){
            totalSql += " AND t.patient_name like  '%"+patientName+"%' ";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = hibenateUtils.objTransformLong(rstotal.get(0).get("total"));
        }

        String sql = "SELECT " +
                " t.id as \"id\", " +
                " t.survey_temp_code AS \"surveyTempCode\", " +
                " t.survey_temp_title AS \"surveyTempTitle\", " +
                " t.patient as \"patient\"," +
                " t.patient_name AS \"patientName\"," +
                " t.dept as \"dept\"," +
                " t.dept_name AS \"deptName\"," +
                " t.doctor AS \"doctor\"," +
                " t.doctor_name AS \"doctorName\"," +
                " t.status AS \"status\"," +
                " t.end_time AS \"endTime\"," +
                " t.create_time AS \"createTime\"," +
                " p.idcard as \"idcard\"," +
                " p.sex as \"sex\"" +
                " FROM " +
                " wlyy_survey_user t " +
                " JOIN base_patient p ON t.patient = p.id " +
                " WHERE 1=1 and t.status = 1 ";
        if(StringUtils.isNotBlank(title)){
            sql += " AND t.survey_temp_title like '%"+title+"%' ";
        }
        if(StringUtils.isNotBlank(patient)){
            sql += " AND t.patient = '"+patient+"' ";
        }
        if(StringUtils.isNotBlank(patientName)){
            sql += " AND t.patient_name like  '%"+patientName+"%' ";
        }
        if(StringUtils.isNotBlank(tempId)){
            sql += " AND t.survey_temp_code = '"+tempId+"' ";
        }
        sql += " ORDER BY t.create_time DESC " ;

        if ("xm_ykyy_wx".equals(wxId)) {
            if (!flag){
                sql ="SELECT * FROM\n" +
                        "( SELECT A.*, ROWNUM RN FROM\n" +
                        "    ("+sql+") A \n" +
                        "    WHERE ROWNUM <= "+page*size+" ) \n" +
                        "       WHERE RN >= "+((page-1)*size+1);

            }else {
                sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

            }
        } else {
            sql+="LIMIT "+ (page - 1) * size + "," + size + " ";

        }
        System.out.println(sql);
        List<WlyySurveyUserVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WlyySurveyUserVO.class));

        if(list!=null&&list.size()>0){
            for(WlyySurveyUserVO vo :list){
                vo.setAge(IdCardUtil.getAgeForIdcard(vo.getIdcard()));
            }
        }

        return MixEnvelop.getSuccessListWithPage(BaseHospitalRequestMapping.Prescription.api_success, list, page, size, count);
    }

    public String sendImMsg(String from, String fromName, String sessionId, String contentType, String content, String businessType) {
        String imAddr = im_host + "api/v2/sessions/" + sessionId + "/messages";
        System.out.println("im地址"+imAddr);
        JSONObject params = new JSONObject();
        params.put("sender_id", from);
        params.put("sender_name", fromName);
        params.put("content_type", contentType);
        params.put("content", content);
        params.put("session_id", sessionId);
        params.put("business_type", businessType);
        String response = HttpClientUtil.postBody(imAddr, params);
        return response;
    }

}
