package com.yihu.wlyy.web.patient.account;

import com.sun.org.apache.regexp.internal.RE;
import com.yihu.wlyy.entity.dict.SystemDict;
import com.yihu.wlyy.entity.doctor.profile.Doctor;
import com.yihu.wlyy.entity.doctor.team.admin.AdminTeam;
import com.yihu.wlyy.entity.doctor.team.sign.DoctorTeamMember;
import com.yihu.wlyy.entity.patient.Patient;
import com.yihu.wlyy.entity.patient.SignFamily;
import com.yihu.wlyy.entity.security.Token;
import com.yihu.wlyy.repository.security.TokenDao;
import com.yihu.wlyy.service.app.account.PatientInfoService;
import com.yihu.wlyy.service.app.sign.FamilyContractService;
import com.yihu.wlyy.service.app.team.AdminTeamService;
import com.yihu.wlyy.service.app.team.DrHealthTeamService;
import com.yihu.wlyy.service.common.account.DoctorService;
import com.yihu.wlyy.service.common.account.TokenService;
import com.yihu.wlyy.util.*;
import com.yihu.wlyy.web.WeixinBaseController;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
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 org.springside.modules.utils.Encodes;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 患者帳戶信息的Controller.
 *
 * @author George
 */
@Controller
@RequestMapping(value = "/patient", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Api(description = "患者管理")
public class PatientController extends WeixinBaseController {

    @Autowired
    private PatientInfoService patientInfoService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private FamilyContractService familyContractService;
    @Autowired
    private DrHealthTeamService doctorTeamService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    AdminTeamService teamService;
    @Autowired
    TokenDao tokenDao;

    /**
     * 患者基本信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "baseinfo")
    @ResponseBody
    public String baseinfo() {
        try {
            Patient temp = patientInfoService.findByCode(getUID());
            SignFamily sanshi = familyContractService.findByPatientByType(getUID(), 1);
            SignFamily jiating = familyContractService.findByPatientByType(getUID(), 2);
            int sign = 0;
            if (sanshi != null && jiating != null) {
                sign = 3;
            } else if (jiating != null) {
                sign = 2;
            } else if (sanshi != null) {
                sign = 1;
            }
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置患者标识
                json.put("code", temp.getCode());
                // 设置患者姓名
                json.put("name", temp.getName());
                // 设置患者头像
                json.put("photo", temp.getPhoto());
                // 设置患者年龄
                json.put("birthday", DateUtil.dateToStrShort(temp.getBirthday()));
                // 设置患者性别
                json.put("sex", temp.getSex());
                // 设置手机号码
                // json.put("mobile", CommonUtil.getMobileEncode(temp.getMobile()));
                json.put("mobile", temp.getMobile());
                // 设置身份证号
                json.put("idcard", CommonUtil.getIdcardEncode(temp.getIdcard()));//加密过的完整身份证
                // 设置社保卡号
                json.put("ssc", temp.getSsc());
                // 设置省
                json.put("province", temp.getProvince());
                // 设置市
                json.put("city", temp.getCity());
                // 设置区县
                json.put("area", temp.getTown());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置市名称
                json.put("cityName", temp.getCityName());
                // 设置区县名称
                json.put("areaName", temp.getTownName());
                // 设置街道
                json.put("street", temp.getStreet());
                // 设置街道名称
                json.put("streetName", temp.getStreetName());
                // 设置地址
                json.put("address", temp.getAddress());
                // 设置签约状态：0未签约，1三师，2家庭，3三师和家庭
                json.put("sign", sign);

                json.put("idcardAll", temp.getIdcard());//完整身份证
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 患者微信圖片信息保存
     *
     * @param mediaIds 頭像
     * @return
     */
    @RequestMapping(value = "saveWXPhote")
    @ResponseBody
    public String saveWXPhote(String mediaIds) {
        try {
            //下載微信的圖片保存到自己的服務器
            String photo = saveImageToDiskNoImageCompress(mediaIds);
            return write(200, "获取成功！", "data", photo);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败！");
        }
    }

    /**
     * 患者基本信息保存
     *
     * @param photo    頭像
     * @param name     姓名
     * @param sex      性別
     * @param birthday 生日
     * @param ssc      社保卡號
     * @param province 省標識
     * @param city     市標識
     * @param town     區縣標識
     * @param address  詳細地址
     * @param street   街道
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(@RequestParam(required = false) String photo,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) Integer sex,
                       @RequestParam(required = false) String birthday,
                       @RequestParam(required = false) String ssc,
                       @RequestParam(required = false) String province,
                       @RequestParam(required = false) String city,
                       @RequestParam(required = false) String town,
                       @RequestParam(required = false) String address,
                       @RequestParam(required = false) String street) {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
            if (StringUtils.isEmpty(photo)) {
                photo = fetchWxImages();
            }
            if (StringUtils.isNotEmpty(photo)) {
                photo = CommonUtil.copyTempImage(photo);
            }
            if (StringUtils.isNotEmpty(photo)) {
                patient.setPhoto(photo);
            }
            if (StringUtils.isNotEmpty(name))
                patient.setName(name);
            if (sex != null)
                patient.setSex(sex);
            if (StringUtils.isNotEmpty(birthday))
                patient.setBirthday(DateUtil.strToDate(birthday, DateUtil.YYYY_MM_DD));
//			if (StringUtils.isNotEmpty(ssc) && StringUtils.isEmpty(patient.getSsc()))
//				patient.setSsc(ssc);
            // if (StringUtils.isNotEmpty(province))
            patient.setProvince(province);
            //if (StringUtils.isNotEmpty(city))
            patient.setCity(city);
            //if (StringUtils.isNotEmpty(town))
            patient.setTown(town);
            //if (StringUtils.isNotEmpty(address))
            patient.setAddress(address);
            //if (StringUtils.isNotEmpty(street))
            patient.setStreet(street);
            if (patientInfoService.updatePatient(patient) != null) {
                // 修改成功
                return success("保存成功！");
            } else {
                // 注册失败
                return error(-1, "保存失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "保存失败！");
        }
    }

    /**
     * 患者信息查询接口
     *
     * @return
     */
    @RequestMapping(value = "info")
    @ResponseBody
    public String info() {
        try {
            Patient temp = patientInfoService.findByCode(getUID());
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置患者标识
                json.put("code", temp.getCode());
                // 设置患者姓名
                json.put("name", temp.getName());
                // 设置患者头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置患者出生年月
                json.put("birthday", DateUtil.dateToStr(temp.getBirthday(), DateUtil.YYYY_MM_DD));
                // 设置患者年龄
                json.put("age", DateUtil.getAgeByBirthday(temp.getBirthday()));
                // 设置患者性别
                json.put("sex", temp.getSex());
                // 设置患者病情：0绿标，1黄标，2红标
                json.put("diseaseLevel", temp.getDiseaseCondition());
                // 查询签约信息
                SignFamily signContract = familyContractService.findByPatient(getUID());
                if (signContract == null) {
                    // 设置签约日期
                    json.put("qyrq", "");
                    // 设置健康管理师
                    json.put("health", "");
                    // 设置专科医生
                    json.put("specialist", "");
                    // 设置全科医生
                    json.put("gp", "");
                } else {
                    // 设置签约日期
                    json.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
                    // // 查询三师医生信息
                    // List<DoctorTeamInfo> doctorTeamInfos = doctorTeamService.findDoctorByTeam(signContract.getTeam());
                    // if (doctorTeamInfos != null) {
                    // for (DoctorTeamInfo doctorTeamInfo : doctorTeamInfos) {
                    // if (doctorTeamInfo.getType() == 1) {
                    // json.put("specialist", doctorTeamInfo.getName());
                    // } else if (doctorTeamInfo.getType() == 2) {
                    // json.put("gp", doctorTeamInfo.getName());
                    // } else
                    // json.put("health", doctorTeamInfo.getName());
                    // }
                    // } else {
                    json.put("health", "");
                    json.put("specialist", "");
                    json.put("gp", "");
                    // }
                }
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 修改密码
     *
     * @param oldpwd 旧密码
     * @param newpwd 新密码
     * @return
     */
    @RequestMapping(value = "updatepwd")
    @ResponseBody
    public String updatepwd(String oldpwd, String newpwd) {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
            if (patient == null) {
                return error(-1, "修改失败！");
            } else {
                String encodePWD = EncodesUtil.entryptPassword(Encodes.decodeHex(patient.getSalt()), oldpwd);
                if (StringUtils.equals(patient.getPassword(), encodePWD)) {
                    patient.setPassword(newpwd);
                    patientInfoService.updatePatientPwd(patient);
                    return success("修改成功！");
                } else {
                    return error(-1, "修改失败：旧密码错误！");
                }
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "修改失败！");
        }
    }

    /**
     * 退出登录
     *
     * @return
     */
    @RequestMapping(value = "loginout")
    @ResponseBody
    public String loginout() {
        try {
            tokenService.delToken(1, getUID());
            return success("已成功退出！");
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }

    /**
     * 微信用户退出登录
     *
     * @return
     */
    @RequestMapping(value = "wxloginout")
    @ResponseBody
    public String wxloginout() {
        try {
            Patient patient = patientInfoService.findByCode(getUID());
            if (patient == null) {
                return error(-1, "退出失败，用户不存在");
            } else {
                //patient.setOpenid("");
                //patientInfoService.updateUser(patient);
                Token token = SystemData.wxPatientTokens.get(getUID());
                if (token == null) {
                    token = tokenDao.findByPatient(getUID(), 3);
                }

                if(token == null){
                    return error(-1,"用户未登录");
                }

                token.setDel("0");
                tokenDao.save(token);
                SystemData.wxPatientTokens.remove(getUID());
                return success("已成功退出！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "操作失败！");
        }
    }

    /**
     * 登录患者获取三师信息
     *
     * @return
     */
    @RequestMapping(value = "teachers")
    @ResponseBody
    public String teachers(@RequestParam(required = false, defaultValue = "") String signDoctor) {
        try {
            String code = getUID();//getUID();
            // 查询签约信息
            SignFamily signContract = familyContractService.findBySanshiPatient(code);
            if (signContract == null) {
                return error(1, "无三师签约信息");
            }
            JSONObject doctorJson = new JSONObject();
            // 设置签约日期
            doctorJson.put("qyrq", DateUtil.dateToStr(signContract.getBegin(), DateUtil.YYYY_MM_DD));
            // 查询三师医生信息
            List<Doctor> doctors = doctorTeamService.findSanshiTeamDoctors(code);
            JSONArray jsonArray = new JSONArray();
            String qkDoctor = "";
            if (doctors != null) {
                for (Doctor doctor : doctors) {
                    if (doctor == null) {
                        continue;
                    }
                    JSONObject json = new JSONObject();
                    json.put("code", doctor.getCode());
                    json.put("name", doctor.getName());
                    json.put("photo", CommonUtil.getPhoneUrl(doctor.getPhoto()));
                    json.put("hospitalName", doctor.getHospitalName());
                    json.put("deptName", doctor.getDeptName());
                    json.put("jobName", doctor.getJobName());
                    json.put("expertise", doctor.getExpertise());
                    int type = doctor.getLevel();
                    if (type == 1) {
                        json.put("typename", "专科医生");
                    } else if (type == 2) {
                        json.put("typename", "全科医生");
                        qkDoctor = doctor.getCode();
                    } else if (type == 3) {
                        json.put("typename", "健康管理师");
                    } else {
                        json.put("typename", "");
                    }
                    json.put("type", type);
                    jsonArray.put(json);
                }
            }

            if (StringUtils.isNotEmpty(signDoctor)) {
                List<AdminTeam> teams = teamService.findDoctorsTeams(signDoctor, qkDoctor);
                doctorJson.put("team", teams != null ? new JSONArray(teams) : new ArrayList<AdminTeam>());
            }

            doctorJson.put("list", jsonArray);
            return write(200, "查询成功！", "data", doctorJson);
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "查询失败！");
        }
    }

    /**
     * 医生基本信息查询接口
     *
     * @param doctor 医生标识
     * @return
     */
    @RequestMapping(value = "docInfo")
    @ResponseBody
    public String doctorInfo(String doctor) {
        try {
            Doctor temp = doctorService.findDoctorByCode(doctor);
            if (temp != null) {
                JSONObject json = new JSONObject();
                // 设置医生标识
                json.put("code", temp.getCode());
                // 设置医生姓名
                json.put("name", temp.getName());
                // 设置医生头像
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));
                // 设置医生性别
                json.put("sex", temp.getSex());
                // 设置省名称
                json.put("provinceName", temp.getProvinceName());
                // 设置城市名称
                json.put("cityName", temp.getCityName());
                // 设置医院名称
                json.put("hospitalName", temp.getHospitalName());
                // 设置部门名称
                json.put("deptName", temp.getDeptName());
                // 设置职称
                json.put("jobName", temp.getJobName());
                // 设置医生专长
                json.put("expertise", temp.getExpertise());
                // 设置医生简介
                json.put("introduce", temp.getIntroduce());
                // 二维码地址
                json.put("qrcode", temp.getQrcode());
                return write(200, "医生信息查询成功！", "data", json);
            } else {
                return error(-1, "医生信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "医生信息查询失败！");
        }
    }

    /**
     * 查询患者签约状态
     *
     * @return
     */
    @RequestMapping(value = "sign_status")
    @ResponseBody
    public String signStaus() {
        try {
            Map<String, String> teamDoctors = new HashMap<>();
            Map<String, String> familyDoctors = new HashMap<>();
            String id = getUID();
            //查询家庭签约
            SignFamily jt = familyContractService.findByPatientYes(id);
            if (jt != null) {
                List<Doctor> doctors = doctorTeamService.findJiatingTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        familyDoctors.put(doctor.getCode(), doctor.getName());
                    }
                }
            }
            // 查询三师医生
            SignFamily ss = familyContractService.findBySanshiPatientYes(id);
            if (ss != null) {
                List<Doctor> doctors = doctorTeamService.findSanshiTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        teamDoctors.put(doctor.getCode(), doctor.getName());
                    }
                }
            }
            // 未签约
            int sign = 0;
            if (ss != null && jt != null) {
                // 三师+家庭
                sign = 3;
            } else if (jt != null) {
                // 家庭签约
                sign = 2;
            } else if (ss != null) {
                // 三师签约
                sign = 1;
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "获取签约状态成功！");
            json.put("data", sign);
            json.put("teamDoctors", teamDoctors.size() > 0 ? new JSONArray(teamDoctors.values()) : new JSONArray());
            json.put("familyDoctors", familyDoctors.size() > 0 ? new JSONArray(familyDoctors.values()) : new JSONArray());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "签约状态查询失败！");
        }
    }

    /**
     * 查询患者签约状态
     *
     * @return
     */
    @RequestMapping(value = "sign_doctors")
    @ResponseBody
    public String signDoctors() {
        try {
            Map<String, JSONObject> teamDoctors = new HashMap<>();
            Map<String, JSONObject> familyDoctors = new HashMap<>();
            String id = getUID();
            //查询家庭签约
            SignFamily jt = familyContractService.findByPatientYes(id);
            Map<String,Object> docMap = new HashMap<>();
            if (jt != null) {
                List<Doctor> doctors = doctorTeamService.findJiatingTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        JSONObject doctorJson = new JSONObject();
                        doctorJson.put("code", doctor.getCode());
                        doctorJson.put("name", doctor.getName());
                        doctorJson.put("level", doctor.getLevel());
                        List<DoctorTeamMember> oc = new ArrayList<>();
                        if(docMap.get(doctor.getCode())!=null){//不为空证明全科，建管同一个
                            oc = (List<DoctorTeamMember>)docMap.get(doctor.getCode());
                            doctorJson.put("teamlevel",2);
                        }else{//为空证明建管和全科不一致，或者第一次进入
                            oc = doctorTeamService.findTeamType(id,doctor.getCode());
                            if(oc!=null&&oc.size()==1){//找出只有一条直接返回团队所属职位
                                doctorJson.put("teamlevel",oc.get(0).getType());
                            }
                            if(oc!=null&&oc.size()==2){//两条数据证明专科全科一致
                                docMap.put(doctor.getCode(),oc);
                                doctorJson.put("teamlevel",3);
                            }
                        }
                        familyDoctors.put(doctor.getCode(), doctorJson);
                    }
                }
            }
            // 查询三师医生
            SignFamily ss = familyContractService.findBySanshiPatientYes(id);
            if (ss != null) {
                List<Doctor> doctors = doctorTeamService.findSanshiTeamDoctors(id);
                if (doctors != null) {
                    for (Doctor doctor : doctors) {
                        if (doctor == null) {
                            continue;
                        }
                        JSONObject doctorJson = new JSONObject();
                        doctorJson.put("code", doctor.getCode());
                        doctorJson.put("name", doctor.getName());
                        doctorJson.put("level", doctor.getLevel());
                        teamDoctors.put(doctor.getCode(), doctorJson);
                    }
                }
            }
            // 未签约
            int sign = 0;
            if (ss != null && jt != null) {
                // 三师+家庭
                sign = 3;
            } else if (jt != null) {
                // 家庭签约
                sign = 2;
            } else if (ss != null) {
                // 三师签约
                sign = 1;
            }
            JSONObject json = new JSONObject();
            json.put("status", 200);
            json.put("msg", "获取签约状态成功！");
            json.put("data", sign);
            json.put("teamDoctors", teamDoctors.size() > 0 ? new JSONArray(teamDoctors.values()) : new JSONArray());
            json.put("familyDoctors", familyDoctors.size() > 0 ? new JSONArray(familyDoctors.values()) : new JSONArray());
            return json.toString();
        } catch (Exception e) {
            error(e);
            return error(-1, "签约状态查询失败！");
        }
    }

    /**
     * 查询患者是否有签约信息
     *
     * @return
     */
    @RequestMapping(value = "is_sign")
    @ResponseBody
    public String isSign() {
        try {
            JSONObject jsonObject = new JSONObject();
            //判断是否有三师签约
            SignFamily ss = familyContractService.findBySanshiPatient(getUID());  // -1 未签约  0 待签约 1 已签约 2待解约
            if (ss != null) {
                return write(200, "获取签约状态成功！", "data", ss.getStatus());
            }
            //判断是否有家庭签约
            SignFamily sf = familyContractService.findByFamilySignPatient(getUID());
            if (sf != null) {
                return write(200, "获取签约状态成功！", "data", sf.getStatus());
            }
            return write(200, "获取签约状态成功！", "data", -1);
        } catch (Exception e) {
            error(e);
            return error(-1, "签约状态查询失败！");
        }
    }

    /**
     * 查询患者身份证号
     *
     * @return
     */
    @RequestMapping(value = "idc")
    @ResponseBody
    public String idcard() {
        try {
            Patient temp = patientInfoService.findByCode(getUID());
            return write(200, "患者信息查询成功！", "data", temp.getIdcard());
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 根據邀請紀錄查詢邀請人信息
     *
     * @return
     */
    @RequestMapping(value = "getPatientByInviLogCode")
    @ResponseBody
    public String getPatientByInviLogCode(String invilogCode) {
        try {
            Patient temp = patientInfoService.invilogCode(invilogCode);
            if (temp != null) {
                JSONObject json = new JSONObject();
                json.put("code", temp.getCode());    // 设置患者标识
                json.put("name", temp.getName());// 设置患者姓名
                json.put("photo", CommonUtil.getPhoneUrl(temp.getPhoto()));// 设置患者头像
                json.put("birthday", DateUtil.dateToStrShort(temp.getBirthday()));// 设置患者年龄
                json.put("sex", temp.getSex());// 设置患者性别
                // json.put("mobile", CommonUtil.getMobileEncode(temp.getMobile()));
                json.put("mobile", temp.getMobile());// 设置手机号码
                json.put("idcard", CommonUtil.getIdcardEncode(temp.getIdcard()));// 设置身份证号
                json.put("ssc", temp.getSsc());// 设置社保卡号
                json.put("province", temp.getProvince());// 设置省
                json.put("city", temp.getCity());// 设置市
                json.put("area", temp.getTown());    // 设置区县
                json.put("provinceName", temp.getProvinceName());// 设置省名称
                json.put("cityName", temp.getCityName());// 设置市名称
                json.put("areaName", temp.getTownName());// 设置区县名称
                json.put("street", temp.getStreet());        // 设置街道
                json.put("streetName", temp.getStreetName());// 设置街道名称
                json.put("address", temp.getAddress());// 设置地址
                return write(200, "患者信息查询成功！", "data", json);
            } else {
                return error(-1, "患者信息查询失败！");
            }
        } catch (Exception e) {
            error(e);
            return invalidUserException(e, -1, "患者信息查询失败！");
        }
    }

    /**
     * 居民手机号变更
     *
     * @param mobile  新手机号
     * @param captcha 验证码
     * @param type    1:变更手机号  2:绑定手机号
     * @return
     */
    @RequestMapping(value = "/mobile_update", method = RequestMethod.POST)
    @ResponseBody
    public String changePatientMobile(String mobile, String captcha, int type) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "请填写新手机号码");
            }
            if (StringUtils.isEmpty(captcha)) {
                return error(-1, "请输入验证码");
            }
            if (type != 1 && type != 2) {
                return error(-1, "操作类型参数错误");
            }

            int result = patientInfoService.changeMobile(getUID(), mobile, captcha, type);

            if (result == -1) {
                return error(-1, "居民信息查找失败");
            } else if (result == -2) {
                return error(-1, "手机号已注册");
            } else if (result == -3) {
                return error(-1, "验证码错误");
            } else if (result == 1) {
                return write(200, "手机号更新成功");
            } else {
                return write(-1, "手机号更新失败");
            }
        } catch (Exception e) {
            return error(-1, "手机号更新失败");
        }
    }

    /**
     * 手机号是否注册
     *
     * @param mobile 手机号
     * @return
     */
    @RequestMapping("/is_mobile_register")
    @ResponseBody
    public String isMobileRegister(String mobile) {
        try {
            if (StringUtils.isEmpty(mobile)) {
                return error(-1, "手机号码不能为空");
            }

            int result = patientInfoService.isMobileRegister(mobile);

            return write(200, "查询成功", "data", result);
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "查询失败");
        }
    }

    /**
     * 修改密码
     *
     * @param newPassword1 新密码1
     * @param newPassword2 新密码2
     * @param oldPassword  旧密码
     * @return
     */
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    @ResponseBody
    public String updatePassword(String newPassword1,
                                 String newPassword2,
                                 String oldPassword) {
        try {
            newPassword1 = RSAUtils.getInstance(doctorService).decryptString(newPassword1);
            newPassword2 = RSAUtils.getInstance(doctorService).decryptString(newPassword2);
            oldPassword = RSAUtils.getInstance(doctorService).decryptString(oldPassword);
            newPassword1 = StringUtils.reverse(newPassword1);
            newPassword2 = StringUtils.reverse(newPassword2);
            oldPassword = StringUtils.reverse(oldPassword);
            patientInfoService.updatePassword(newPassword1, newPassword2, oldPassword, getUID());
            return write(200, "更新成功");
        } catch (Exception e) {
            return error(-1, e.getMessage());
        }
    }


    /**
     * 切换家庭成员账号
     *
     * @param family 患者code
     * @return
     */
    @RequestMapping(value = "/switch_account")
    @ResponseBody
    public String switchFamilyAccount(String family, String openid) {
        try {
            if (StringUtils.isEmpty(family)) {
                return error(-1, "家庭成员不能为空");
            }
            if (StringUtils.isEmpty(openid)) {
                return error(-1, "openid不能为空");
            }

            String lastUid = getLastUid();

            if (StringUtils.isEmpty(lastUid)) {
                lastUid = getUID();
            }

            JSONObject result = patientInfoService.switchFamilyAccount(lastUid, family, openid);

            int status = result.getInt("status");

            if (status == -1) {
                return error(-1, "成员信息查询失败");
            } else if (status == -2) {
                return error(-2, "家庭成员不存在该人");
            } else {
                JSONObject json = result.getJSONObject("data");

                if (StringUtils.isNotEmpty(lastUid)) {
                    json.put("lastUid", lastUid);
                }

                return write(200, "切换账号成功", "data", json);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return error(-1, "切换账号失败");
        }
    }
}
