Kaynağa Gözat

新增医生助手功能

trick9191 7 yıl önce
ebeveyn
işleme
d75a02dfe2
22 değiştirilmiş dosya ile 3812 ekleme ve 0 silme
  1. 366 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java
  2. 483 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java
  3. 564 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java
  4. 42 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java
  5. 48 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/data/DataController.java
  6. 65 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java
  7. 45 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java
  8. 88 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java
  9. 63 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java
  10. 49 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java
  11. 80 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/icd/Icd10Controller.java
  12. 350 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/im/imController.java
  13. 35 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java
  14. 399 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java
  15. 115 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java
  16. 62 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java
  17. 45 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java
  18. 108 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java
  19. 353 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java
  20. 326 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java
  21. 61 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java
  22. 65 0
      patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java

+ 366 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/FileUploadController.java

@ -0,0 +1,366 @@
package com.yihu.wlyy.web.common;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yihu.wlyy.util.CommonUtil;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.ImageCompress;
import com.yihu.wlyy.util.SystemConf;
import com.yihu.wlyy.util.fastdfs.FastDFSUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
@Controller
@RequestMapping(value = "/upload", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "文件上传")
public class FileUploadController extends BaseController {
    @ApiParam
    FastDFSUtil fastDFSUtil;
    @Autowired
    private CommonUtil CommonUtil;
    @Value("${fastDFS.fastdfs_file_url}")
    private String fastdfs_file_url;
    /**
     * 患者头像上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "patientPhoto", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
    @ResponseBody
    public String patientPhoto(HttpServletRequest request, HttpServletResponse response, String photo) {
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            String firstPhoto = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                firstPhoto = photo.substring(0, photo.lastIndexOf(".")) + "_small." + fileExt;
                File uploadFile = new File(SystemConf.getInstance().getTempPath() + File.separator + firstPhoto);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", String.join(",", firstPhoto));
            System.out.println("图片上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "上传失败");
        }
    }
    /**
     * 图片上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "image", method = RequestMethod.POST/* , headers = "Accept=image/png" */)
    @ResponseBody
    public String image(HttpServletRequest request, HttpServletResponse response) {
        // 圖片列表
        List<File> images = new ArrayList<File>();
        List<String> tempPaths = new ArrayList<String>();
        // 文件保存的临时路径
        String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // 创建文件夹
            File file = new File(tempPath + datePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File uploadFile = new File(tempPath + datePath + newFileName);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 生成缩略图
                ImageCompress.compress(uploadFile.getAbsolutePath(), uploadFile.getAbsolutePath() + "_small", 300, 300);
                // 添加到上传成功数组中
                images.add(uploadFile);
                tempPaths.add(datePath + newFileName);
            }
            String urls = "";
            for (String image : tempPaths) {
                if (urls.length() == 0) {
                    urls = image;
                } else {
                    urls += "," + image;
                }
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("图片上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            try {
                // 清除垃圾图片
                for (File file : images) {
                    FileUtils.forceDelete(file);
                }
            } catch (Exception e2) {
                error(e2);
            }
            return error(-1, "上传失败");
        }
    }
    /**
     * 聊天附件上传
     *
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping(value = "chat", method = RequestMethod.POST)
    @ResponseBody
    public String chatFile(HttpServletRequest request, HttpServletResponse response) {
        List<String> tempPaths = new ArrayList<String>();
        try {
            String fastUrl = fastdfs_file_url;
            String type  = request.getParameter("type");
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                if("3".equals(type)){
                    String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
                    String map3Path = tempPath.substring(0,tempPath.lastIndexOf("."));
                    CommonUtil.changeToMp3(tempPath,map3Path);
                    File tempFile = new File(tempPath);
                    File mp3File = new File(map3Path);
                    ObjectNode objectNode = fastDFSUtil.upload(new FileInputStream(mp3File),"mp3","");
                    //1.3.7 去掉前缀,返回相对路径
//                    tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(objectNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    if(tempFile!=null){
                        tempFile.delete();
                    }
                    if(mp3File!=null){
                        mp3File.delete();
                    }
                }else if("4".equals(type)){
                    String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
                    String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
                    File tempFile = new File(tempPath);
                    File pngFile = new File(pngPath);
                    long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
                    if(times<1000){
                        JSONObject json = new JSONObject();
                        json.put("status", -1);
                        json.put("success",true);
                        json.put("msg", "视频录制时间太短!");
                        json.put("times", times);
                        return json.toString();
                    }
                    ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
                    //1.3.7 去掉前缀,返回相对路径
//                    tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
//                    tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(imgNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(videoNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(times+"");
                    if(tempFile!=null){
                        tempFile.delete();
                    }
                    if(pngFile!=null){
                        pngFile.delete();
                    }
                } else{
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                    ObjectNode objectNode = fastDFSUtil.upload(mf.getInputStream() ,fileExt,"");
                    //1.3.7 去掉前缀,返回相对路径
//                  tempPaths.add(fastUrl + objectNode.get("groupName").toString().replaceAll("\"","")
//                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                    tempPaths.add(objectNode.get("groupName").toString().replaceAll("\"","")
                            + "/" + objectNode.get("remoteFileName").toString().replaceAll("\"",""));
                }
            }
            String urls = String.join(",", tempPaths);
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("success",true);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("附件上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "上传失败");
        }
    }
    /**
     * 语音上传
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "voice", method = RequestMethod.POST)
    @ResponseBody
    public String voice(HttpServletRequest request, HttpServletResponse response) {
        // 圖片列表
        List<File> voices = new ArrayList<File>();
        List<String> tempPaths = new ArrayList<String>();
        // 文件保存的临时路径
        String tempPath = SystemConf.getInstance().getTempPath() + File.separator;
        // 拼接年月日路径
        String datePath = DateUtil.getStringDate("yyyy") + File.separator + DateUtil.getStringDate("MM") + File.separator + DateUtil.getStringDate("dd") + File.separator;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
            // 创建文件夹
            File file = new File(tempPath + datePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();
                String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
                // 重命名文件
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
                File uploadFile = new File(tempPath + datePath + newFileName);
                // 拷贝文件流到指定文件路径
                FileCopyUtils.copy(mf.getBytes(), uploadFile);
                // 添加到上传成功数组中
                voices.add(uploadFile);
                tempPaths.add(datePath + newFileName);
            }
            String urls = "";
            for (String voice : tempPaths) {
                if (urls.length() == 0) {
                    urls = voice;
                } else {
                    urls += "," + voice;
                }
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "上传成功");
            // 图片标识对象的HTTP链接
            json.put("urls", urls);
            System.out.println("语音上传:" + json.toString());
            return json.toString();
        } catch (Exception e) {
            error(e);
            try {
                // 清除垃圾图片
                for (File file : voices) {
                    FileUtils.forceDelete(file);
                }
            } catch (Exception e2) {
                error(e2);
            }
            return error(-1, "上传失败");
        }
    }
    /**
     * 语音上传
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "test", method = RequestMethod.POST)
    @ResponseBody
    public String test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        List<String> tempPaths = new ArrayList<String>();
        String fastUrl = fastdfs_file_url;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();
            String tempPath  =  CommonUtil.saveVoiceToDisk(mf.getInputStream(),fileName);
            String pngPath = tempPath.substring(0,tempPath.lastIndexOf("."))+".png";
            File tempFile = new File(tempPath);
            File pngFile = new File(pngPath);
            long times = CommonUtil.getVideoTimeAndImg(tempPath,pngPath);
            ObjectNode imgNode = fastDFSUtil.upload(new FileInputStream(pngPath),"png","");
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            ObjectNode videoNode = fastDFSUtil.upload(new FileInputStream(tempPath),fileExt,"");
            tempPaths.add(fastUrl + imgNode.get("groupName").toString().replaceAll("\"","")
                    + "/" + imgNode.get("remoteFileName").toString().replaceAll("\"",""));
            tempPaths.add(fastUrl + videoNode.get("groupName").toString().replaceAll("\"","")
                    + "/" + videoNode.get("remoteFileName").toString().replaceAll("\"",""));
            tempPaths.add(times+"");
            if(tempFile!=null){
                tempFile.delete();
            }
            if(pngFile!=null){
                pngFile.delete();
            }
        }
        String urls = String.join(",", tempPaths);
        return urls;
    }
}

+ 483 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/LoginController.java

@ -0,0 +1,483 @@
package com.yihu.wlyy.web.common.account;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.login.LoginLog;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.repository.security.TokenDao;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.common.account.RoleService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.service.common.login.LoginLogService;
import com.yihu.wlyy.util.DateUtil;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.util.SystemData;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.patchca.color.SingleColorFactory;
import org.patchca.filter.predefined.*;
import org.patchca.service.ConfigurableCaptchaService;
import org.patchca.utils.encoder.EncoderHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
//import io.swagger.annotations.Api;
/**
 * @author calvin
 */
