package com.yihu.jw.wlyy.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.dict.dao.DictDoctorDutyDao;
import com.yihu.jw.dict.dao.DictHospitalDeptDao;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.doctor.dao.BaseDoctorHospitalDao;
import com.yihu.jw.doctor.dao.BaseDoctorRoleDao;
import com.yihu.jw.entity.base.dict.DictDoctorDutyDO;
import com.yihu.jw.entity.base.dict.DictHospitalDeptDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorHospitalDO;
import com.yihu.jw.entity.base.doctor.BaseDoctorRoleDO;
import com.yihu.jw.entity.base.org.BaseOrgDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.hospital.mapping.DoctorMappingDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.hospital.httplog.dao.BaseOperateLogDao;
import com.yihu.jw.hospital.httplog.service.BaseOperateLogService;
import com.yihu.jw.hospital.mapping.dao.DoctorMappingDao;
import com.yihu.jw.hospital.prescription.dao.OutpatientDao;
import com.yihu.jw.hospital.prescription.service.PrescriptionService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.org.dao.BaseOrgDao;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientMedicareCardDao;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.util.wechat.wxhttp.HttpUtil;
import com.yihu.jw.wlyy.wlyyhttp.WlyyHttpService;
import com.yihu.utils.security.MD5;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by Trick on 2019/8/21.
 */
@Service
@Transactional
public class WlyyBusinessService {

    private static final Logger logger = LoggerFactory.getLogger(WlyyBusinessService.class);

    @Autowired
    private WlyyHttpService wlyyHttpService;

    @Autowired
    private BaseDoctorDao baseDoctorDao;

    @Autowired
    private OutpatientDao outpatientDao;

    @Autowired
    private BasePatientDao basePatientDao;

    @Autowired
    private BaseOrgDao baseOrgDao;

    @Autowired
    private DictHospitalDeptDao dictHospitalDeptDao;

    @Autowired
    private BaseDoctorHospitalDao baseDoctorHospitalDao;

    @Autowired
    private BaseDoctorRoleDao baseDoctorRoleDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DoctorMappingDao doctorMappingDao;

    @Autowired
    private PrescriptionService prescriptionService;

    @Autowired
    private BasePatientMedicareCardDao patientMedicareCardDao;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;
    @Autowired
    private BaseOperateLogService baseOperateLogService;


    /**
     * 推送系统门诊wlyy系统消息
     * @param doctor
     * @param outPatientId
     * @return
     */
    public Boolean sendWlyyOutpatientMes(String doctor,String outPatientId){

        BaseDoctorDO doctorDO = baseDoctorDao.findOne(doctor);

        if(doctorDO!=null&& StringUtils.isNotBlank(doctorDO.getIdcard())){
            WlyyOutpatientDO outpatientDO =outpatientDao.findOne(outPatientId);
            BasePatientDO basePatientDO = basePatientDao.findOne(outpatientDO.getPatient());

            JSONObject param = new JSONObject();
            param.put("idCard",doctorDO.getIdcard());
            param.put("sender","hlwyy");
            param.put("senderName","互联网医院");
            param.put("relationCode",outPatientId);
            String sex = "";
            try {
                String sx = IdCardUtil.getSexForIdcard_new(basePatientDO.getIdcard());
                if("1".equals(sx)){
                    sex = "男";
                }else if("2".equals(sx)){
                    sex = "女";
                }
            }catch (Exception e){
                logger.error("推送wlyy系统消息 身份证转换性别失败！："+e.toString());
            }
            String age = IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard())==-1?"未知":IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard())+"";

            String content = "您已向"+outpatientDO.getHospitalName()+outpatientDO.getDeptName()+
                    "医师"+doctorDO.getName()+"发起了协同门诊请求。协同门诊患者："+outpatientDO.getPatientName()+
                    "（"+sex+" "+age+"岁），协同门诊时间："+ DateUtil.dateToStr(outpatientDO.getRegisterDate(),"yyyy-MM-dd HH:mm");

            param.put("content",content);
            param.put("title","协同门诊消息");
            param.put("type",500);

