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

import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.dict.dao.BaseJobCategoryDao;
import com.yihu.jw.entity.base.dict.BaseJobCategoryDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.base.patient.PatientMedicareCardDO;
import com.yihu.jw.entity.hospital.family.BasePatientMemberDictDO;
import com.yihu.jw.entity.hospital.family.WlyyPatientFamilyMemberDO;
import com.yihu.jw.entity.hospital.mapping.PatientMappingDO;
import com.yihu.jw.hospital.dict.WlyyHospitalSysDictDao;
import com.yihu.jw.hospital.family.dao.BasePatientMemberDictDao;
import com.yihu.jw.hospital.family.dao.WlyyPatientFamilyMemberDao;
import com.yihu.jw.hospital.mapping.dao.PatientMappingDao;
import com.yihu.jw.hospital.prescription.service.entrance.EntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.TnyyEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.XzzxEntranceService;
import com.yihu.jw.hospital.prescription.service.entrance.YkyyEntranceService;
import com.yihu.jw.hospital.ykyy.service.YkyyService;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.patient.dao.BasePatientMedicareCardDao;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.util.date.DateUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class WlyyFamilyMemberService extends BaseJpaService<WlyyPatientFamilyMemberDO, WlyyPatientFamilyMemberDao> {
    @Autowired
    private WlyyPatientFamilyMemberDao wlyyPatientFamilyMemberDao;
    @Autowired
    private BasePatientMemberDictDao basePatientMemberDictDao;
    @Autowired
    private EntranceService entranceService;
    @Autowired
    private PatientMappingDao patientMappingDao;
    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private YkyyEntranceService ykyyEntranceService;
    @Autowired
    private BasePatientMedicareCardDao basePatientMedicareCardDao;
    @Autowired
    private XzzxEntranceService xzzxEntranceService;
    @Autowired
    private WlyyHospitalSysDictDao wlyyHospitalSysDictDao;
    @Autowired
    private TnyyEntranceService tnyyEntranceService;
    @Autowired
    private YkyyService ykyyService;
    @Value("${wechat.id}")
    private String wxId;
    @Autowired
    private BaseJobCategoryDao baseJobCategoryDao;

    //添加关联家属
    @Transactional
    public MixEnvelop addFamily(String id,String patientId, String familyName, String dictId, String cardType, String idCard, String phoneNum,boolean demo,String medicareType,String medicare,String clinicId) throws Exception {
        MixEnvelop mixEnvelop = new MixEnvelop();
        try{
        BasePatientMemberDictDO basePatientMemberDictDO = basePatientMemberDictDao.findOne(dictId);
        BasePatientDO basePatientDO = null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            /*List<BasePatientDO> listpatients=basePatientDao.findByMobileAndDel(phoneNum,"1");
            if (listpatients!=null&&listpatients.size()>0){
                basePatientDO=listpatients.get(0);
            }*/
            basePatientDO= basePatientDao.findByIdcard(idCard);
        }else {
            basePatientDO= basePatientDao.findByIdcard(idCard);
        }

        List<BasePatientDO> list = basePatientDao.findByMobile(phoneNum);
        if ("xm_xzzx_wx".equalsIgnoreCase(wxId)){
            if (list!=null&&list.size()>0&&basePatientDO!=null){
                if (basePatientDO.getMobile().equalsIgnoreCase(phoneNum)){

                }else{
                    mixEnvelop.setStatus(408);
                    mixEnvelop.setMessage("您所添加的家属手机号已被他人占用");
                    return  mixEnvelop;
                }
            }else if (list!=null&&list.size()>0&&basePatientDO==null){
                mixEnvelop.setStatus(408);
                mixEnvelop.setMessage("您所添加的家属手机号已被他人占用");
                return  mixEnvelop;
            } else {
                if(basePatientDO==null){
                    basePatientDO = new BasePatientDO();
                }
                basePatientDO.setMobile(phoneNum);
            }
        }else{
            if(basePatientDO==null){
                basePatientDO = new BasePatientDO();
            }
        }
        Map<String,Object> resultMap = new HashMap<>();
        PatientMappingDO patientMappingDO = patientMappingDao.findByIdcard(idCard);
        if(null==patientMappingDO){
            patientMappingDO = new PatientMappingDO();
        }
        WlyyPatientFamilyMemberDO result = new WlyyPatientFamilyMemberDO();
        if (StringUtils.isNotBlank(id)){
            result = wlyyPatientFamilyMemberDao.findOne(id);
            basePatientDO = basePatientDao.findById(result.getFamilyMember());
            patientMappingDO = patientMappingDao.findByPatient(result.getFamilyMember());
        }

        String dictName = "";
        if (null!=basePatientMemberDictDO){
            dictName = basePatientMemberDictDO.getRelationName();
        }
        String familyId="";
        String birth = "";
        String yktFamilyId = "";
        int sex=3;
        //获取his家属数据
        JSONArray jsonArray = new JSONArray();
        if("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            jsonArray = ykyyEntranceService.findHisPatientBymMedicare(medicare,clinicId,false);
            if(jsonArray!=null&&jsonArray.size()>0){
                net.sf.json.JSONObject jsonObject= net.sf.json.JSONObject.fromObject(jsonArray.get(0).toString());
                if (null!=jsonObject.get("brid")){
                    String Pat_name = jsonObject.getString("brxm");
                    if (!Pat_name.equalsIgnoreCase(familyName)) {
                        mixEnvelop.setStatus(408);
                        mixEnvelop.setMessage("您所添加的家属的名称有误，无法添加");
                        return mixEnvelop;
                    }

                    /*basePatientDO.setMobile(phoneNum);*/
                    familyId= jsonObject.getString("brid");
                    birth= jsonObject.getString("csny");
                    long lt = new Long(birth);
                    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
                    birth = sf.format(lt);
                    String familySex = IdCardUtil.getSexForIdcard(idCard);
                    if (familySex.equalsIgnoreCase("男")){
                        familySex= "1";
                        sex =1 ;
                    }else if (familySex.equalsIgnoreCase("女")){
                        familySex = "0";
                        sex = 2 ;
                    }else {
                        familySex = "2";
                        sex = 3;
                    }
                    String familyAge = String.valueOf(IdCardUtil.getAgeForIdcard(idCard));
                    BasePatientMemberDictDO basePatientMemberDictDO1 = basePatientMemberDictDao.findOne(dictId);
                    String relationName = "";
                    if (null!=basePatientMemberDictDO1){
                        relationName=basePatientMemberDictDO1.getRelationName();
                    }
                    BasePatientDO basePatientDO1  = basePatientDao.findById(patientId);
                    String res = "";
                    //id不为空则为修改家人关系
                    if (StringUtils.isNotBlank(id)){
                        if (null!=basePatientDO1){
                            res = ykyyService.updateYktFamily(familyName,idCard, familySex,familyAge,phoneNum,medicare,relationName,clinicId,result.getYktFamilyId(),birth);
                        }
                        if (StringUtils.isNotEmpty(res)){
                            JSONObject jsonObject1 = JSONObject.parseObject(res);
                            if ("200".equalsIgnoreCase(jsonObject1.getString("code"))){
                                /*JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.getString("data"));
                                yktFamilyId = jsonObject2.getString("ID");*/
                            }else {
                                mixEnvelop.setStatus(408);
                                mixEnvelop.setMessage("更新家人关系失败,请核对个人信息.");
                                return mixEnvelop;
                            }
                        }else {
                            mixEnvelop.setStatus(408);
                            mixEnvelop.setMessage("更新家人关系失败,请核对个人信息.");
                            return mixEnvelop;
                        }
                    }else {
                        if (null!=basePatientDO1){
                            res = ykyyService.addYktFamily(familyName,idCard, familySex,familyAge,phoneNum,medicare,relationName,clinicId,basePatientDO1.getUserId(),birth);
                        }
                        if (StringUtils.isNotEmpty(res)){
                            JSONObject jsonObject1 = JSONObject.parseObject(res);
                            if ("200".equalsIgnoreCase(jsonObject1.getString("code"))){
                                JSONObject jsonObject2 = JSONObject.parseObject(jsonObject1.getString("data"));
                                yktFamilyId = jsonObject2.getString("ID");
                                result.setYktFamilyId(yktFamilyId);
                            }else {
                                mixEnvelop.setStatus(408);
                                mixEnvelop.setMessage("添加家人关系失败,请核对个人信息.");
                                return mixEnvelop;
                            }
                        }else {
                            mixEnvelop.setStatus(408);
                            mixEnvelop.setMessage("添加家人关系失败,请核对个人信息.");
                            return mixEnvelop;
                        }
                    }

                    System.out.println("眼科转换后的csny"+birth);
                }else {
                    mixEnvelop.setStatus(408);
                    mixEnvelop.setMessage("您所添加的家属无就诊记录无法添加");
                    return mixEnvelop;
                }

            }else {
                mixEnvelop.setStatus(408);
                mixEnvelop.setMessage("您所添加的家属无就诊记录无法添加");
                return mixEnvelop;
            }
        }else if ("xm_zsyy_wx".equalsIgnoreCase(wxId)) {
            jsonArray = entranceService.BS10008(idCard, "", "", "", "", "", demo);
            if (jsonArray != null && jsonArray.size() > 0) {
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(jsonArray.get(0).toString());
                //如果病人id为空则没有就诊记录
                if (null != jsonObject.get("Patient_Id")) {
                    familyId = jsonObject.getString("Patient_Id");
                    String Pat_name = jsonObject.getString("Pat_Name");
                    if (null != jsonObject.get("Phone_Number_Business")) {
                        String Next_Of_Kin_Phone = jsonObject.get("Phone_Number_Business").toString();
                        if (!Next_Of_Kin_Phone.equalsIgnoreCase(phoneNum)) {
                            mixEnvelop.setStatus(408);
                            mixEnvelop.setMessage("您所添加的家属的电话有误，无法添加");
                            return mixEnvelop;
                        }
                        basePatientDO.setMobile(phoneNum);
                        basePatientDO.setPhone(phoneNum);
                    }
                    if (!Pat_name.equalsIgnoreCase(familyName)) {
                        mixEnvelop.setStatus(408);
                        mixEnvelop.setMessage("您所添加的家属的名称有误，无法添加");
                        return mixEnvelop;
                    }
                    if(null!=jsonObject.get("Birth_Date")){
                        birth = jsonObject.get("Birth_Date").toString();
                    }
                    if(null!=jsonObject.get("Sex")){
                        sex = Integer.parseInt(jsonObject.get("Sex").toString());
                    }
                }else {
                mixEnvelop.setStatus(408);
                mixEnvelop.setMessage("您所添加的家属无就诊记录，无法添加");
            }
            }
        }else if ("xm_xzzx_wx".equalsIgnoreCase(wxId)) {
            com.alibaba.fastjson.JSONArray jsonArray1 = xzzxEntranceService.selectPateintCardByIdCard(idCard);
            if (null!=jsonArray1&&jsonArray1.size()>0){
                String familySex = IdCardUtil.getSexForIdcard(idCard);
                if (familySex.equalsIgnoreCase("男")){
                    sex =1 ;
                }else if (familySex.equalsIgnoreCase("女")){
                    sex = 2 ;
                }
            }else {
                mixEnvelop.setStatus(408);
                mixEnvelop.setMessage("您所添加的家属无就诊记录，无法添加");
                return  mixEnvelop;
            }
        }else if ("sd_tnzyy_wx".equalsIgnoreCase(wxId)){
            com.alibaba.fastjson.JSONArray jsonArray1 = tnyyEntranceService.selectPatientMappingCode(idCard);
            if (jsonArray1!=null&&jsonArray1.size()>0){
                com.alibaba.fastjson.JSONObject jsonObject = JSONObject.parseObject(jsonArray1.get(0).toString());
                if (jsonObject!=null){
                    familyId = jsonObject.getString("BRID");
                    String familySex = IdCardUtil.getSexForIdcard(idCard);
                    if (familySex.equalsIgnoreCase("男")){
                        sex =1 ;
                    }else if (familySex.equalsIgnoreCase("女")){
                        sex = 2 ;
                    }
                }
            }else {
                mixEnvelop.setStatus(408);
                mixEnvelop.setMessage("您所添加的家属无就诊记录，无法添加");
                return  mixEnvelop;
            }
        }
        basePatientDO.setSex(sex);
        if ("xm_xzzx_wx".equalsIgnoreCase(wxId)){
            basePatientDO.setBirthday(IdCardUtil.getBirthdayForIdcard(idCard));
        }else if("xm_zsyy_wx".equalsIgnoreCase(wxId)||"xm_ykyy_wx".equalsIgnoreCase(wxId)) {
            SimpleDateFormat sf3 = new SimpleDateFormat("yyyy-MM-dd");
            Date saveBirth1 = sf3.parse(birth);
            System.out.println("====="+saveBirth1);
            basePatientDO.setBirthday(saveBirth1);
        }else {
            basePatientDO.setBirthday(IdCardUtil.getBirthdayForIdcard(idCard));
        }
        result.setFamilyRelation(dictId);
        result.setFamilyRelationName(dictName);
        result.setIsDel(1);
        result.setPatient(patientId);
        result.setCardNo(idCard);
        result.setCardType(cardType);
        result.setMobile(phoneNum);
        //保存到base_patient表
        basePatientDO.setName(familyName);
        basePatientDO.setIdcard(idCard);
        basePatientDO.setRegister("0");
        basePatientDO.setEnabled(1);
        basePatientDO.setDel("1");

        BasePatientDO sucessPatient= basePatientDao.save(basePatientDO);
        String patientNewId= "";
        if (sucessPatient!=null){
            patientNewId=sucessPatient.getId();
        }
            result.setFamilyMember(patientNewId);
            wlyyPatientFamilyMemberDao.save(result);
            if (!"xm_xzzx_wx".equalsIgnoreCase(wxId)){
                patientMappingDO.setIdcard(idCard);
                patientMappingDO.setSource("1");
                patientMappingDO.setPatientName(familyName);
                patientMappingDO.setMappingCode(familyId);
                patientMappingDO.setPatient(patientNewId);
                patientMappingDO.setCreateTime(new Date());
                patientMappingDao.save(patientMappingDO);
            }
            resultMap.put("patientId",patientId);
            resultMap.put("familyMember",patientNewId);
            resultMap.put("idCard",idCard);
            resultMap.put("phoneNum",phoneNum);
            resultMap.put("relationName",dictName);
            resultMap.put("name",familyName);
            resultMap.put("cardType",cardType);
            List<Map<String,Object>> resultList = new ArrayList();
            resultList.add(resultMap);
            mixEnvelop.setStatus(200);
            mixEnvelop.setMessage("添加成功");
            mixEnvelop.setDetailModelList(resultList);
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                if (StringUtils.isNotBlank(clinicId)){
                    PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_02",sucessPatient.getId(),"1");
                    if (patientMedicareCardDO==null){
                        patientMedicareCardDO = new PatientMedicareCardDO();
                    }
                    patientMedicareCardDO.setCode(clinicId);
                    //patientMedicareCardDO.setType(medicareType);
                    patientMedicareCardDO.setPatientCode(patientNewId);
                    patientMedicareCardDO.setDel("1");
                    patientMedicareCardDO.setParentType("A");
                    patientMedicareCardDO.setType("A_02");
                    basePatientMedicareCardDao.save(patientMedicareCardDO);
                }
                if (StringUtils.isNotBlank(medicare)){
                    //PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByCode(medicare);
                    PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByTypeAndPatientCodeAndDel("A_01",sucessPatient.getId(),"1");
                    if (patientMedicareCardDO==null){
                        patientMedicareCardDO = new PatientMedicareCardDO();
                    }
                    patientMedicareCardDO.setCode(medicare);
                    //patientMedicareCardDO.setType(medicareType);
                    patientMedicareCardDO.setPatientCode(patientNewId);
                    patientMedicareCardDO.setDel("1");
                    patientMedicareCardDO.setParentType("A");
                    patientMedicareCardDO.setType("A_01");
                    basePatientMedicareCardDao.save(patientMedicareCardDO);
                }

            }

        }catch (Exception e){
            e.printStackTrace();
            mixEnvelop.setStatus(408);
            mixEnvelop.setMessage("添加失败");
        }


        return mixEnvelop;
    }
    //眼科同步家人信息
    @Transactional
    public void saveYktFamily(String patientId) throws Exception{
        try {
            String userId="";
            BasePatientDO basePatientDO = basePatientDao.findById(patientId);
            if (null!=basePatientDO){
                userId = basePatientDO.getUserId();
            }
            List<Map<String, String>> list=new ArrayList<Map<String, String>>();
            String res  = ykyyService.findYktFamily(userId);
            if (StringUtils.isNotEmpty(res)){
                JSONObject jsonObject = JSONObject.parseObject(res);
                if ("200".equalsIgnoreCase(jsonObject.getString("code"))){
                    JSONObject data = jsonObject.getJSONObject("data");
                    List<WlyyPatientFamilyMemberDO> patientFamilyMemberDOS = wlyyPatientFamilyMemberDao.findbyPatient(patientId);
                    if (patientFamilyMemberDOS!=null&&patientFamilyMemberDOS.size()>0){
                        wlyyPatientFamilyMemberDao.delete(patientFamilyMemberDOS);
                    }
                    com.alibaba.fastjson.JSONArray jsonArray = data.getJSONArray("list");
                    if(jsonArray!=null && jsonArray.size()>0) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                            System.out.println("==="+jsonArray.get(i).toString());
                            if (StringUtils.isNotEmpty(jsonObject1.getString("IDCARD"))){
                                System.out.println("同步的身份证号："+jsonObject1.getString("IDCARD"));
                                BasePatientDO patientDO = null;
                                /*if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                                    List<BasePatientDO> listpatients=basePatientDao.findByMobileAndDel(jsonObject1.getString("TEL"),"1");
                                    if (listpatients!=null&&listpatients.size()>0){
                                        patientDO=listpatients.get(0);
                                    }
                                }else {*/
                                patientDO= basePatientDao.findByIdcard(jsonObject1.getString("IDCARD"));
                        /*        }*/
                                if (patientDO==null){
                                    patientDO = new BasePatientDO();
                                }
                                if (StringUtils.isNotBlank(jsonObject1.getString("TEL"))){
                                    List<BasePatientDO> listpatients=basePatientDao.findByMobileAndDel(jsonObject1.getString("TEL"),"1");
                                    if (listpatients!=null&&listpatients.size()>0){
                                    }else {
                                        patientDO.setMobile(jsonObject1.getString("TEL"));
                                    }
                                }
                                if(StringUtils.isNotBlank(jsonObject1.getString("BIRTHDAY"))){
                                    patientDO.setBirthday(DateUtil.strToDate(jsonObject1.getString("BIRTHDAY")));
                                }
                                String pw = null;
                                String salt = UUID.randomUUID().toString().substring(0,5);
                                String mobile = jsonObject1.getString("TEL");
                                String idcard = jsonObject1.getString("IDCARD");
                                if(org.apache.commons.lang3.StringUtils.isNotBlank(mobile)){
                                    pw = mobile.substring(mobile.length()-6);
                                }else{
                                    pw = idcard.substring(idcard.length()-6);
                                }
                                patientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
                                patientDO.setSalt(salt);
                                patientDO.setIdcard(jsonObject1.getString("IDCARD"));
                                patientDO.setName(jsonObject1.getString("NAME"));
                                if(jsonObject1.getInteger("SEX")!=null){
                                    if (1==jsonObject1.getInteger("SEX")){
                                        patientDO.setSex(1);
                                    }else if (0==jsonObject1.getInteger("SEX")){
                                        patientDO.setSex(2);
                                    }else {
                                        patientDO.setSex(0);
                                    }
                                }
                                patientDO.setDel("1");
                                patientDO.setEnabled(1);
                                patientDO.setLocked(0);
                                patientDO.setCreateTime(new Date());
                                patientDO.setUpdateTime(new Date());
                                patientDO = basePatientDao.save(patientDO);
                                //取his中的病人code
                                JSONArray hisArray = ykyyEntranceService.findHisPatientBymMedicare(jsonObject1.getString("MEDICALCARD"),jsonObject1.getString("CLINICID"),false);
                                if(hisArray!=null&&hisArray.size()>0) {
                                    net.sf.json.JSONObject hisObject = net.sf.json.JSONObject.fromObject(hisArray.get(0).toString());
                                    PatientMappingDO patientMappingDO = patientMappingDao.findByIdcard(patientDO.getIdcard());
                                    if(patientMappingDO==null){
                                        patientMappingDO= new PatientMappingDO();
                                    }
                                    patientMappingDO.setPatientName(jsonObject1.getString("NAME"));
                                    patientMappingDO.setPatient(patientDO.getId());
                                    patientMappingDO.setMappingCode(hisObject.getString("brid"));
                                    patientMappingDO.setSource("1");
                                    patientMappingDO.setCreateTime(new Date());
                                    patientMappingDO.setIdcard(patientDO.getIdcard());
                                    patientMappingDao.save(patientMappingDO);
                                }
                                WlyyPatientFamilyMemberDO wlyyPatientFamilyMemberDO = new WlyyPatientFamilyMemberDO();
                                BasePatientMemberDictDO basePatientMemberDictDO =basePatientMemberDictDao.findByRelationName(jsonObject1.getString("ILLNESS"));
                                if (basePatientMemberDictDO!=null){
                                    wlyyPatientFamilyMemberDO.setIsDel(1);
                                    wlyyPatientFamilyMemberDO.setPatient(patientId);
                                    wlyyPatientFamilyMemberDO.setClinicid(jsonObject1.getString("CLINICID"));
                                    wlyyPatientFamilyMemberDO.setCardType("身份证");
                                    wlyyPatientFamilyMemberDO.setFamilyMember(patientDO.getId());
                                    wlyyPatientFamilyMemberDO.setFamilyRelation(basePatientMemberDictDO.getId());
                                    wlyyPatientFamilyMemberDO.setFamilyRelationName(basePatientMemberDictDO.getRelationName());
                                    wlyyPatientFamilyMemberDO.setCardNo(jsonObject1.getString("IDCARD"));
                                    wlyyPatientFamilyMemberDO.setYktFamilyId(jsonObject1.getString("ID"));
                                    if (StringUtils.isNotBlank(jsonObject1.getString("TEL"))){
                                        wlyyPatientFamilyMemberDO.setMobile(jsonObject1.getString("TEL"));
                                    }
                                    wlyyPatientFamilyMemberDao.save(wlyyPatientFamilyMemberDO);
                                }
                                if(jsonObject1.get("MEDICALCARD")!=null){
                                    List<PatientMedicareCardDO> patientMedicareCardDOS =  basePatientMedicareCardDao.findByPatientCode(patientDO.getId());
                                    boolean flag = false;
                                    PatientMedicareCardDO patientMedicareCardDO1 = new PatientMedicareCardDO();
                                    for (PatientMedicareCardDO medicareCardDO:patientMedicareCardDOS){
                                        if (medicareCardDO.getType().equalsIgnoreCase("A_01")){
                                            flag=true;
                                            patientMedicareCardDO1=medicareCardDO;
                                            break;
                                        }
                                    }
                                    System.out.println("flag"+flag);
                                    PatientMedicareCardDO patientMedicareCardDO = basePatientMedicareCardDao.findByCodeAndPatientCode(jsonObject1.getString("MEDICALCARD"),patientDO.getId());
                                    if (patientMedicareCardDO==null&&flag==false){
                                        patientMedicareCardDO = new PatientMedicareCardDO();
                                        patientMedicareCardDO.setCode(jsonObject1.getString("MEDICALCARD"));
                                        patientMedicareCardDO.setParentType("A");
                                        patientMedicareCardDO.setType("A_01");
                                        patientMedicareCardDO.setPatientCode(patientDO.getId());
                                        patientMedicareCardDO.setDel("1");
                                        basePatientMedicareCardDao.save(patientMedicareCardDO);
                                    }else if (patientMedicareCardDO!=null&&flag==true&&patientMedicareCardDO1!=null){
                                        patientMedicareCardDO1.setCode(jsonObject1.getString("MEDICALCARD"));
                                        patientMedicareCardDO1.setParentType("A");
                                        patientMedicareCardDO1.setType("A_01");
                                        patientMedicareCardDO1.setPatientCode(patientDO.getId());
                                        patientMedicareCardDO1.setDel("1");
                                        basePatientMedicareCardDao.save(patientMedicareCardDO1);
                                    }

                                }
                            }
                        }
                    }
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            System.out.println("同步家人关系失败");
        }
    }
    //根据患者id查询关联家属
    @Transactional
    public List<Map<String,Object>> findFamilyByPatientId(String patientId) throws ParseException {
        if("xm_ykyy_wx".equalsIgnoreCase(wxId)){
            String sql = "select t.id as \"id\",t.card_type as \"cardType\", " +
                    "t.patient as \"patient\",b.name as \"name\",b.sex as \"sex\","+
                    "to_char(b.birthday,'yyyy-MM-dd') as\"birthday\",b.idcard as \"idcard\",t.clinicid as \"clinicid\"," +
                    "t.family_member as \"familyMember\",c.relation_name as \"relationName\" "+
                    " from wlyy_patient_family_member t left join base_patient b" +
                    " on t.family_member = b.id left join base_patient_member_dict c on t.family_relation=c.id where 1=1 and t.is_del=1 ";
            if (StringUtils.isNotBlank(patientId)){
                sql += " and t.patient = '"+patientId+"'";
            }
            List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
            if (list!=null&&list.size()>0){
                for (Map<String,Object> map:list){
                    if (null!=map.get("idcard")){
                        map.put("age",IdCardUtil.getAgeForIdcard(map.get("idcard").toString()));
                    }
                    if (null!=map.get("birthday")){
                        System.out.println("birthday:"+map.get("birthday").toString());
                    }
                    List<PatientMedicareCardDO> list1 = basePatientMedicareCardDao.findByPatientCode(map.get("familyMember").toString());
                    if (null!=list1&&list1.size()>0){
                        map.put("card",list1.get(0));
                    }else {
                        map.put("card","");
                    }
                    WlyyPatientFamilyMemberDO patientFamilyMemberDO = wlyyPatientFamilyMemberDao.findByIdAndDel(map.get("id").toString());
                    if (patientFamilyMemberDO!=null){
                        map.put("mobile",patientFamilyMemberDO.getMobile());
                    }

                }
            }
            return list;
        }else {
            String sql = "select t.id as \"id\",t.card_type as \"cardType\", " +
                    "t.patient as \"patient\",b.name as \"name\",b.sex as \"sex\","+
                    "b.birthday as\"birthday\",b.idcard as \"idcard\"," +
                    "t.family_member as \"familyMember\",c.relation_name as \"relationName\" "+
                    " from wlyy_patient_family_member t left join base_patient b" +
                    " on t.family_member = b.id left join base_patient_member_dict c on t.family_relation=c.id where 1=1 and t.is_del=1 ";
            if (StringUtils.isNotBlank(patientId)){
                sql += " and t.patient = '"+patientId+"'";
            }
            List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
            if (list!=null&&list.size()>0){
                for (Map<String,Object> map:list){
                    if (map.get("birthday")!=null){
                        SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
                        int age = getAgeByBirth(sp.parse(map.get("birthday").toString()));
                        map.put("age",age);
                    }
                    List<PatientMedicareCardDO> list1 = basePatientMedicareCardDao.findByPatientCode(map.get("familyMember").toString());
                    map.put("cardList",list1);
                }
            }
            return list;
        }
    }

    private static int getAgeByBirth(Date birthday) {
        int age = 0;
        try {
            Calendar now = Calendar.getInstance();
            now.setTime(new Date());// 当前时间

            Calendar birth = Calendar.getInstance();
            birth.setTime(birthday);

            if (birth.after(now)) {//如果传入的时间，在当前时间的后面，返回0岁
                age = 0;
            } else {
                age = now.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
                if (now.get(Calendar.DAY_OF_YEAR) > birth.get(Calendar.DAY_OF_YEAR)) {
                    age += 1;
                }
            }
            return age;
        } catch (Exception e) {//兼容性更强,异常后返回数据
            return 0;
        }
    }
    //删除家人信息
    public Envelop delMember(String id){
        Envelop envelop = new Envelop();
        WlyyPatientFamilyMemberDO wlyyPatientFamilyMemberDO = wlyyPatientFamilyMemberDao.findOne(id);
        if (wlyyPatientFamilyMemberDO!=null){
            wlyyPatientFamilyMemberDO.setIsDel(0);
            if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                //删除眼科通的家人关系
                String res = ykyyService.deleteYktFamily(wlyyPatientFamilyMemberDO.getYktFamilyId());
                if (StringUtils.isNotEmpty(res)){
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    if ("200".equalsIgnoreCase(jsonObject.getString("code"))){
                        envelop.setMessage("删除成功");
                    }else {
                        envelop.setMessage("删除失败");
                        envelop.setStatus(-1);
                        return envelop;
                    }
                }else {
                    envelop.setMessage("删除失败");
                    envelop.setStatus(-1);
                    return envelop;
                }

            }
            wlyyPatientFamilyMemberDao.save(wlyyPatientFamilyMemberDO);
            envelop.setMessage("删除成功");
            return envelop;
        }else {
            envelop.setMessage("删除失败");
            envelop.setStatus(408);
            return envelop;
        }
    }
    //获取单个亲属详细信息
    public List<Map<String,Object>>  findMemberById(String id) throws Exception {
        String sql="select t.id as \"id\",t.card_type as \"cardType\"," +
                "t.family_member as \"familyMember\",t.patient as \"patient\"," +
                "b.name as \"name\",b.idcard as \"idcard\",b.mobile as \"mobile\",t.clinicid as \"clinicid\"," +
                "c.relation_name \"relationName\",b.birthday as\"birthday\",b.sex as\"sex\"" +
                " from wlyy_patient_family_member t left join base_patient b" +
                " on t.family_member = b.id left join base_patient_member_dict c on t.family_relation=c.id " +
                " where 1=1 and t.is_del = 1 ";
        if (StringUtils.isNotBlank(id)){
            sql+=" and t.id='"+id+"'";
        }
       List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql);
        if (list!=null&&list.size()>0){
            for (Map<String,Object> map:list){
                if (map.get("birthday")!=null){
                    SimpleDateFormat sp = new SimpleDateFormat("yyyy-MM-dd");
                    int age = getAgeByBirth(sp.parse(map.get("birthday").toString()));
                    map.put("age",age);
                }
                if ("xm_ykyy_wx".equalsIgnoreCase(wxId)){
                    WlyyPatientFamilyMemberDO patientFamilyMemberDO = wlyyPatientFamilyMemberDao.findByIdAndDel(map.get("id").toString());
                    if (patientFamilyMemberDO!=null){
                        map.put("mobile",patientFamilyMemberDO.getMobile());
                    }
                    if(null!=map.get("familyMember")){
                        List<PatientMedicareCardDO> list1 = basePatientMedicareCardDao.findByPatientCode(map.get("familyMember").toString());
                        if (list1!=null&&list1.size()!=0){
                            for (PatientMedicareCardDO patientMedicareCardDO:list1){
                                if (patientMedicareCardDO.getType().equalsIgnoreCase("A_02")){
                                    map.put("clinicid",patientMedicareCardDO.getCode());
                                }else {
                                    map.put("card",patientMedicareCardDO);
                                }
                            }
                            JSONObject object = ykyyEntranceService.selectByAddress(list1.get(0).getCode());
                            if (object!=null){
                                map.put("address",object.getString("address"));
                                map.put("zydm",object.getString("zydm"));
                                if (StringUtils.isNotBlank(object.getString("zydm"))){
                                    BaseJobCategoryDO jobCategoryDO = baseJobCategoryDao.findOne(Integer.parseInt(object.getString("zydm")));
                                    if (jobCategoryDO!=null){
                                        map.put("zydmName",jobCategoryDO.getName());
                                    }
                                }else {
                                    map.put("zydmName","");
                                }
                                map.put("jtdh",object.getString("jtdh"));
                            }

                        }else {
                            map.put("card","");
                            map.put("address","");
                            map.put("zydm","");
                            map.put("jtdh","");
                            map.put("zydmName","");

                        }

                    }
                }
            }
        }
        return list;
    }
}