@Controller
@RequestMapping(value = "/login", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者、医生及管理员登录")
public class LoginController extends BaseController {
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private PatientService patientService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SMSService smsService;
    @Autowired
    public TokenDao tokenDao;
    @Autowired
    private RoleService roleService;
    @Autowired
    private LoginLogService loginLogService;
    /**
     * 公钥生成并返回接口
     *
     * @return
     */
    @RequestMapping(value = "public_key", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String publicKey() {
        try {
            String modulus = RSAUtils.getInstance(smsService).getModulus();
            String exponent = RSAUtils.getInstance(smsService).getExponent();
            if (StringUtils.isEmpty(modulus) || StringUtils.isEmpty(exponent)) {
                return error(-1, "公钥获取失败!");
            } else {
                JSONObject json = new JSONObject();
                json.put("modulus", modulus);
                json.put("exponent", exponent);
                return write(200, "公钥获取成功!", "data", json);
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "公钥获取失败!");
        }
    }
    /**
     * 医生登录接口
     *
     * @param mobile   手机号
     * @param captcha  短信验证码
     * @param platform // 1患者端,2医生端app,3微信公众号wechat,4 IM医生端pc, PC端取药系统,5医生助手公众号
     * @param password 密码
     * @return
     */
    @RequestMapping(value = "doctor", method = RequestMethod.POST)
    @ResponseBody
    public String doctor(@ApiParam(required = false, name = "mobile", value = "手机号") @RequestParam(required = false, value = "mobile") String mobile,
                         @ApiParam(required = false, name = "captcha", value = "短信验证码") @RequestParam(required = false) String captcha,
                         @ApiParam(required = false, name = "platform", value = "医生端pc,取药系统 或者对外系统") @RequestParam(required = false) Integer platform,
                         @ApiParam(required = false, name = "password", value = "密码") @RequestParam(required = false) String password,
                         @ApiParam(required = false, name = "password", value = "openid") @RequestParam(required = false) String openid) {
        String errorMessage;
        LoginLog loginLog = new LoginLog();
        loginLog.setCreateTime(new Date());
        loginLog.setPhone(mobile);
        loginLog.setType("2");
        loginLog.setUserType("2");
        loginLog.setAppVersion(super.getAppVersion());
        try {
            if (StringUtils.isEmpty(getIMEI())) {
                errorMessage = "获取手机IMEI码失败!";
                loginLog.setErrorMessage(errorMessage);
                loginLogService.saveLog(loginLog);
                return error(-1, errorMessage);
            }
            if (platform == null) {
                platform = 2;//默认为医生app端
            }
            //身份证登录
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(password)) {
                password = RSAUtils.getInstance(doctorService).decryptString(password);
                password = StringUtils.reverse(password);
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                loginLog.setLoginType("2");
                if (doctor == null) {
                    errorMessage = "该号码未注册!";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
                loginLog.setUserCode(doctor.getCode());
                String loginPassword = MD5.GetMD5Code(password + doctor.getSalt());
                if (loginPassword.equals(doctor.getPassword())) {
                    Token token = tokenService.findDoctorToken(doctor.getCode());
                    if (token != null && platform == 4 && getIMEI().equals(token.getImei())) {
                        //pc版本要做单点登陆 所以如果platform =4 并且 token存在直接返回之前的token
                    }else {
                        // 用户校验通过,生成token
                        token = tokenService.newToken(doctor.getCode(), getIMEI(), platform);
                    }
                    loginLog.setTokenId(token.getId());
                    loginLog.setType("1");
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", doctor.getId());
                    map.put("uid", doctor.getCode());
                    map.put("token", token.getToken());
                    map.put("name", doctor.getName());
                    map.put("hospital", doctor.getHospital());
                    map.put("photo", doctor.getPhoto());
                    // 设置医生类型:1专科医生,2全科医生,3健康管理师
                    map.put("doctorType", doctor.getLevel());
                    //获取医生角色和区域权限
                    List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(doctor.getCode());
                    map.put("userRole", roleMap);
                    if ("10" .equals(doctor.getLevel()) && roleMap.size() == 0) {
                        errorMessage = "该用户没有管理员权限";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    loginLogService.saveLog(loginLog);
                    if(StringUtils.isNotBlank(openid)){
                        doctor.setOpenid(openid);
                    }
                    return write(200, "登录成功", "data", map);
                } else {
                    errorMessage = "密码错误,登录失败";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
            }
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(captcha)) {
                // 对验证码进行校验
                int res = smsService.check(mobile, 5, captcha);
                switch (res) {
                    case -2: {
                        errorMessage = "验证码已过期!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case -1: {
                        errorMessage = "请输入正确的验证码!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case 0: {
                        errorMessage = "验证码无效!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                }
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                loginLog.setLoginType("1");
                if (doctor == null) {
                    errorMessage = "该手机号未注册,请确认!";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else {
                    loginLog.setUserCode(doctor.getCode());
                    // 用户校验通过,生成token
                    Token token = tokenService.findDoctorToken(doctor.getCode());
                    if (token != null && platform == 4 && getIMEI().equals(token.getImei())) {
                        //pc版本要做单点登陆 所以如果platform =4 并且 token存在直接返回之前的token
                    } else {
                        // 用户校验通过,生成token
                        token = tokenService.newToken(doctor.getCode(), getIMEI(), platform);
                    }
                    loginLog.setTokenId(token.getId());
                    loginLog.setType("1");
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", doctor.getId());
                    map.put("uid", doctor.getCode());
                    map.put("token", token.getToken());
                    map.put("name", doctor.getName());
                    map.put("hospital", doctor.getHospital());
                    map.put("photo", doctor.getPhoto());
                    // 设置医生类型:1专科医生,2全科医生,3健康管理师
                    map.put("doctorType", doctor.getLevel());
                    //获取医生角色和区域权限
                    List<Map<String, String>> roleMap = roleService.getUserRoleAndArea(doctor.getCode());
                    map.put("userRole", roleMap);
                    if ("10" .equals(doctor.getLevel()) && roleMap.size() == 0) {
                        errorMessage = "改用户没有管理员权限";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    loginLogService.saveLog(loginLog);
                    return write(200, "登录成功", "data", map);
                }
            }
            errorMessage = "登录信息不完整,请重新输入!";
            loginLog.setErrorMessage(errorMessage);
            loginLogService.saveLog(loginLog);
            return error(-1, errorMessage);
        } catch (Exception e) {
            loginLog.setErrorMessage(e.getMessage());
            loginLogService.saveLog(loginLog);
            error(e);
            return error(-1, "系统异常,登录失败");
        }
    }
    /**
     * 忘记密码
     *
     * @param type    1患者端,2医生端
     * @param idcard  患者身份证号
     * @param mobile  手机号
     * @param captcha 手机验证码
     * @param newpwd  新密码
     * @return
     */
    @RequestMapping(value = "forgetpwd", method = RequestMethod.POST)
    @ResponseBody
    public String forgetpwd(int type,
                            @RequestParam(required = false) String idcard,
                            @RequestParam(required = false) String mobile,
                            @RequestParam(required = false) String captchaToken,
                            @RequestParam(required = false) String captcha,
                            @RequestParam(required = false) String patient,
                            String newpwd) {
        try {
            //String ct = request.getSession().getAttribute("captchaToken").toString();
//            if (StringUtils.isEmpty(captchaToken)) {
//                return error(-1, "图形验证码不允许为空!");
//            }
//            if (!StringUtils.equalsIgnoreCase(captchaToken, ct)) {
//                return error(-1, "图形验证码错误!");
//            }
//            idcard = RSAUtils.getInstance(doctorService).decryptString(idcard);
//            idcard = URLDecoder.decode(idcard, "UTF-8");
//            idcard = StringUtils.reverse(idcard);
//            newpwd = RSAUtils.getInstance(doctorService).decryptString(newpwd);
//            newpwd = URLDecoder.decode(newpwd, "UTF-8");
//            newpwd = StringUtils.reverse(newpwd);
            // 对验证码进行校验
            if (type == 2) {
                // 医生端
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                String password = RSAUtils.getInstance(doctorService).decryptString(newpwd);
                password = StringUtils.reverse(password);
                password = MD5.GetMD5Code(password + doctor.getSalt());
                doctor.setPassword(password);
                doctorService.updateDoctorPwd(doctor);
                return success("操作成功!");
            } else {
                // 患者端
                Patient patientTemp = patientService.findByIdcard(idcard);
                if (patientTemp == null) {
                    return error(-1, "操作失败:此用户未注册");
                } else {
                    String password = RSAUtils.getInstance(doctorService).decryptString(newpwd);
                    password = StringUtils.reverse(password);
                    password = MD5.GetMD5Code(password + patientTemp.getSalt());
                    patientTemp.setPassword(password);
                    patientService.updatePatientPwd(patientTemp);
                    return success("操作成功!");
                }
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "系统异常,操作失败");
        }
    }
    /**
     * 退出登录
     *
     * @param type 1患者,2医生,3微信公众号
     * @return
     */
    @RequestMapping(value = "exit", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String logout(int type) {
        try {
            tokenService.delToken(type, getUID());
            return success("已成功退出!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败!");
        }
    }
    @RequestMapping(value = "/third/login", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String thirdLogin(
            @RequestParam(value = "id") int id,
            @RequestParam(value = "uid") String uid,
            @RequestParam(value = "imei") String imei,
            @RequestParam(value = "token") String tokenStr,
            @RequestParam(value = "platform") int platform) {
        try {
            if (StringUtils.isEmpty(tokenStr) || StringUtils.isEmpty(imei) || StringUtils.isEmpty(uid)) {
                // response.getWriter().write(error(SystemConf.NOT_LOGIN, "请登录后再操作!"));
                return error(-1, "系统异常,操作失败");
            }
            Token token = SystemData.doctorTokens.get(uid);
            if (token == null) {
                token = tokenDao.findByToken(tokenStr);
                if (token != null) {
                    // 加入缓存
                    SystemData.doctorTokens.put(uid, token);
                }
            }
            if (token == null || token.getPlatform() != 2) {
                // 未登录
                return error(-1, "系统异常,操作失败");
            } else {
                if (token.getTimeout().getTime() < new Date().getTime()) {
                    // 登录超时
                    return error(-1, "系统异常,操作失败");
                } else if (!StringUtils.equals(uid, token.getUser()) || !StringUtils.equals(imei, token.getImei())) {
                    // 别处登录
                    return error(-1, "系统异常,操作失败");
                } else {
                    // 一天只更新一次
                    if (DateUtil.getDays(token.getCzrq(), DateUtil.getNowDateShort()) != 0) {
                        // 今天未更新,则更新缓存
                        token.setCzrq(new Date());
                        // 更新内存
                        SystemData.doctorTokens.put(uid, token);
                        // 更新数据库
                        tokenDao.save(token);
                    }
                }
            }
            return success("登陆成功");
        } catch (Exception ex) {
            error(ex);
            return error(-1, "系统异常,操作失败");
        }
    }
    /**
     * 验证码地址
     *
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "pcrimg", method = {RequestMethod.POST, RequestMethod.GET})
    public void crimg(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
        cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
        Random random = new Random();
        switch (random.nextInt(5)) {
            case 0:
                cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
                break;
            case 1:
                cs.setFilterFactory(new MarbleRippleFilterFactory());
                break;
            case 2:
                cs.setFilterFactory(new DoubleRippleFilterFactory());
                break;
            case 3:
                cs.setFilterFactory(new WobbleRippleFilterFactory());
                break;
            case 4:
                cs.setFilterFactory(new DiffuseRippleFilterFactory());
                break;
        }
        HttpSession session = request.getSession(false);
        if (session == null) {
            session = request.getSession();
        }
        setResponseHeaders(response);
        String token = EncoderHelper.getChallangeAndWriteImage(cs, "png", response.getOutputStream());
        session.setAttribute("captchaToken", token);
    }
    protected void setResponseHeaders(HttpServletResponse response) {
        response.setContentType("image/png");
        response.setHeader("Cache-Control", "no-cache, no-store");
        response.setHeader("Pragma", "no-cache");
        long time = System.currentTimeMillis();
        response.setDateHeader("Last-Modified", time);
        response.setDateHeader("Date", time);
        response.setDateHeader("Expires", time);
    }
    /**
     * 患者,医生注册-验证手机号
     *
     * @param mobile 登录手机号
     * @return
     */
    @RequestMapping(value = "checkmobile", method = RequestMethod.POST)
    @ResponseBody
    public String checkmobile(@RequestParam(required = true, value = "mobile", defaultValue = "0") String mobile,
                              @RequestParam(required = true, value = "type", defaultValue = "0") int type) {
        try {
            if (type == 0) {//患者端
                List<Patient> temp = patientService.findByMobile(mobile);
                if (temp != null && temp.size() > 0) {
                    // 设置身份证号
                    return write(200, "手机号码已经被注册!");
                }
                return error(-1, "该手机号未被注册!");
            } else if (type == 1) {
                Doctor doctor = doctorService.findDoctorByMobile(mobile);
                if (doctor != null) {
                    return write(200, "手机号码已经被注册!");
                }
                return error(-1, "该手机号未被注册!");
            } else {
                return error(1, "错误的请求类型!");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "手机号验证失败");
        }
    }
}

+ 564 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/account/WechatController.java

@ -0,0 +1,564 @@
package com.yihu.wlyy.web.common.account;
import com.yihu.wlyy.entity.login.LoginLog;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SocialSecurityInfo;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.logs.BusinessLogs;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.repository.patient.SocialSecurityInfoDao;
import com.yihu.wlyy.service.app.family.FamilyMemberService;
import com.yihu.wlyy.service.app.family.FamilyService;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.service.common.account.AccessTokenService;
import com.yihu.wlyy.service.common.account.PatientService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.service.common.login.LoginLogService;
import com.yihu.wlyy.task.PushMsgTask;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.util.IdcardValidator;
import com.yihu.wlyy.util.MD5;
import com.yihu.wlyy.util.RSAUtils;
import com.yihu.wlyy.web.WeixinBaseController;
import com.yihu.wlyy.wechat.util.WeiXinOpenIdUtils;
import com.yihu.wlyy.wechat.util.WeiXinTagUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.net.URLDecoder;
import java.util.*;
/**
 * @author calvin
 */
@Controller
@RequestMapping(value = "/weixin", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "微信端用户注册")
public class WechatController extends WeixinBaseController {
    @Autowired
    private PatientService patientService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SMSService smsService;
    @Autowired
    private SocialSecurityInfoDao socialSecurityInfoDao;
    @Autowired
    private PatientDao patientDao;
    @Autowired
    private FamilyService familyService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private FamilyMemberService familyMemberService;
    @Autowired
    WeiXinOpenIdUtils weiXinOpenIdUtils;
    @Autowired
    AccessTokenService accessTokenService;
    @Autowired
    HttpUtil HttpUtil;
    @Autowired
    private PushMsgTask pushMsgTask;
    @Autowired
    private WeiXinTagUtil weiXinTagUtil;
    /**
     * 获取验证码发送的手机号码
     *
     * @param idCard
     * @return
     */
    @RequestMapping(value = "getMobile", method = RequestMethod.POST)
    @ResponseBody
    public String getPatientInfoByIdCard(@RequestParam(value = "idCard", required = true) String idCard) {
        Patient temp = patientService.findByIdcard(idCard);
        getAccessToken();
        if (temp == null) {
            return error(-1, "用户未注册");
        } else {
            if (StringUtils.isBlank(temp.getMobile())) {
                return error(-2, "用户未绑定手机号");
            } else {
                JSONObject object = new JSONObject();
                object.put("mobile", temp.getMobile());
                return write(200, "获取成功", "data", object);
            }
        }
    }
    /**
     * 注册信息验证
     *
     * @param name   姓名
     * @param idcard 身份证号
     * @param ssc    社保卡号
     * @param mobile 手机号
     * @return
     */
    @RequestMapping(value = "/check_regist_info", method = RequestMethod.POST)
    @ResponseBody
    public String checkRegistInfo(String name, String idcard, String ssc, String mobile) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空");
            }
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号不允许为空");
            }
            //if (patientService.findByMobile(mobile) != null) {
            //    return error(-1, "该手机号已被注册");
            //}
            // 解密身份证号
            idcard = RSAUtils.getInstance(patientService).decryptString(idcard);
            idcard = URLDecoder.decode(idcard, "UTF-8");
            idcard = StringUtils.reverse(idcard);
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致,请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0 && ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                    return error(-1, "身份证号与医保卡号不一致,请检查后重新输入");
                }
            } else {
                return error(-1, "对不起,暂不支持16年6月份之后办理的医保卡注册");
            }
            Patient patient = patientDao.findByIdcard(idcard);
            if (patient != null) {
                if (!StringUtils.isEmpty(patient.getMobile())) {
                    return error(-2, "该身份证已被注册");
                }
            }
            return write(200, "验证成功");
        } catch (Exception e) {
            return error(-1, "验证失败");
        }
    }
    /**
     * 患者注册
     *
     * @param idcard  身份證號
     * @param mobile  登录手机号
     * @param captcha 手机验证码
     * @return
     */
    @RequestMapping(value = "regist", method = RequestMethod.POST)
    @ResponseBody
    public String regist(@RequestParam(value = "name", required = true) String name,
                         @RequestParam(value = "idcard", required = true) String idcard,
                         @RequestParam(value = "ssc", required = true) String ssc,
                         @RequestParam(value = "mobile", required = true) String mobile,
                         @RequestParam(value = "captcha", required = true) String captcha,
                         @RequestParam(value = "openid", required = true) String openid,
                         @RequestParam(value = "password", required = true) String password) {
        try {
            if (StringUtils.isEmpty(name)) {
                return error(-1, "姓名不允许为空!");
            }
            if (StringUtils.isEmpty(idcard)) {
                return error(-1, "身份证号不允许为空!");
            }
            if (StringUtils.isEmpty(ssc)) {
                return error(-1, "社保卡号不允许为空!");
            }
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号不允许为空!");
            }
            //if (patientService.findByMobile(mobile) != null) {
            //    return error(-1, "该手机号已被注册!");
            //}
            // 对验证码进行校验
            int res = smsService.check(mobile, 1, captcha);
            switch (res) {
                case -2:
                    return error(-1, "验证码已过期!");
                case -1:
                    return error(-1, "请输入正确的验证码!");
                case 0:
                    return error(-1, "验证码无效!");
            }
            // 未绑定openid,查询是否绑定其他账号
//			if (patientService.countByOpenid(openid) > 0) {
//				return error(-1, "该微信号已绑定其他手机号!");
//			}
            // 解密身份证号
            idcard = RSAUtils.getInstance(patientService).decryptString(idcard);
            idcard = URLDecoder.decode(idcard, "UTF-8");
            idcard = StringUtils.reverse(idcard);
            // 校验身份证号
            IdcardValidator validator = new IdcardValidator();
            if (validator.isValidatedAllIdcard(idcard)) {
                if (idcard.length() == 15) {
                    idcard = validator.convertIdcarBy15bit(idcard);
                    if (StringUtils.isEmpty(idcard)) {
                        return error(-1, "请输入正确的身份证号!");
                    }
                }
            } else {
                return error(-1, "请输入正确的身份证号!");
            }
            SocialSecurityInfo socialSecurityInfo = socialSecurityInfoDao.findBySfzh18Max(idcard);
            if (socialSecurityInfo != null) {
                if (name.compareTo(socialSecurityInfo.getXming0() == null ? "" : socialSecurityInfo.getXming0()) != 0) {
                    return error(-1, "身份证号与姓名不一致<br/>请检查后重新输入");
                }
                if (ssc.compareTo(socialSecurityInfo.getCardno() == null ? "" : socialSecurityInfo.getCardno()) != 0) {
                    if (ssc.compareTo(socialSecurityInfo.getCard16() == null ? "" : socialSecurityInfo.getCard16()) != 0) {
                        return error(-1, "身份证号与医保卡号不一致,请检查后重新输入");
                    } else {
                        ssc = socialSecurityInfo.getCardno();//统一只存英文字母开头的医保卡
                    }
                }
            } else {
                return error(-1, "对不起,暂不支持16年6月份之后办理的医保卡注册");
            }
            Patient patient = patientDao.findByIdcard(idcard);
            if (patient == null) {
                patient = new Patient();
            } else {
                if (!StringUtils.isEmpty(patient.getMobile())) {
                    return error(-2, "该身份证已被注册!");
                }
            }
            patient.setName(name);
            patient.setIdcard(idcard);
            patient.setMobile(mobile);
            //增加密码
            String salt = UUID.randomUUID().toString().replace("-", "");
            patient.setSalt(salt);
            password = RSAUtils.getInstance(patientService).decryptString(password);
            password = StringUtils.reverse(password);
            patient.setPassword(MD5.GetMD5Code(password + salt));
            patient.setSsc(ssc);
            if (!org.springframework.util.StringUtils.isEmpty(openid)) {
                patient.setOpenid(openid);
                patient.setOpenidTime(new Date());
            }
            JSONObject json = patientService.register(idcard, ssc, name, mobile, MD5.GetMD5Code(password + salt)
                    , salt, openid, 3);
            if (json != null) {
                try {
                    Patient p = patientDao.findByIdcard(idcard);
                    BusinessLogs.info(BusinessLogs.BusinessType.register, p.getCode(), p.getCode(), new JSONObject(p));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 注册成功
                return write(200, "注册成功!", "data", json);
            } else {
                // 注册失败
                return error(-1, "注册失败!");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "注册失败!");
        }
    }
    /**
     * 患者微信登录接口
     *
     * @param captcha  短信号
     * @param mobile   电话号码
     * @param password 登录密码
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public String login(
            @RequestParam(required = false) String mobile,
            @RequestParam(required = false) String captcha,
            @RequestParam(required = false) String password,
            String openid) {
        System.out.println("login openid : " + openid);
        String errorMessage;
        LoginLog loginLog = new LoginLog();
        loginLog.setCreateTime(new Date());
        loginLog.setPhone(mobile);
        loginLog.setType("2");
        loginLog.setUserType("1");
        try {
            //账号登录 mobile可能是电话号也可能是身份证
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(password)) {
                Patient p = patientService.findByIdcard(mobile);
                if (p == null) {
                    List<Patient> patients = patientService.findByMobile(mobile);
                    if (patients.size() > 1) {
                        return error(-1, "此手机号码存在多个用户,请用身份证进行登录!");
                    } else if (patients.size() == 1) {
                        p = patients.get(0);
                    }
                }
                loginLog.setLoginType("2");
                if (p == null) {
                    if (mobile.length() == 11) {
                        errorMessage = "该手机号暂未注册账号,请确认后重新输入!";
                    } else {
                        errorMessage = "该身份证号暂未注册账号,请确认后重新输入!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (p.getStatus() == 0) {
                    if (mobile.length() == 11) {
                        errorMessage = "该手机号已被禁止使用!";
                    } else {
                        errorMessage = "该身份证号已被禁止使用!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (p.getStatus() == 2) {
                    errorMessage = "该账号正在审核中,请确认审核通过后再登录,“如有疑问,拨打400-6677-400转2人工客服”";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else if (StringUtils.isEmpty(openid)) {
                    errorMessage = "无效的OpenID!";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
                loginLog.setUserCode(p.getCode());
                //解密
                password = RSAUtils.getInstance(patientService).decryptString(password);
                password = StringUtils.reverse(password);
                //生成MD5
                String loginPassword = MD5.GetMD5Code(password + p.getSalt());
                //判断d登录密码是否正确
                if (loginPassword.equals(p.getPassword())) {
                    // 绑定用户手机号和openid
                    if (!StringUtils.equals(p.getOpenid(), openid) && !"undefined".equals(openid)) {//undefined不更新数据库
                        //patient.setOpenid(openid);
                        patientService.updatePatient(p, openid);
                    }
                    // 用户校验通过,生成token
                    Token token = tokenService.newTxToken(p.getCode(), openid);
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    map.put("id", p.getId());
                    map.put("uid", p.getCode());
                    map.put("name", p.getName());
                    map.put("token", token.getToken());
                    map.put("photo", p.getPhoto());
                    if (StringUtils.isNoneEmpty(openid)) {
                        //发送微信模板
                        familyService.sendWXMessage(p);
                    }
                    loginLog.setLoginType("1");
                    loginLogService.saveLog(loginLog);
                    //判断是否打过标签
                   //if (!(Patient.isWchatTage.yes.getValue() == p.getIsWxtag())) {
                    //给患者打微信标签
                    weiXinTagUtil.addTagWithOpenid(openid, p.getCode(), p.getName());
                    //}
                    return write(200, "登录成功", "data", map);
                } else {
                    errorMessage = "密码错误,登录失败";
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                }
            }
            //短信登录
            if (StringUtils.isNoneEmpty(mobile) && StringUtils.isNoneEmpty(captcha)) {
                List<Patient> patients = patientService.findByMobile(mobile);
                if (patients.size() > 1) {
                    return error(-1, "此手机存在多个用户,请用身份证和密码登录!");
                }
                // 对验证码进行校验
                int res = smsService.check(mobile, 4, captcha);
                switch (res) {
                    case -2: {
                        errorMessage = "验证码已过期!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case -1: {
                        errorMessage = "请输入正确的验证码!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    case 0: {
                        errorMessage = "验证码无效!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                }
                loginLog.setLoginType("1");
                if (patients == null || patients.size() == 0) {
                    if (mobile.length() == 11) {
                        errorMessage = "该手机号暂未注册账号,请确认后重新输入!";
                    } else {
                        errorMessage = "该身份证号暂未注册账号,请确认后重新输入!";
                    }
                    loginLog.setErrorMessage(errorMessage);
                    loginLogService.saveLog(loginLog);
                    return error(-1, errorMessage);
                } else {
                    Patient p = null;
                    if (patients.size() == 1) {
                        p = patients.get(0);
                    }
                    if (p.getStatus() == 0) {
                        if (mobile.length() == 11) {
                            errorMessage = "该手机号已被禁止使用!";
                        } else {
                            errorMessage = "该身份证号已被禁止使用!";
                        }
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    } else if (p.getStatus() == 2) {
                        errorMessage = "该账号正在审核中,请确认审核通过后再登录,“如有疑问,拨打400-6677-400转2人工客服”";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    } else if (StringUtils.isEmpty(openid)) {
                        errorMessage = "无效的OpenID!";
                        loginLog.setErrorMessage(errorMessage);
                        loginLogService.saveLog(loginLog);
                        return error(-1, errorMessage);
                    }
                    loginLog.setUserCode(p.getCode());
                    // 绑定用户手机号和openid
                    if (!StringUtils.equals(p.getOpenid(), openid) && !"undefined".equals(openid)) {//undefined不更新数据库
                        //patient.setOpenid(openid);
                        patientService.updatePatient(p, openid);
                    }
                    // 用户校验通过,生成token
                    Token token = tokenService.newTxToken(p.getCode(), openid);
                    Map<Object, Object> map = new HashMap<Object, Object>();
                    map.put("id", p.getId());
                    map.put("uid", p.getCode());
                    map.put("name", p.getName());
                    map.put("token", token.getToken());
                    map.put("photo", p.getPhoto());
                    if (StringUtils.isNoneEmpty(openid)) {
                        //发送微信模板
                        familyService.sendWXMessage(p);
                    }
                    loginLog.setType("1");
                    loginLogService.saveLog(loginLog);
                    //判断是否打过标签
                    //if (!(Patient.isWchatTage.yes.getValue() == p.getIsWxtag())) {
                        //给患者打微信标签
                        weiXinTagUtil.addTagWithOpenid(openid, p.getCode(), p.getName());
                    //}
                    return write(200, "登录成功", "data", map);
                }
            }
            return error(-1, "登录失败");
        } catch (Exception e) {
            errorMessage = "系统异常,登录失败";
            loginLog.setErrorMessage(errorMessage);
            loginLogService.saveLog(loginLog);
            error(e);
            return error(-1, "系统异常,登录失败");
        }
    }
    /**
     * 获取签名signature
     *
     * @param pageUrl 需要签名的页面全地址(?后的也需要除了#后的不需要)
     * @return
     */
    @RequestMapping(value = "getSign", method = RequestMethod.POST)
    @ResponseBody
    public String getSign(String pageUrl) {
        try {
            String ticket = getJsapi_ticketByToken();
            if (ticket != null) {
                String noncestr = UUID.randomUUID().toString();
                long timestamp = System.currentTimeMillis() / 1000;
                String url = pageUrl;
                String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
                // sha1加密
                String signature = SHA1(str);
                Map<Object, Object> map = new HashMap<Object, Object>();
                map.put("noncestr", noncestr);
                map.put("timestamp", timestamp);
                map.put("signature", signature);
                return write(200, "获取签名成功", "data", map);
            } else
                return error(-1, "获取签名失败");
        } catch (Exception e) {
            error(e);
        }
        return error(-1, "获取签名失败");
    }
    /**
     * 获取微信openid
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "getOpenidByCode", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getOpenidByCode(String code) {
        try {
            String openid = super.getOpenidByCode(code);
            if (!StringUtils.isEmpty(openid)) {
                return write(200, "获取openid成功!", "openid", openid);
            } else {
                return error(-1, "获取openid失败!");
            }
        } catch (Exception e) {
            error(e);
            return error(-1, "获取openid失败!");
        }
    }
}

+ 42 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/area/AreaController.java

@ -0,0 +1,42 @@
package com.yihu.wlyy.web.common.area;
import com.yihu.wlyy.entity.address.Town;
import com.yihu.wlyy.service.common.area.AreaService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by lyr-pc on 2016/11/22.
 */
@RestController
@RequestMapping(value = "/area")
@Api(description = "城市、城镇管理")
public class AreaController extends BaseController {
    @Autowired
    AreaService areaService;
    /**
     * 查询城市下的城镇
     *
     * @param city 城市
     * @return
     */
    @RequestMapping(value = "/{city}/towns", method = RequestMethod.GET)
    public String getCityTowns(@PathVariable String city) {
        try {
            List<Town> towns = areaService.getCityTowns(city);
            return write(200, "查询成功", "data", towns == null ? new ArrayList<Town>() : towns);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 48 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/data/DataController.java

@ -0,0 +1,48 @@
package com.yihu.wlyy.web.common.data;
import com.yihu.wlyy.entity.dict.Disease;
import com.yihu.wlyy.service.common.data.DataService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@RequestMapping(value = "/common/data", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Controller
@Api(description = "疾病与社区")
public class DataController extends BaseController {
	@Autowired
	private DataService dataService;
	@RequestMapping(value = "diseases",method = RequestMethod.POST)
	@ResponseBody
	public String diseases() {
		try {
			JSONArray array = new JSONArray();
			List<Disease> list = dataService.findAllDisease();
			for (Disease temp : list) {
				if (temp == null) {
					continue;
				}
				JSONObject json = new JSONObject();
				json.put("code", temp.getCode());
				json.put("name", temp.getName());
				array.put(json);
			}
			return write(200, "获取疾病成功!", "list", array);
		} catch (Exception e) {
			error(e);
			return error(-1, "获取疾病失败!");
		}
	}
}

+ 65 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/device/DeviceController.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.web.common.device;
import com.yihu.wlyy.entity.device.Device;
import com.yihu.wlyy.entity.device.DeviceCategory;
import com.yihu.wlyy.service.app.device.DeviceService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping(value = "/common/device", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "设备管理")
public class DeviceController extends BaseController {
    @Autowired
    private DeviceService deviceService;
    @ApiOperation("获取设备分类")
    @RequestMapping(value = "DeviceCategory", method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String getDeviceCategory() {
        try {
            List<DeviceCategory> list = deviceService.findAllCategory();
            return write(200, "获取设备分类成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "获取设备分类失败!");
        }
    }
    @ApiOperation("获取设备列表")
    @RequestMapping(value = "DeviceList", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceList(@ApiParam(name = "category_code", value = "设备类型代码", defaultValue = "1")
                                @RequestParam(value = "category_code", required = true) String categoryCode) {
        try {
            List<Device> list = deviceService.findDeviceByCategory(categoryCode);
            return write(200, "获取设备列表成功!", "data", list);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "获取设备列表失败!");
        }
    }
    @ApiOperation("获取设备信息")
    @RequestMapping(value = "DeviceInfo", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String getDeviceInfo(@ApiParam(name = "id", value = "设备ID", defaultValue = "19")
                                @RequestParam(value = "id", required = true) String id) {
        try {
            Device device = deviceService.findById(id);
            return write(200, "查询成功", "data", device);
        } catch (Exception ex) {
            return invalidUserException(ex, -1, ex.getMessage());
        }
    }
}

+ 45 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/district/DistrictController.java

@ -0,0 +1,45 @@
package com.yihu.wlyy.web.common.district;
import com.yihu.wlyy.service.common.district.DistrictService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
 * 省市区三级地址控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "省市区三级地址")
public class DistrictController extends BaseController {
	@Autowired
	private DistrictService districtService;
	/**
	 * 省市一二三级查询接口
	 * @param type 1一级目录,2二级目录,3三级目录,4街道目录
	 * @param code 省或市标识
	 * @return
	 */
	@RequestMapping(value = "district",method = RequestMethod.POST)
	@ResponseBody
	public String district(int type, String code) {
		try {
			List<?> list = districtService.findByType(type, code);
			return write(200, "查询成功!", "list", list);
		} catch (Exception e) {
			error(e);
			return error(-1, "查询失败!");
		}
	}
}

+ 88 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/FoodCompController.java

@ -0,0 +1,88 @@
package com.yihu.wlyy.web.common.health;
import com.yihu.wlyy.entity.education.FoodComp;
import com.yihu.wlyy.service.app.health.FoodCompService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
 * 患者端:食物热量查询
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/common/health/food", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者端-食物热量查询")
public class FoodCompController extends BaseController {
    @Autowired
    private FoodCompService foodCompService;
    /**
     * 查询食物热量列表
     *
     * @param pid 父id
     * @return 列表
     */
    @ApiOperation("查询食物热量列表")
    @RequestMapping(value = "list", method = RequestMethod.POST)
    @ResponseBody
    public String list(@RequestParam("pid") long pid) {
        try {
            List<FoodComp> foodComps = foodCompService.getByPid(pid);
            return write(200, "查询成功", "list", foodComps);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 查询食物热量查询
     *
     * @param name 查询名称
     * @return 列表
     */
    @ApiOperation("查询食物热量查询")
    @RequestMapping(value = "search", method = RequestMethod.POST)
    @ResponseBody
    public String list(@RequestParam("name") String name) {
        try {
            List<FoodComp> foodComps = foodCompService.getByName(name);
            return write(200, "查询成功", "list", foodComps);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
    /**
     * 查询食物热量详情
     *
     * @param id 查询名称
     * @return 列表
     */
    @ApiOperation("查询食物热量详情")
    @RequestMapping(value = "detail", method = RequestMethod.POST)
    @ResponseBody
    public String list(@RequestParam("id") Long id) {
        try {
            FoodComp foodComp = foodCompService.getById(id);
            return write(200, "查询成功", "list", foodComp);
        } catch (Exception ex) {
            error(ex);
            return invalidUserException(ex, -1, "查询失败!");
        }
    }
}

+ 63 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/health/HealthEduArticlesController.java

@ -0,0 +1,63 @@
package com.yihu.wlyy.web.common.health;
import com.yihu.wlyy.service.app.health.HealthEduArticleService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by Reece on 2017/2/13.
 */
@Controller
@RequestMapping(value = "/common")
@Api(description = "获取福州健康教育文章并保存")
public class HealthEduArticlesController extends BaseController{
    @Autowired
    private HealthEduArticleService healthEduArticleService;
    @RequestMapping(value = "getHealthEduArticles",method = RequestMethod.GET)
    @ResponseBody
    public String getHealthEduArticles(
            @RequestParam(value = "医院名称") String hospitalName,
            @RequestParam(value = "开始时间") String startTime,
            @RequestParam(value = "截至时间") String endTime,
            @RequestParam(value = "文章来源 0 医生自创 1健康之路 2 39健康网") String MessageFrom,
            @RequestParam(value = "获取文章数量默认10",defaultValue = "10") String pageSize,
            @RequestParam(value = "展示页数,从0开始",defaultValue = "0") String pageNumber
    ){
        try {
            Map<String,String> params = new HashMap<>();
            params.put("hospitalName",hospitalName);
            params.put("startTime",startTime);
            params.put("endTime",endTime);
            params.put("MessageFrom",MessageFrom);
            params.put("pageSize",pageSize);
            params.put("pageNumber",pageNumber);
//      timestamp必须与服务器时间相差在5分钟以内,否则调用将失败
            String timestamp = Long.toString(System.currentTimeMillis());
            params.put("timestamp",timestamp);
//          获取福州健康教育文章
            String result = healthEduArticleService.getHealthEduArticles(params);
//          保存福州健康教育文章
            int rows = healthEduArticleService.saveHealthEduArticles(result);
            if(rows>0){
                return write(200, "数据导入成功");
            }
            return write(-1, "数据导入失败!");
        }catch (Exception e){
            return error(-1, "数据导入失败!");
        }
    }
}

+ 49 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/hospital/HospitalCommonController.java

@ -0,0 +1,49 @@
package com.yihu.wlyy.web.common.hospital;
import com.yihu.wlyy.entity.organization.Hospital;
import com.yihu.wlyy.service.app.hospital.HospitalService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by lyr-pc on 2016/11/22.
 */
@RestController
@RequestMapping(value = "/hospitals")
@Api(description = "医院管理")
public class HospitalCommonController extends BaseController {
    @Autowired
    HospitalService hospitalService;
    @RequestMapping(value = "/{town}/community_hospitals",method = RequestMethod.GET)
    @ApiOperation(value = "查询城镇下社区")
    public String getTownHospitals(@PathVariable String town) {
        try {
            List<Hospital> hospitals = hospitalService.getHositalByTownCode(town);
            return write(200, "查询成功", "data", hospitals == null ? new ArrayList<Hospital>() : hospitals);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    @RequestMapping(value = "/getHospitalsNot00",method = RequestMethod.GET)
    @ApiOperation(value = "查询健管师所属的社区下的服务站")
    public String getHospitalsNot00() {
        try {
            List<Hospital> hospitals = hospitalService.getHospitalsNot00(getUID());
            return write(200, "查询成功", "data", hospitals == null ? new ArrayList<Hospital>() : hospitals);
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
}

+ 80 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/icd/Icd10Controller.java

@ -0,0 +1,80 @@
package com.yihu.wlyy.web.common.icd;
import com.yihu.wlyy.service.system.Icd10DictServcie;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
 * Created by chenweida on 2017/8/9.
 */
@RestController
@RequestMapping("/idc10/")
@Api(description = "icd10和健康问题接口管理")
public class Icd10Controller extends BaseController {
    @Autowired
    private Icd10DictServcie icd10DictServcie;
    @ApiOperation("根据icd10字典的code找到name")
    @RequestMapping(value = "/getIdc10NameByCode", method = RequestMethod.GET)
    public String getTopic(
            @ApiParam(required = true, name = "code", value = "icd10字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getIcd10Name(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("根据icd10的code找到健康问题字典")
    @RequestMapping(value = "/getIcd10ByHealthProCode", method = RequestMethod.GET)
    public String getIcd10ByHealthProCode(
            @ApiParam(required = true, name = "code", value = "icd10字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getIcd10ByHealthProblemCode(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("根据健康问题字典的code找到name")
    @RequestMapping(value = "/getHealthProNameByCode", method = RequestMethod.GET)
    public String getHealthProNameByCode(
            @ApiParam(required = true, name = "code", value = "健康问题字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getHealthProblemName(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("根据健康问题字典的code找到icd10字典")
    @RequestMapping(value = "/getHealthProByIcd10Code", method = RequestMethod.GET)
    public String getHealthProByIcd10Code(
            @ApiParam(required = true, name = "code", value = "健康问题字典code") @RequestParam(required = true, value = "code") String code) {
        try {
            return write(200, "查询成功", "data", icd10DictServcie.getHealthProblemsByIcd10Code(code));
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    @ApiOperation("初始化全部数据到redis")
    @RequestMapping(value = "/init2Redis", method = RequestMethod.POST)
    public String init2Redis() {
        try {
            icd10DictServcie.cacheDict();
            return write(200, "查询成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
}

+ 350 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/im/imController.java

@ -0,0 +1,350 @@
package com.yihu.wlyy.web.common.im;
import com.yihu.wlyy.entity.consult.Consult;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.repository.consult.ConsultDao;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.SignFamilyDao;
import com.yihu.wlyy.util.ImUtill;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.*;
@RestController
@RequestMapping(value = "im_new", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "IM-即时消息")
public class imController extends BaseController {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SignFamilyDao signFamilyDao;
    @Autowired
    private DoctorDao doctorDao;
    @Autowired
    private ConsultDao consultDao;
    @Autowired
    private ImUtill ImUtill;
    /**
     * 获取单个咨询
     *
     * @param consult
     * @return
     */
    @RequestMapping(value = "/getTopic",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String getTopic(String consult) {
        try {
            return success(ImUtill.getTopic(consult).get("data").toString());
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }
    /**
     * 获取当前团队的咨询列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamList", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam int adminTeamCode,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = ImUtill.getTeamConsultByStatus(doctor,adminTeamCode, status, reply, page, pagesize);
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }
                map.put("id", id);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型:1三师咨询,2家庭医生咨询,3图文咨询,4公共咨询,5病友圈
                map.put("type", con.getType());
                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getList", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @ApiParam(name = "type", value = "咨询类型") @RequestParam(required = false) Integer type,
            @ApiParam(name = "patientName", value = "居民姓名") @RequestParam(required = false) String patientName,
            @ApiParam(name = "startTime", value = "开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime,
            @RequestParam int page,
            @RequestParam int pagesize) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = null;
            if(type==null){
                consult = ImUtill.getConsultByStatus(doctor, status, reply, page, pagesize);
            }else {
                consult = ImUtill.getConsultByStatusAndType(doctor, status, reply,type,patientName,startTime,endTime, page, pagesize);
            }
            JSONArray jsonArray = new JSONArray(consult);
            Iterator<Object> it = jsonArray.iterator();
            List list = new ArrayList();
            while (it.hasNext()) {
                Map map = new HashMap();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                JSONObject ob = (JSONObject) it.next();
                String id = ob.get("id").toString();
                String avatar = ob.get("avatar").toString();
                String session_id = ob.get("session_id").toString();
                String name = ob.get("patient_name").toString();
                String createTime = ob.get("create_time").toString();
                String description = ob.get("description").toString();
                String sex = ob.get("sex").toString();
                String startId = ob.get("start_message_id").toString();
                String endId = ob.get("end_message_id").toString();
                Consult con = consultDao.findTypeByCode(id);
                System.out.println("consult========>" + con);
                System.out.println("consultId========>" + id);
                if (StringUtils.isNotEmpty(createTime)) {
                    Date date = sdf.parse(createTime);
                    map.put("create_time", sdf.format(date));
                }
                map.put("id", id);
                map.put("status", status);
                map.put("session_id", session_id);
                map.put("photo", avatar);
                map.put("patientName", name);
                map.put("patient", con.getPatient());
                map.put("sex", sex);
                map.put("description", description);
                map.put("start_message_id", startId);
                map.put("end_message_id", endId);
//                咨询类型:1三师咨询,2家庭医生咨询,3图文咨询,4公共咨询,5病友圈
                map.put("type", con.getType());
                list.add(map);
            }
            return write(200, "查询成功", "data", list);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取列表
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     * 第一次列表为当前医生(很可能团队长)待回复列表 传参:doctor有后台获取 status=0,reply=0未回复
     * 后 取团队内单个医生的咨询情况 doctor、status、reply均有前端传入
     *
     * @return
     */
    @RequestMapping(value = "/consult/getListCount", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultCountByStatus(
            @RequestParam(required = false) String doctor,
            @RequestParam Integer status,
            @RequestParam(required = false) Integer reply,
            @ApiParam(name = "type", value = "咨询类型") @RequestParam(required = true) Integer type,
            @ApiParam(name = "patientName", value = "居民姓名") @RequestParam(required = false) String patientName,
            @ApiParam(name = "startTime", value = "开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(name = "endTime", value = "结束时间") @RequestParam(required = false) String endTime) {
        try {
            if (StringUtils.isEmpty(doctor)) {
                doctor = getUID();
            }
            String consult = null;
            consult = ImUtill.getConsultCountByStatusAndType(doctor, status, reply,type,patientName,startTime,endTime);
            JSONObject json = new JSONObject(consult);
            return write(200, "查询成功", "total", json.getInt("count"));
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取团队统计数据
     * status = 10 已结束的咨询,status=0,reply = 1 已回复 ,status=0,reply=0未回复
     *
     * @return
     */
    @RequestMapping(value = "/consult/getTeamData", method = RequestMethod.GET)
    @ResponseBody
    public String getTeamData(@RequestParam int adminTeamCode) {
        try {
            String uid = getUID();
            List<Map<String, Object>> doctors = getMemberByDoctor(uid);
            JSONObject json = new JSONObject();
            List list = new ArrayList();
            int countUnReply = 0;
            int countReply = 0;
            int countConsult = 0;
//        团队下的医生统计数量
            for (Map<String, Object> doc : doctors) {
                Map map = new HashMap();
                String doctor = doc.get("code").toString();
                map.put("photo", doc.get("photo") == null ? "" : doc.get("photo").toString());
                map.put("name", doc.get("name").toString());
                map.put("sex", doc.get("sex").toString());
                map.put("doctor", doctor);
                map.put("type", doc.get("level") == null ? "" : doc.get("level").toString());
//                未回复
                String totalUnReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 0);
                int unReply = Integer.parseInt(totalUnReply);
                map.put("totalUnReply", unReply);
//                已回复
                String totalReply = ImUtill.getConsultData(doctor,adminTeamCode, 0, 1);
                String totalReply1 = ImUtill.getConsultData(doctor,adminTeamCode, 10, null);
                int reply = Integer.parseInt(totalReply) + Integer.parseInt(totalReply1);
                map.put("totalReply", reply);
//                总咨询量
                String totalConsult = ImUtill.getConsultData(doctor, adminTeamCode,null, null);
                int consult = Integer.parseInt(totalConsult);
                map.put("totalConsult", consult);
                countUnReply += unReply;
                countReply += reply;
                countConsult += consult;
                list.add(map);
            }
            json.put("totalUnReply", countUnReply);
            json.put("totalReply", countReply);
            json.put("totalConsult", countConsult);
            json.put("doctors", list);
            return write(200, "查询成功", "data", json);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 获取团队医生下居民的咨询
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/getConsultByPatient", method = RequestMethod.GET)
    @ResponseBody
    public String getConsultByPatient(@RequestParam String patient) {
        try {
//            1.调im接口
//            2.判断团队长和当前咨询居民是否存在签约关系
            String doctor = getUID();
            int count = signFamilyDao.findByPatientAndDoctor(patient, doctor);
            boolean flag = (count == 0) ? false : true;
            return write(200, "查询成功", "data", flag);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    /**
     * 提醒医生相关信息
     *
     * @param doctor  提醒的医生
     * @param content 提醒的内容
     * @return
     */
    @RequestMapping(value = "/message/remain", method = RequestMethod.POST)
    @ResponseBody
    public String reaminDoctor(String doctor, String content) {
        try {
            JSONObject participants = new JSONObject();
            participants.put(doctor, 0);
            participants.put(getUID(), 0);
            Doctor d = doctorDao.findByCode(getUID());
            //创建医生会话讨论组
            JSONObject sessionObj = ImUtill.createSession(participants, ImUtill.SESSION_TYPE_P2P, d.getName() + "发来消息提醒", "");
            if (sessionObj.getInt("status") == -1) {
                throw new RuntimeException(sessionObj.getString("message"));
            }
            JSONObject session = sessionObj.getJSONObject("data");
            ImUtill.sendImMsg(getUID(), d.getName(), session.getString("id"), "1", content, "REMAIN");
            return success("提醒成功!");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败!");
        }
    }
    public List getMemberByDoctor(String doctor) {
        String sql = "SELECT d.photo,d.`name`,d.sex,d.`code`,d.level " +
                " from wlyy_admin_team t,wlyy_admin_team_member m,wlyy_doctor d " +
                " where t.id = m.team_id and m.doctor_code = d.`code` and t.available = 1 and m.available=1 " +
                " and t.leader_code = ? ";
        List<Map<String, Object>> doctors = jdbcTemplate.queryForList(sql, doctor);
        return doctors;
    }
}

+ 35 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/messages/ImMessageController.java

@ -0,0 +1,35 @@
package com.yihu.wlyy.web.common.messages;
import com.yihu.wlyy.service.app.message.MessageService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/im/common/message", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "医生端-消息")
public class ImMessageController extends BaseController {
    @Autowired
    private MessageService messageService;
    @RequestMapping(value = "messages",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    @ApiOperation("查询医生未读消息和最后消息")
    public String messages() {
        try {
            JSONObject json = messageService.findDoctorAllMessage(getUID());
            return write(200, "获取消息总数成功!", "data", json);
        } catch (Exception e) {
            error(e);
            return error(-1, e.getMessage());
        }
    }
}

+ 399 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/qrcode/QrCodeController.java

@ -0,0 +1,399 @@
package com.yihu.wlyy.web.common.qrcode;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.service.common.QrcodeService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * Created by lyr on 2016/08/10.
 */
@Controller
@RequestMapping(value = "/qrcode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "二维码")
public class QrCodeController extends WeixinBaseController {
    @Autowired
    private QrcodeService qrcodeService;
    @Autowired
    private DoctorService doctorService;
    @RequestMapping(value = "/doctors",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeDoctorQrcodes(String hospital) {
        try {
            if (qrcodeService.makeDoctorQrCode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成某个医生的二维码
     *
     * @param doctor
     * @return
     */
    @RequestMapping(value = "/doctor",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeDoctorQrcode(String doctor) {
        try {
            if (qrcodeService.makeDoctorQrcode(doctor, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成社区二维码
     *
     * @param hospital
     * @return
     */
    @RequestMapping(value = "/hospital",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeHospitalQrcode(String hospital) {
        try {
            if (qrcodeService.makeHospitalQrcode(hospital, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 生成区二维码
     *
     * @param town
     * @return
     */
    @RequestMapping(value = "/town",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String makeTownQrcode(String town) {
        try {
            if (qrcodeService.makeTownQrcode(town, getAccessToken())) {
                return write(200, "生成二维码成功!");
            } else {
                return error(-1, "生成二维码失败!");
            }
        } catch (Exception e) {
            return error(-1, "生成二维码失败!");
        }
    }
    /**
     * 下载某个社区的二维码
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/hospital_img",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadSqQrcode(String hospital, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + hospital + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeHospitalQrcode(hospital, getAccessToken());
            } else {
                flag = true;
            }
            if (flag = true) {
                response.setCharacterEncoding("utf-8");
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + hospital + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
        }
    }
    /**
     * 下载某个区的二维码
     *
     * @param town
     * @param response
     */
    @RequestMapping(value = "/town_img",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadTownQrcode(String town, HttpServletResponse response) {
        try {
            File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                    File.separator + "qrcode" + File.separator + town + ".png");
            boolean flag = false;
            if (!file.exists()) {
                flag = qrcodeService.makeTownQrcode(town, getAccessToken());
            } else {
                flag = true;
            }
            if (flag = true) {
                response.setCharacterEncoding("utf-8");
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + town + ".png";
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(404);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/download",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadQrcode(String doctor, HttpServletResponse response) {
        try {
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());
                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + doc.getQrcode());
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载某个医生的二维码
     *
     * @param doctor
     * @param response
     */
    @RequestMapping(value = "/doctor_img",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadQrcodeImage(String doctor, HttpServletResponse response) {
        try {
            System.out.println("------------------doctor:" + doctor);
            Doctor doc = doctorService.findDoctorByCode(doctor);
            if (doc != null) {
                if (StringUtils.isEmpty(doc.getQrcode())) {
                    qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                    doc = doctorService.findDoctorByCode(doctor);
                } else {
                    File file = new File(QrCodeController.class.getResource("/").getPath().replace("/WEB-INF/classes/", "") +
                            File.separator + "qrcode" + File.separator + doc.getQrcode());
                    if (!file.exists()) {
                        qrcodeService.makeDoctorQrcode(doctor, getAccessToken());
                        doc = doctorService.findDoctorByCode(doctor);
                    }
                }
                String path = request.getSession().getServletContext().getRealPath("/")
                        + File.separator + "qrcode" + File.separator + doc.getQrcode();
                InputStream inputStream = new FileInputStream(path);
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=" + doc.getQrcode());
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                throw new Exception("医生信息不存在!");
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载所有医生的二维码图片
     *
     * @param hospital
     * @param response
     */
    @RequestMapping(value = "/download/doctors",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadQrcodes(String hospital, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadDoctorQrCodes(hospital, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=doctors_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载某个区的社区的二维码图片
     *
     * @param area
     * @param response
     */
    @RequestMapping(value = "/download/hospitals",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadSqQrcodes(String area, HttpServletResponse response) {
        try {
            File file = qrcodeService.downloadHospitalQrCodes(area, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=hospitals_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
    /**
     * 下载某个城市的区的二维码图片 t
     *
     * @param city
     * @param response
     */
    @RequestMapping(value = "/download/towns",method = {RequestMethod.GET,RequestMethod.POST})
    public void downloadTownQrcodes(String city, HttpServletResponse response) {
        try {
            File file = qrcodeService.downLoadTownQrcodes(city, getAccessToken());
            if (file != null) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName=towns_qrcode.zip");
                InputStream inputStream = new FileInputStream(file);
                OutputStream outputStream = response.getOutputStream();
                byte[] b = new byte[2048];
                int length = 0;
                while ((length = inputStream.read(b)) > 0) {
                    outputStream.write(b, 0, length);
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
            } else {
                response.setStatus(500);
            }
        } catch (Exception e) {
            response.setStatus(500);
        }
    }
}

+ 115 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/sms/SMSController.java

@ -0,0 +1,115 @@
package com.yihu.wlyy.web.common.sms;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.repository.doctor.DoctorDao;
import com.yihu.wlyy.repository.patient.PatientDao;
import com.yihu.wlyy.service.common.SMSService;
import com.yihu.wlyy.util.NetworkUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@Controller
@RequestMapping(value = "/common")
@Api(description = "短信")
public class SMSController extends BaseController {
	@Autowired
	public SMSService smsService;
	@Autowired
	private PatientDao patientDao;
	@Autowired
	private DoctorDao doctorDao;
	/**
	 * 发送短信验证码接口
	 * @param mobile 手机号
	 * @param type 消息类型:1微信端注册,2微信端找回密码,3医生端找回密码,4患者登录,5医生登录 .6患者签约验证 7用户变更手机号验证 8用户新手机号验证 9绑定手机号
	 *             10 家庭成员添加验证
	 * @return
	 */
	@RequestMapping(value = "captcha", method = RequestMethod.POST)
	@ResponseBody
	public String send(String mobile, int type, @RequestParam(required = false) String captchaToken) {
		try {
			if (type > 10 || type < 1) {
				return error(-1, "无效的请求!");
			}
			if (StringUtils.isEmpty(mobile)) {
				return error(-1, "手机号码不允许为空!");
			}
			if (type == 4) {
				// 登录时校验用户是否存在
				List<Patient> patients = patientDao.findByMobile(mobile);
				if (patients == null||patients.size()==0) {
					return error(-1, "该手机号未注册!");
				}
			} else if (type == 5) {
				// 登录时校验用户是否存在
				Doctor doctor = doctorDao.findByMobile(mobile);
				if (doctor == null) {
					return error(-1, "该手机号未注册!");
				}
			}
			if (StringUtils.isNotEmpty(captchaToken)) {
				String ct = request.getSession().getAttribute("captchaToken").toString();
				if (!StringUtils.equalsIgnoreCase(captchaToken, ct)) {
					return error(-1, "图形验证码错误!");
				}
			}
			// 获取ip地址
			String ip = NetworkUtil.getIpAddress(request);
			if (StringUtils.isEmpty(ip)) {
				return error(-1, "无效的ip请求!");
			}
//			String res = smsService.send(mobile, ip, type, getUID());
			String res = smsService.send(mobile, ip, type, getRepUID());
			if (StringUtils.equals(res, "ok")) {
				return write(200, "验证码短信已发送!");
			} else {
				return error(-1, res);
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "短信发送失败!");
		}
	}
	/**
	 * 验证手机验证码
	 * @param type 消息类型:1微信端注册,2微信端找回密码,3医生端找回密码
	 * @param mobile
	 * @param captcha
	 * @return
	 */
	@RequestMapping(value = "check_captcha", method = RequestMethod.POST)
	@ResponseBody
	public String checkCaptcha(int type, String mobile, String captcha) {
		try {
			// 对验证码进行校验
			int res = smsService.check(mobile, type, captcha);
			switch (res) {
			case -2:
				return error(-1, "验证码已过期!");
			case -1:
				return error(-1, "验证码错误!");
			case 0:
				return error(-1, "验证码无效!");
			}
			return success("有效验证码!");
		} catch (Exception e) {
			error(e);
			return error(-1, "验证码检查失败!");
		}
	}
}

+ 62 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/system/SystemDictController.java

@ -0,0 +1,62 @@
package com.yihu.wlyy.web.common.system;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.service.system.SystemDictService;
import com.yihu.wlyy.web.BaseController;
import com.yihu.wlyy.web.manager.Index;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
 * Created by Administrator on 2016/8/13.
 */
@Controller
@RequestMapping(value = "/common", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "系统字典")
public class SystemDictController extends BaseController {
    @Autowired
    private SystemDictService systemDictService;
    @ApiOperation("根據dictname查找字典数据")
    @RequestMapping(value = "/getDictByDictName", produces = "application/json;charset=UTF-8", method = RequestMethod.GET)
    @ResponseBody
    public String getDictByDictName(
            @ApiParam(name="name",value="字典名",defaultValue = "")@RequestParam(value="name",required = true) String name){
        try {
            List<SystemDict> list=systemDictService.getDictByDictName(name);
            JSONArray ja=new JSONArray();
            for (SystemDict systemDict:list){
                JSONObject jo=new JSONObject();
                jo.put("code",systemDict.getCode());
                jo.put("value",systemDict.getValue());
                ja.put(jo);
            }
            return write(200,"查询成功","list",ja);
        } catch (Exception e) {
            error(e);
            return error(-1, "验证码检查失败!");
        }
    }
    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ApiOperation("测试方法")
    @ResponseBody
    public Index index(
            @ApiParam(name="name",required = false,value = "参数") @RequestParam(required = false,name = "name") String name
    ) {
        return new Index();
    }
}

+ 45 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/url/CudUrlController.java

@ -0,0 +1,45 @@
package com.yihu.wlyy.web.common.url;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
 * Created by lyr-pc on 2017/1/17.
 */
@RestController
@RequestMapping(value = "/common/cud_url")
@Api("增删改路径查询")
public class CudUrlController extends BaseController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * 查询增删改路径
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation(value = "查询增删改路径")
    public String getCudUrl() {
        try {
            String sql = "select * from wlyy_cud_url";
            List<Map<String,Object>> result = jdbcTemplate.queryForList(sql);
            return write(200,"查询成功","data",result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }
}

+ 108 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/CaptchaController.java

@ -0,0 +1,108 @@
package com.yihu.wlyy.web.common.util;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
 * 患者端验证码生成控制器。验证码生成后保存到Redis中,并将Redis的Key与图片路径返回。
 * 客户端获取图片,并由用户输入后,与redis的key一块返回,用于验证是否出错。
 *
 * @author Sand
 * @created 2016/09/28
 */
@Api(description = "验证码")
@RestController
@RequestMapping(value = "/patient/captcha", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CaptchaController extends BaseController {
    private Map<String, String> captchaCache = new ConcurrentHashMap<>();
    private DefaultKaptcha captchaProducer = new DefaultKaptcha();
    public CaptchaController() {
        Properties properties = new Properties();
        properties.put("kaptcha.textproducer.font.color", "blue");
        properties.put("kaptcha.textproducer.font.size", "45");
        properties.put("kaptcha.textproducer.char.length", "4");
        properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        Config config = new Config(properties);
        captchaProducer.setConfig(config);
    }
    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation("生成验证码,用于第一次请求")
    public String createCaptcha(){
        try{
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    @RequestMapping(value = "/{legacy_key}", method = RequestMethod.POST)
    @ApiOperation("刷新验证码,需提供第一次生成验证码返回的key")
    public String refreshCaptcha(@PathVariable("legacy_key") String legacyKey){
        try{
            cleanCaptcha(legacyKey);
            return generateCaptcha();
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    @RequestMapping(value = "/{key}", method = RequestMethod.GET)
    @ApiOperation("校验证码,提供key及用户输入的验证码")
    public String verifyCaptcha(@PathVariable("key") String key,
                                @RequestParam("text") String text){
        try{
            boolean pass = false;
            String captcha = captchaCache.get(key);
            if (captcha != null && captcha.equals(text.toLowerCase())){
                pass = true;
                cleanCaptcha(key);
            }
            return write(200, "ok", "pass", pass);
        } catch (Exception e){
            return error(500, e.getMessage());
        }
    }
    private String generateCaptcha() throws IOException {
        String captchaText = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(captchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        String base64Img = new BASE64Encoder().encode(outputStream.toByteArray());
        String key = "captcha:" + UUID.randomUUID().toString() + ":text";
        Map<String, String> data = new HashMap<>();
        data.put("key", key);
        data.put("image", base64Img);
        data.put("format", "png");
        captchaCache.put(key, captchaText.toLowerCase());
        return write(200, "ok", "data", data);
    }
    private void cleanCaptcha(String key){
        captchaCache.remove(key);
    }
}

+ 353 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/ManagerUtilController.java

@ -0,0 +1,353 @@
package com.yihu.wlyy.web.common.util;
import com.alibaba.fastjson.JSONObject;
import com.yihu.wlyy.interceptors.DoctorInterceptor;
import com.yihu.wlyy.interceptors.GateWayInterceptor;
import com.yihu.wlyy.interceptors.PatientInterceptor;
import com.yihu.wlyy.repository.consult.ConsultTeamDoctorDao;
import com.yihu.wlyy.service.app.disease.PatientDiseaseService;
import com.yihu.wlyy.service.app.scheduling.DoctorWorkTimeService;
import com.yihu.wlyy.service.app.statistics.StatisticsService;
import com.yihu.wlyy.service.common.util.ManageUtilService;
import com.yihu.wlyy.service.common.util.SignTeamAndGroupRunnable;
import com.yihu.wlyy.util.SpringUtil;
import com.yihu.wlyy.util.SystemData;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
 * Created by lyr on 2016/09/13.
 */
@RestController
@RequestMapping(value = "/manage_util", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "管理工具及后台任务控制")
public class ManagerUtilController extends BaseController {
    @Autowired
    PatientDiseaseService diseaseService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    DoctorWorkTimeService workTimeService;
    @Autowired
    StatisticsService statisticsService;
    @Autowired
    ManageUtilService manageUtilService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    ConsultTeamDoctorDao consultTeamDoctorDao;
    /*********************************************患者疾病相关******************************************/
    /**
     * 更新到redis
     *
     * @return
     */
    @RequestMapping(value = "/disease/to_redis", method = RequestMethod.POST)
    public String updateToRedid() {
        try {
            diseaseService.updateToRedis();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 更新到疾病表
     *
     * @return
     */
    @RequestMapping(value = "/disease/to_disease", method = RequestMethod.POST)
    public String updateToDisease() {
        try {
            diseaseService.updateToDisease();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 查询患者redis疾病
     *
     * @param patient
     * @return
     */
    @RequestMapping(value = "/disease/patient", method = RequestMethod.POST)
    public String getDiseaseFromRedis(String patient) {
        try {
            return write(200, "查询成功", "data", redisTemplate.opsForValue().get("disease:" + patient));
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /***********************************************名医咨询相关****************************************/
    /**
     * 名医咨询剩余次数手动更新
     *
     * @return
     */
    @RequestMapping(value = "/famous_doctor/times_update", method = RequestMethod.POST)
    public String famousConsultTimeUpdate() {
        try {
            workTimeService.consultTimesRemain(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /*********************************************统计相关*******************************************/
    /**
     * 更新人口数据到redis
     *
     * @return
     */
    @RequestMapping(value = "/people_num_to_redis", method = RequestMethod.POST)
    public String peopleNumToRedis(String year) {
        try {
            statisticsService.peopleNumToRedis(year);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team", method = RequestMethod.POST)
    public String signSetGroupAndTeam() {
        try {
            manageUtilService.signPatientSetGroup();
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team_page", method = RequestMethod.POST)
    public String signSetGroupAndTeamPage(int page) {
        try {
            manageUtilService.setSignTeamAndGroupByPage(page);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_set_group_team_id", method = RequestMethod.POST)
    public String signSetGroupAndTeamId(Long id) {
        try {
            manageUtilService.setSignTeamAndGroupById(id);
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, "更新失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_error_page_id", method = RequestMethod.POST)
    public String getErrorPage(int type) {
        try {
            if (type == 1) {
                return write(200, "查询成功", "data", ManageUtilService.page);
            } else if (type == 2) {
                return write(200, "查询成功", "data", ManageUtilService.errorPages);
            } else {
                return write(200, "查询成功", "data", ManageUtilService.errorSigns);
            }
        } catch (Exception e) {
            return error(-1, "查询失败");
        }
    }
    /**
     * 签约同步数据设置团队和分组
     *
     * @return
     */
    @RequestMapping(value = "/sign_team_group_thread", method = RequestMethod.POST)
    public String getErrorPage(long start, long end) {
        try {
            new Thread(SpringUtil.getBean(SignTeamAndGroupRunnable.class)
                    .setEnd(end).setStart(start)).start();
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 健康教育数据清洗
     *
     * @return
     */
    @RequestMapping(value = "/tranform_edu_article", method = RequestMethod.POST)
    public String tranformEduArticle() {
        try {
            manageUtilService.transformEduArticle();
            return write(200, "启动成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    /**
     * 产检提醒
     * 每天早上六点
     *
     * @return
     */
//    @RequestMapping(value = "/start_prenatal_inspector_job")
//    @ResponseBody
//    public String startPrenatalInspectorJob() {
//        try {
//            if (!quartzHelper.isExistJob("prenatal_inspector_job")) {
//                quartzHelper.addJob(PrenatalInspectorJob.class, "0 0 6 * * ?", "prenatal_inspector_job", new HashMap<String, Object>());
//                return write(200, "启动成功");
//            } else {
//                return write(200, "任务已存在");
//            }
//        } catch (Exception e) {
//            return error(-1, "启动失败");
//        }
//    }
    //---------------------------获取在线人数相关 start---------------------------------
    @RequestMapping(value = "/online_num", method = RequestMethod.GET)
    @ApiOperation("获取在线人数")
    public String online_num() {
        try {
            JSONObject jo = new JSONObject();
            jo.put("doctor_online", SystemData.doctorTokens.size());
            jo.put("pc_online", SystemData.doctorPCTokens.size());
            jo.put("patient_online", SystemData.patientTokens.size());
            return write(200, "启动成功","data",jo);
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    //---------------------------获取在线人数相关 end---------------------------------
    //----------------------------权限相关 start---------------------------------
    @RequestMapping(value = "/closeAll", method = RequestMethod.POST)
    @ApiOperation("关闭全部拦截")
    public String closeAll() {
        try {
            String close = "0";
            DoctorInterceptor.status = close;
            PatientInterceptor.status = close;
            GateWayInterceptor.status = close;
            return write(200, "关闭成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/openAll", method = RequestMethod.POST)
    @ApiOperation("开启全部拦截")
    public String openAll() {
        try {
            String open = "1";
            DoctorInterceptor.status = open;
            PatientInterceptor.status = open;
            GateWayInterceptor.status = open;
            return write(200, "开启成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/closeByType", method = RequestMethod.POST)
    @ApiOperation("根据类型关闭拦截")
    public String closeByType(
            @ApiParam(name = "type", value = "1 患者端 2医生端 3对外", required = true) @RequestParam(value = "type", required = true) String type) {
        try {
            String close = "0";
            switch (type) {
                case "1": {
                    DoctorInterceptor.status = close;
                    break;
                }
                case "2": {
                    PatientInterceptor.status = close;
                    break;
                }
                case "3": {
                    GateWayInterceptor.status = close;
                    break;
                }
            }
            return write(200, "关闭成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    @RequestMapping(value = "/openByTYpe", method = RequestMethod.POST)
    @ApiOperation("根据类型开启拦截")
    public String openByTYpe(
            @ApiParam(name = "type", value = "1 患者端 2医生端 3对外", required = true) @RequestParam(value = "type", required = true) String type) {
        try {
            String open = "1";
            switch (type) {
                case "1": {
                    DoctorInterceptor.status = open;
                    break;
                }
                case "2": {
                    PatientInterceptor.status = open;
                    break;
                }
                case "3": {
                    GateWayInterceptor.status = open;
                    break;
                }
            }
            return write(200, "开启成功");
        } catch (Exception e) {
            return error(-1, "启动失败");
        }
    }
    //----------------------------权限相关 end---------------------------------
}

+ 326 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/util/WlyySerivceController.java

@ -0,0 +1,326 @@
package com.yihu.wlyy.web.common.util;
import com.yihu.wlyy.service.third.guahao.GuahaoXMService;
import com.yihu.wlyy.service.third.jw.JwSmjkService;
import com.yihu.wlyy.util.HttpUtil;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * Created by lyr on 2016/9/29.
 */
@RestController
@RequestMapping(value = "/wlyy_service")
@Api(description = "卫计委签约接口调试")
public class WlyySerivceController extends BaseController{
    @Autowired
    private GuahaoXMService guahaoXM;
    @Autowired
    private JwSmjkService jwSmjkService;
    @Autowired
    private HttpUtil HttpUtil;
    //基卫服务地址
    @Value("${sign.check_upload}")
    private String jwUrl;
    /**
     * 检查是否签约
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/third/sign/CheckSignFamily",method = RequestMethod.POST)
    @ApiOperation("检查是否签约")
    public String checkSignFamily(@RequestParam("idcard") String idcard){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/CheckSignFamily?idcard=" + idcard, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 上传签约数据
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/third/sign/UploadSignFamily",method = RequestMethod.POST)
    @ApiOperation("上传签约数据")
    public String uploadSignFamily(@RequestParam("code")String code){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/UploadSignFamily?code=" + code, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 初次采集签约接口
     *
     * @param start_time
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadAllSignFamily",method = RequestMethod.POST)
    @ApiOperation("初次采集签约接口")
    public String loadAllSignFamily(@RequestParam("start_time")String start_time){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadAllSignFamily?start_time=" + start_time, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 单条采集签约接口
     *
     * @param idcard
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadSignFamily",method = RequestMethod.POST)
    @ApiOperation("单条采集签约接口")
    public String loadSingleSignFamily(@RequestParam("idcard")String idcard){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadSignFamily?idcard=" + idcard, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 时间范围采集签约接口
     *
     * @param start_time
     * @param end_time
     * @return
     */
    @RequestMapping(value = "/third/sign/LoadSignFamilyBatch",method = RequestMethod.POST)
    @ApiOperation("时间范围采集签约接口")
    public String loadSignFamilyBatch(@RequestParam("start_time")String start_time,@RequestParam("end_time")String end_time){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/LoadSignFamilyBatch?start_time=" + start_time + "&end_time=" + end_time, "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 补上传签约接口
     *
     * @return
     */
    @RequestMapping(value = "/third/sign/ReUploadSignFamily",method = RequestMethod.POST)
    public String reuploadSignFamily(){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/ReUploadSignFamily", "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"调用失败");
        }
    }
    /**
     * 补更新签约接口
     *
     * @return
     */
    @RequestMapping(value = "/third/sign/ReUpdateSignFamily",method = RequestMethod.POST)
    public String reupdateSignFamily(){
        try{
            String checkUrl = jwUrl;
            String jsonString = HttpUtil.sendPost(checkUrl + "/third/sign/ReUpdateSignFamily", "");
            if(StringUtils.isEmpty(jsonString)){
                return write(-1,"调用失败");
            }else{
                return write(200,"调用成功","data",jsonString);
            }
        }catch (Exception e){
            return error(-1,"调用失败");
        }
    }
    /**
     * 转诊预约医生特殊号源获取
     * @param OrgCode 医院编号
     * @param DeptCode 科室编号
     * @param DocCode 医生编号
     * @return
     */
    @RequestMapping(value = "/third/smjk/RegDeptSpeDoctorSectionList",method = RequestMethod.POST)
    @ApiOperation("转诊预约获取特殊号源接口")
    public String getSpeDoctorSectionList(@RequestParam("OrgCode") String OrgCode,
                                          @RequestParam("DeptCode") String DeptCode,
                                          @RequestParam("DocCode") String DocCode){
        try{
            List<Map<String,Object>> list = guahaoXM.GetDoctorArrangeTenDay(OrgCode,DeptCode,DocCode);
            return write(200, "获取医生排班成功!", "data", list);
           /* *//*****modify by linz 暂时把号源转换成普通号源****//*
            List<Map<String,Object>> list =  guahaoXM.GetDoctorArrange(OrgCode,DeptCode,DocCode);
            for(Map map :list){
                String date = (String)map.get("date");
                map.put("date",date.replaceAll("-","/"));
            }
            return write(200, "获取医生排班成功!", "data", list);*/
        }catch (Exception e){
            e.printStackTrace();
            return error(-1,"医生排班时间获取失败");
        }
    }
    /**
     * 获取转诊预约医生列表
     * @param city
     * @param hospitalId
     * @param hosDeptId
     * @param filter
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "/third/smjk/RegDeptSpeDoctorList",method = RequestMethod.POST)
    @ApiOperation("获取转诊预约医生列表")
    @ResponseBody
    public String getRegDeptSpeDoctorList(
            @ApiParam(name = "city", value = "城市编码", defaultValue = "350200")@RequestParam(value = "city", required = true) String city,
            @ApiParam(name="hospitalId",value="医院编码",defaultValue = "350211A1001") @RequestParam(name="hospitalId",required = true) String hospitalId,
            @ApiParam(name="hosDeptId",value="科室编码",defaultValue = "1040610") @RequestParam(name="hosDeptId",required = true) String hosDeptId,
            @ApiParam(name = "filter", value = "过滤条件", defaultValue = "")
            @RequestParam(value = "filter", required = false) String filter,
            @ApiParam(name = "pageIndex", value = "第几页", defaultValue = "")
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @ApiParam(name = "pageSize", value = "每页记录数", defaultValue = "")
            @RequestParam(value = "pageSize", required = false) Integer pageSize){
        try {
            //10天排班的医生列表
            //String list  = jwSmjkService.getRegDeptSpeDoctorList(orgCode,deptCode);
            //7天排班的医生列表
            String list = jwSmjkService.GetDoctorList(hospitalId,hosDeptId);
            return list;
        } catch (Exception ex) {
            ex.printStackTrace();
            return error(-1,"获取转诊预约医生列表列表失败");
        }
    }
    /**
     * 转诊预约医生号源转换
     * @param xml
     * @return
     */
    private List<Map<String,Object>>  parseXmlForSpe(String xml) {
            List<Map<String,Object>> re = new ArrayList<>();
            Document document = null;
            try{
                 document = DocumentHelper.parseText(xml);
             }catch (Exception e){
                throw new RuntimeException("解析数据失败!");
            }
            Element root = document.getRootElement();
            List<?> child = root.elements();//取出root的子集合
            for (Object o : child) {
                List<?> dataList = ((Element) o).elements();
                for(Object dataElement:dataList) {
                    Element e = (Element) dataElement;
                    // 日期
                    String date = e.attributeValue("date");
                    // a或者p
                    String time = e.attributeValue("time");
                    // 限号
                    String max = e.attributeValue("max");
                    // 已使用的号
                    String used = e.attributeValue("used");
                    // 1正常、2满号、3已过期
                    String status = e.attributeValue("status");
                    Map<String, Object> map = new HashMap<>();
                    map.put("date", date);
                    map.put("time", time);
                    map.put("max", max);
                    map.put("used", used);
                    map.put("status", status);
                    // 排班信息
                    List<?> sections = e.elements();
                    List<Map<String, String>> arrangeList = new ArrayList<>();
                    for (Object s : sections) {
                        Element section = (Element) s;
                        // 限号
                        String s_max = section.attributeValue("max");
                        // 已使用的号
                        String s_used = section.attributeValue("used");
                        // 一次专家坐诊时间段的开始时间
                        String start_time = section.attributeValue("start_time");
                        // 结束时间
                        String end_time = section.attributeValue("end_time");
                        Map<String, String> item = new HashMap<>();
                        item.put("max", s_max);
                        item.put("used", s_used);
                        item.put("startTime", start_time);
                        item.put("endTime", end_time);
                        arrangeList.add(item);
                    }
                    map.put("sections", arrangeList);
                    re.add(map);
                }
            }
            return  re;
        }
}

+ 61 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/verified/VerifiedController.java

@ -0,0 +1,61 @@
package com.yihu.wlyy.web.common.verified;
import com.yihu.wlyy.service.third.verified.VerifiedService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping(value = "/verified", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "实名认证")
public class VerifiedController extends BaseController {
	@Autowired
	private VerifiedService verifiedService;
	/**
	 * 人脸识别
	 */
	@RequestMapping(value = "face", method = RequestMethod.POST)
	@ResponseBody
	public String face(
			@ApiParam(name="idcard",value="身份证号码",defaultValue = "350628198802200051")
			@RequestParam(value="idcard",required = true) String idcard,
			@ApiParam(name="username",value="姓名",defaultValue = "黄展鹏")
			@RequestParam(value="username",required = true) String username,
			@ApiParam(name="picData",value="图片Base64转化后的输入流",defaultValue = "")
			@RequestBody String picData) throws Exception {
		try {
			/*// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
			String imgFile = "D:/1.jpg";// 待处理的图片
			InputStream in = null;
			byte[] data = null;
			// 读取图片字节数组
			try {
				in = new FileInputStream(imgFile);
				data = new byte[in.available()];
				in.read(data);
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 对字节数组Base64编码
			BASE64Encoder encoder = new BASE64Encoder();
			picData = encoder.encode(data);*/
			verifiedService.faceVerified(idcard,username,picData);
			return write(200, "人脸识别成功!");
		} catch (Exception e) {
			return error(-1, e.getMessage());
		}
	}
}

+ 65 - 0
patient-co/patient-co-doctor-assistant/src/main/java/com/yihu/wlyy/web/common/version/VersionController.java

@ -0,0 +1,65 @@
package com.yihu.wlyy.web.common.version;
import com.yihu.wlyy.entity.Versions;
import com.yihu.wlyy.service.app.version.VersionsService;
import com.yihu.wlyy.web.BaseController;
import io.swagger.annotations.Api;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
/**
 * 版本号控制类
 * @author George
 *
 */
@Controller
@RequestMapping(value = "/version", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "版本")
public class VersionController extends BaseController {
	@Autowired
	private VersionsService versionsService;
	/**
	 * 校验APP版本号
	 * @param code 版本类型编码
	 * @param version 当前版本号
	 * @return
	 */
	@RequestMapping(value = "app",method = RequestMethod.POST)
	@ResponseBody
	public String appVersion(String code, double version) {
		try {
			Versions temp = versionsService.findVersionByCode(code);
			if (temp == null) {
				return error(-1, "无效的APP类型失败!");
			}
			if (version > 0) {
				if (temp.getVersionInt() > version) {
					// 有新的版本号
					return write(200, "发现新版本!", "url", temp.getUrl());
				} else {
					// 已是最新版本
					return write(200, "已是最新版本!");
				}
			} else {
				JSONObject json = new JSONObject();
				json.put("version_int", temp.getVersionInt());
				json.put("version_str", temp.getVersionStr());
				json.put("url", temp.getUrl());
				json.put("info", temp.getInfo());
				json.put("size", temp.getSize());
				return write(200, "读取版本号成功!", "data", json);
			}
		} catch (Exception e) {
			error(e);
			return error(-1, "版本号校验失败!");
		}
	}
}