            JSONObject rs = wlyyHttpService.sendWlyyMes("wlyySendMes",param,null);
            if(rs!=null){
                return true;
            }
        }
        return false;
    }


    public Boolean readWlyyOutpatientMes(String outPatientId){

        Map<String,Object> res = new HashedMap();

        WlyyOutpatientDO outpatientDO =outpatientDao.findOne(outPatientId);

        if(outpatientDO!=null){
            BaseDoctorDO doctorDO = baseDoctorDao.findOne(outpatientDO.getDoctor());

            JSONObject param = new JSONObject();
            param.put("idCard",doctorDO.getIdcard());
            param.put("type",500);
            param.put("relationCode",outPatientId);

            JSONObject rs = wlyyHttpService.sendWlyyMes("wlyyReadMes",param,null);
            if(rs!=null){
                return true;
            }
        }
        return false;
    }

    /**
     * 验证居民是否签约
     *
     * @param idCard
     * @return
     */
    public Boolean checkSignFamily(String idCard){

        JSONObject param = new JSONObject();
        param.put("idCard",idCard);
        JSONObject rs = wlyyHttpService.sendWlyyMes("wlyyCheckSignFamily",param,null);
        if(rs!=null){
            return true;
        }
        return false;
    }
    
    /**
     * 根据身份证获取i健康居民信息
     * @param idcard
     * @return
     */
    public String getPatientCodeByWlyyIdcard(String idcard) throws Exception {
        BasePatientDO patientDO =  basePatientDao.findByIdcardAndDel(idcard,"1");
        String result = "";
        if(patientDO == null){
    
            Map<String,String> params = new HashMap<>();
            params.put("idcard",idcard);
    
            JSONObject rs = wlyyHttpService.sendWlyyMes("wlyyGetPatient",null,params);
            if(rs!=null){
                Integer status = rs.getInteger("status");
                if(200 == status){
                    JSONObject data = rs.getJSONObject("data");
                    BasePatientDO patient = new BasePatientDO();
                    String salt = UUID.randomUUID().toString().substring(0,5);
                    String mobile = data.getString("mobile");
                    String pw = null;
    
                    if(StringUtils.isNotBlank(mobile)){
                        pw = mobile.substring(mobile.length()-6);
                    }else{
                        pw = idcard.substring(idcard.length()-6);
                    }
    
                    patient.setIdcard(idcard);
                    patient.setName(data.getString("name"));
                    patient.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                    patient.setSalt(salt);
                    patient.setMobile(mobile);
                    patient.setDel("1");
                    patient.setEnabled(1);
                    patient.setLocked(0);
                    patient.setCreateTime(new Date());
                    patient.setUpdateTime(new Date());
                    patient.setBirthday(DateUtil.strToDate(data.getString("birthday"),"yyyyMMdd"));
                    patient = basePatientDao.save(patient);
                    result = patient.getId();
                    if(data.get("ssc")!=null){
                        PatientMedicareCardDO patientMedicareCardDO = new PatientMedicareCardDO();
                        patientMedicareCardDO.setDel("1");
                        patientMedicareCardDO.setPatientCode(patient.getId());
                        patientMedicareCardDO.setCode(data.getString("ssc"));
                        patientMedicareCardDO.setType("A_01");
                        patientMedicareCardDao.save(patientMedicareCardDO);
                    }
                }else{
                    throw new Exception("请求i健康接口，获取居民信息失败");
                }
            }

        }else{
            result =  patientDO.getId();
        }
        return result;
    }
    
    
    /**
     * (健康咨询)转发消息
     * @param senderIdcard
     * @param reciverIdcard
     * @param messageids
     * @param title
     * @param sessionType
     * @return
     * @throws Exception
     */
    public Boolean wlyyMessageForward(String senderIdcard, String reciverIdcard, String messageids, String title, String sessionType) throws Exception {
    
        Map<String,String> params = new HashMap<>();
        params.put("senderIdcard",senderIdcard);
        params.put("reciverIdcard",reciverIdcard);
        params.put("messageids",messageids);
        params.put("title",title);
        params.put("sessionType",sessionType);

        JSONObject rs = wlyyHttpService.sendWlyyMes("wlyyMessageForward",null,params);
        if(rs!=null){
            Integer status = rs.getInteger("status");
            if(200 == status){
                return true;
            }else{
                return false;
            }
        }
        return false;
    }
    
    /**
     * 根据居民CODE换取居民请求秘钥
     * @param patientId
     * @return
     * @throws Exception
     */
    public String wlyyGetPatientAccetokenByIdcard(String patientId,String wxId,String doctorId) throws Exception {
        
        String idcard = "";
        String result = "";
        BasePatientDO basePatientDO = basePatientDao.findById(patientId);
        if(basePatientDO != null){
            idcard = basePatientDO.getIdcard();
    
            Map<String,String> params = new HashMap<>();
            params.put("idcard",idcard);

            String patientCardNo = null;
            if (wxId.equalsIgnoreCase("xm_zsyy_wx")){
                net.sf.json.JSONArray array =prescriptionService.findPatientCard(patientId);
                for (int i=0;i<array.size();i++){
                    net.sf.json.JSONObject object = array.getJSONObject(i);
                    String cardType = object.getString("CARD_TYPE");
                    String cardNo = object.getString("CARD_NO");
                    String cardTypeName = object.getString("CARD_TYPE_NAME");
                    PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByCodeAndPatientCode(cardNo,patientId);
                    if (patientMedicareCardDO==null){
                        patientMedicareCardDO = new PatientMedicareCardDO();
                        patientMedicareCardDO.setCode(cardNo);
                        patientMedicareCardDO.setParentType("A");
                        if (cardType.equalsIgnoreCase("2")){
                            patientMedicareCardDO.setType("A_01");
                            patientCardNo = cardNo;
                        }else {
                            patientMedicareCardDO.setType("A_03");
                        }
                        patientMedicareCardDO.setPatientCode(patientId);
                        patientMedicareCardDO.setOrgCode("350211A1002");
                        patientMedicareCardDO.setCityCode("350200");
                        patientMedicareCardDO.setDel("1");
                        patientMedicareCardDO.setRemark(cardTypeName);
                        patientMedicareCardDao.save(patientMedicareCardDO);
                    }else {
                        if (patientMedicareCardDO.getType().equalsIgnoreCase("A_01")){
                            patientCardNo = patientMedicareCardDO.getCode();
                        }
                    }
                }
            }else if (wxId.equalsIgnoreCase("xm_xzzx_wx")){
                JSONArray array = xzzxEntranceService.selectPateintCard(patientId);
                for (int i=0;i<array.size();i++){
                    JSONObject jsonObject = array.getJSONObject(i);
                    String cardType = jsonObject.getString("CARD_TYPE");
                    String cardNo = jsonObject.getString("CARD_NO");
                    String cardTypeName = jsonObject.getString("CARD_TYPE_HIS");
                    PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByCodeAndPatientCode(cardNo,patientId);
                    if (patientMedicareCardDO==null){
                        patientMedicareCardDO = new PatientMedicareCardDO();
                        patientMedicareCardDO.setCode(cardNo);
                        patientMedicareCardDO.setParentType("A");
                        if (cardType.equalsIgnoreCase("01")){
                            patientMedicareCardDO.setType("A_01");
                            patientCardNo = cardNo;
                        }else {
                            patientMedicareCardDO.setType("A_03");
                        }
                        patientMedicareCardDO.setPatientCode(patientId);
                        patientMedicareCardDO.setOrgCode("350211A1002");
                        patientMedicareCardDO.setCityCode("350200");
                        patientMedicareCardDO.setDel("1");
                        patientMedicareCardDO.setRemark(cardTypeName);
                        patientMedicareCardDao.save(patientMedicareCardDO);
                    }else {
                        if (patientMedicareCardDO.getType().equalsIgnoreCase("A_01")){
                            patientCardNo = patientMedicareCardDO.getCode();
                        }
                    }
                }
            }else {
                PatientMedicareCardDO patientMedicareCardDO = patientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",patientId,"1");
                if (patientMedicareCardDO!=null){
                    patientCardNo = patientMedicareCardDO.getCode();
                }else {
                    Map<String,String> params2 = new HashMap<>();
                    params2.put("idcard",idcard);
                    JSONObject rs = wlyyHttpService.sendWlyyMes("wlyyGetPatient",null,params2);
                    if(rs!=null) {
                        Integer status = rs.getInteger("status");
                        if (200 == status) {
                            JSONObject data = rs.getJSONObject("data");
                            if (data.get("ssc")!=null){
                                patientCardNo = data.getString("ssc");
                                patientMedicareCardDO = new PatientMedicareCardDO();
                                patientMedicareCardDO.setPatientCode(patientId);
                                patientMedicareCardDO.setCode(patientCardNo);
                                patientMedicareCardDO.setType("A_01");
                                patientMedicareCardDO.setDel("1");
                                patientMedicareCardDao.save(patientMedicareCardDO);
                            }
                        }
                    }
                }
            }
            if (!StringUtils.isNoneBlank(patientCardNo)){
                return "社保卡不能为空！";
            }
            //查询i健康信息，没有就注册；
            Map<String,String> patientSccParams = new HashMap<>();
            patientSccParams.put("ssc",patientCardNo);
            patientSccParams.put("name",basePatientDO.getName());
            patientSccParams.put("idCard",basePatientDO.getIdcard());
            patientSccParams.put("sex",basePatientDO.getSex().toString());
            patientSccParams.put("phone",basePatientDO.getMobile());
            patientSccParams.put("birthday",DateUtil.dateToStrShort(basePatientDO.getBirthday()));
            //JSONObject object = wlyyHttpService.sendWlyyMes("wlyyFindAccountBySsc", null, patientSccParams);

            JSONObject rs = wlyyHttpService.sendWlyyMes("wlyyGetPatientAccetokenByIdcard",null,params);
            if(rs!=null){
                Integer status = rs.getInteger("status");
                if(200 == status){
                    JSONObject data = rs.getJSONObject("data");
                    result = data.getString("patientCode");
                }else{
                    logger.info(rs.toJSONString());
                    throw new Exception("请求i健康接口失败");
                }
            }
            try {
                baseOperateLogService.saveOperateLog(doctorId,patientId,"JKDA","健康档案","","");
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            throw new Exception("该居民不存在");
        }
        return result;
    }

    /**
     * 查询I健康接口获取居民信息
     */
    public Map<String,Object> findWlyyPatient(String idcard)throws Exception{

        JSONObject param = new JSONObject();
        param.put("idcard",idcard);
        JSONObject re = wlyyHttpService.sendWlyyMes("wlyyGetSignFamily",param,null);
        if(re!=null){
            JSONObject p = re.getJSONObject("data");

            BasePatientDO patientDO =  basePatientDao.findByIdcardAndDel(idcard,"1");
            if(patientDO == null){
                BasePatientDO patient = new BasePatientDO();

                String salt = UUID.randomUUID().toString().substring(0,5);
                String mobile = p.getString("mobile");
                String pw = mobile.substring(mobile.length()-6);

                patient.setIdcard(idcard);
                patient.setName(p.getString("name"));
                patient.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                patient.setSalt(salt);
                patient.setMobile(mobile);
                patient.setDel("1");
                patient.setEnabled(1);
                patient.setLocked(0);
                patient.setCreateTime(new Date());
                patient.setUpdateTime(new Date());
                patient.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));

                BasePatientDO temp = basePatientDao.save(patient);

                return getPatientInfoMap(temp);
            }
            return getPatientInfoMap(patientDO);
        }
        return null;
    }

    public Map<String,Object> getPatientInfoMap(BasePatientDO basePatientDO){
        Map<String,Object> rs = new HashedMap();
        rs.put("id",basePatientDO.getId());
        rs.put("name",basePatientDO.getName());
        rs.put("sex",basePatientDO.getSex());
        rs.put("provinceCode",basePatientDO.getProvinceCode());
        rs.put("provinceName",basePatientDO.getProvinceName());
        rs.put("cityCode",basePatientDO.getCityCode());
        rs.put("cityName",basePatientDO.getCityName());
        rs.put("townCode",basePatientDO.getTownCode());
        rs.put("townName",basePatientDO.getTownName());
        rs.put("idcard",basePatientDO.getIdcard());
        rs.put("age",IdCardUtil.getAgeForIdcard(basePatientDO.getIdcard()));
        rs.put("mobile",basePatientDO.getMobile());
        return rs;
    }

    public JSONArray findPatientListBySscOrIdCard(String idcard,String ssc){

        Map<String,String> mapParams = new HashedMap();
        if(StringUtils.isNotBlank(idcard)){
            mapParams.put("idcard",idcard);
        }
        if(StringUtils.isNotBlank(ssc)){
            mapParams.put("ssc",ssc);
        }
        JSONObject re = wlyyHttpService.sendWlyyMes("findPatientListBySscOrIdCard",null,mapParams);
        JSONArray list =null;
        if(re!=null){
            list = re.getJSONArray("data");
            return list;
        }
        return null;
    }

    public String makeBase64Qrcode(String doctor){

        BaseDoctorDO doctorDO = baseDoctorDao.findById(doctor);

        Map<String,String> mapParams = new HashedMap();
        mapParams.put("doctor",doctorDO.getId()+"_"+doctorDO.getName());

        JSONObject re = wlyyHttpService.sendWlyyMes("makeBase64Qrcode",null,mapParams);
        if(re!=null){
            return re.getString("data");
        }
        return null;
    }

    public String findWlyyHospital(){
        JSONObject re = wlyyHttpService.sendWlyyMes("findWlyyHospital",null,null);
        if(re!=null){
            JSONArray hospitals = JSONArray.parseArray(re.getString("data"));
            logger.info("hospitals size:"+hospitals.size());
            if(hospitals!=null&&hospitals.size()>0){
                Integer addCount = 0;
                Integer updateCount =0;
                for(int i=0;i<hospitals.size();i++){
                    JSONObject h = (JSONObject) hospitals.get(i);
                    String code = h.getString("code");
                    if(!baseOrgDao.existsByCode(code)){
                        BaseOrgDO org = new BaseOrgDO();
                        org.setCode(code);
                        org.setName(h.getString("name"));
                        org.setProvinceCode(h.getString("province"));
                        org.setProvinceName(h.getString("provinceName"));
                        org.setCityCode(h.getString("city"));
                        org.setCityName(h.getString("cityName"));
                        org.setTownCode(h.getString("town"));
                        org.setTownName(h.getString("townName"));
                        org.setOrgLevel(h.getInteger("level"));
                        org.setType("1");
                        org.setWinNo("-1");
                        org.setDel("1");
                        baseOrgDao.save(org);
                        addCount++;
                    }else{
                        BaseOrgDO org = baseOrgDao.findByCode(code);
                        org.setName(h.getString("name"));
                        org.setProvinceCode(h.getString("province"));
                        org.setProvinceName(h.getString("provinceName"));
                        org.setCityCode(h.getString("city"));
                        org.setCityName(h.getString("cityName"));
                        org.setTownCode(h.getString("town"));
                        org.setTownName(h.getString("townName"));
                        org.setOrgLevel(h.getInteger("level"));
                        baseOrgDao.save(org);
                        updateCount++;
                    }
                }
                logger.info("hospitals addCount:"+addCount+" updateCount:"+updateCount);
            }
        }
        return "ok";
    }

    public String findWlyyDept(){
        JSONObject re = wlyyHttpService.sendWlyyMes("findWlyyDept",null,null);
        if(re!=null){
            JSONArray depts = JSONArray.parseArray(re.getString("data"));
            logger.info("depts size:"+depts.size());
            if(depts!=null&&depts.size()>0){
                Integer addCount = 0;
                for(int i=0;i<depts.size();i++){
                    JSONObject d = (JSONObject) depts.get(i);
                    String code = d.getString("code");
                    String hospital = d.getString("hospital");
                    if(!dictHospitalDeptDao.existsByCodeAndOrgCode(code,hospital)){
                        DictHospitalDeptDO deptDO = new DictHospitalDeptDO();
                        deptDO.setCode(code);
                        deptDO.setName(d.getString("name"));
                        deptDO.setOrgCode(hospital);
                        deptDO.setConsultDeptFlag("1");
                        deptDO.setCreateTime(new Date());
                        dictHospitalDeptDao.save(deptDO);
                        addCount++;
                    }

                }
                logger.info("Dept addCount"+addCount);
            }
        }
        return "ok";
    }

    public String findWlyyDoctor()throws Exception{
        JSONObject re = wlyyHttpService.sendWlyyMes("findWlyyDoctor",null,null);
        if(re!=null){
            JSONArray doctors = JSONArray.parseArray(re.getString("data"));
            logger.info("doctors size:"+doctors.size());
            if(doctors!=null&&doctors.size()>0){
                Integer count = 0;
                //获取全部职称.
                List<Map<String,Object>> dutys = findDutys();

                for(int i=0;i<doctors.size();i++){
                    try {
                        JSONObject doctorJson = (JSONObject) doctors.get(i);
                        String idcard = doctorJson.getString("idcard");
                        if(StringUtils.isNotBlank(idcard)) {
                            List<BaseDoctorDO> ds = baseDoctorDao.findByIdcard(idcard);
                            if (ds != null && ds.size() > 0) {
                                //已有账号更新
                                BaseDoctorDO doctor = ds.get(0);
                                doctor.setName(doctorJson.getString("name"));
                                doctor.setIdcard(doctorJson.getString("idcard"));
                                doctor.setMobile(doctorJson.getString("mobile"));
                                doctor.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(idcard)));
                                doctor.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));
                                doctor.setProvinceCode(doctorJson.getString("province"));
                                doctor.setProvinceName(doctorJson.getString("provinceName"));
                                doctor.setTownCode(doctorJson.getString("town"));
                                doctor.setTownName(doctorJson.getString("townName"));
                                doctor.setCityCode(doctorJson.getString("city"));
                                doctor.setCityName(doctorJson.getString("cityName"));
                                doctor.setExpertise(doctorJson.getString("expertise"));
                                doctor.setIntroduce(doctorJson.getString("introduce"));
//                                String salt = randomString(5);
//                                String pw = idcard.substring(idcard.length() - 6);
//                                doctor.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
//                                doctor.setSalt(salt);

                                String jobName = doctorJson.getString("jobName");
                                doctor.setJobTitleCode(getDutysCode(dutys, jobName));
                                doctor.setJobTitleName(jobName);
                                baseDoctorDao.save(doctor);

                                //更新机构科室信息
                                String orgCode =doctorJson.getString("hospital");
                                if(StringUtils.isNotBlank(orgCode)){
                                    List<BaseDoctorHospitalDO> hospitalDOs = baseDoctorHospitalDao.findByOrgCodeAndDoctorCode(orgCode,doctor.getId());
                                    if(hospitalDOs!=null&&hospitalDOs.size()>0){
                                        BaseDoctorHospitalDO hospitalDO = hospitalDOs.get(0);
                                        hospitalDO.setOrgCode(doctorJson.getString("hospital"));
                                        hospitalDO.setOrgName(doctorJson.getString("hospitalName"));
                                        hospitalDO.setDeptCode(doctorJson.getString("dept"));
                                        hospitalDO.setDeptName(doctorJson.getString("deptName"));
                                        baseDoctorHospitalDao.save(hospitalDO);
                                    }
                                }


                            } else {

                                BaseDoctorDO doctor = new BaseDoctorDO();
                                doctor.setName(doctorJson.getString("name"));
                                doctor.setIdcard(doctorJson.getString("idcard"));
                                doctor.setMobile(doctorJson.getString("mobile"));
                                doctor.setSex(Integer.parseInt(IdCardUtil.getSexForIdcard_new(idcard)));
                                doctor.setBirthday(IdCardUtil.getBirthdayForIdcard(idcard));
                                doctor.setProvinceCode(doctorJson.getString("province"));
                                doctor.setProvinceName(doctorJson.getString("provinceName"));
                                doctor.setTownCode(doctorJson.getString("town"));
                                doctor.setTownName(doctorJson.getString("townName"));
                                doctor.setCityCode(doctorJson.getString("city"));
                                doctor.setCityName(doctorJson.getString("cityName"));
                                doctor.setExpertise(doctorJson.getString("expertise"));
                                doctor.setIntroduce(doctorJson.getString("introduce"));
                                doctor.setOutpatientType("zj");
                                //认证信息设置
                                String salt = randomString(5);
                                String pw = idcard.substring(idcard.length() - 6);
                                doctor.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                doctor.setSalt(salt);
                                doctor.setDel("1");
                                doctor.setEnabled(1);
                                doctor.setLocked(0);
                                doctor.setCreateTime(new Date());

                                String jobName = doctorJson.getString("jobName");
                                doctor.setJobTitleCode(getDutysCode(dutys, jobName));
                                doctor.setJobTitleName(jobName);

                                BaseDoctorDO temp = baseDoctorDao.save(doctor);

                                //机构信息部门信息
                                BaseDoctorHospitalDO hospitalDO = new BaseDoctorHospitalDO();
                                hospitalDO.setDoctorCode(temp.getId());
                                hospitalDO.setOrgCode(doctorJson.getString("hospital"));
                                hospitalDO.setOrgName(doctorJson.getString("hospitalName"));
                                hospitalDO.setDeptCode(doctorJson.getString("dept"));
                                hospitalDO.setDeptName(doctorJson.getString("deptName"));
                                hospitalDO.setDel("1");
                                baseDoctorHospitalDao.save(hospitalDO);

                                Integer level = doctorJson.getInteger("level");
                                BaseDoctorRoleDO role = new BaseDoctorRoleDO();
                                role.setDoctorCode(temp.getId());
                                if (level != null && level == 1) {
                                    role.setRoleCode("specialist");
                                } else {
                                    role.setRoleCode("generalDoctor");
                                }
                                baseDoctorRoleDao.save(role);


                                DoctorMappingDO mappingDO = new DoctorMappingDO();
                                mappingDO.setIdcard(idcard);
                                mappingDO.setDoctor(temp.getId());
                                mappingDO.setOrgCode(doctorJson.getString("hospital"));
                                mappingDO.setOrgName(doctorJson.getString("hospitalName"));
                                mappingDO.setMappingCode(temp.getId());
                                mappingDO.setDoctorName(temp.getName());
                                mappingDO.setMappingDeptName(temp.getName());
                                mappingDO.setCreateTime(new Date());
                                doctorMappingDao.save(mappingDO);
                                count++;
                            }
                        }

                    }catch (Exception e){
                        logger.info("data error");
                    }
                }
                logger.info("add count:"+count);
            }
        }
        return "ok";
    }

    /**
     * 获取全部职称
     * @return
     */
    public List<Map<String,Object>> findDutys(){
        String sql = "select code,name from dict_doctor_duty";
        return jdbcTemplate.queryForList(sql);
    }

    public String getDutysCode(List<Map<String,Object>> dutys,String name){
        if(StringUtils.isNotBlank(name)){
            for(Map<String,Object> d:dutys){
                String duty = (String)d.get("name");
                if(name.equals(duty)){
                    return (String)d.get("code");
                }
            }
        }
        return "";
    }

    public String randomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuffer buffer = new StringBuffer();
        Random random = new Random();

        for(int i = 0; i < length; ++i) {
            int pos = random.nextInt(str.length());
            buffer.append(str.charAt(pos));
        }

        return buffer.toString();
    }
    
    /**
     * 推送i健康智能助手模版消息
     * @param wxurl
     */
    public void sendDoctorTemplateByDoctorIdcard(String wxurl) {
        String re = HttpUtil.sendGet(wxurl);
        JSONObject reObject = JSONObject.parseObject(re);
        if(200 == reObject.getInteger("status")){
            logger.info("请求成功,"+re);
        }else{
            logger.info("请求失败");

        }
    }

    public static void main(String ag[]){
        String id = "350212198709121575";
        String salt = "dfgtr";
        String pw = id.substring(id.length() - 6);
        String  spw = MD5.md5Hex(pw + "{" + salt + "}");
        System.out.println(spw);
    }
}
