package com.yihu.jw.rehabilitation.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.doctor.dao.BaseDoctorDao;
import com.yihu.jw.entity.base.doctor.BaseDoctorDO;
import com.yihu.jw.entity.base.patient.BasePatientDO;
import com.yihu.jw.entity.patient.Patient;
import com.yihu.jw.entity.specialist.DoctorPatientRelationDO;
import com.yihu.jw.entity.specialist.rehabilitation.PatientMedicalRecordsDO;
import com.yihu.jw.patient.dao.BasePatientDao;
import com.yihu.jw.rehabilitation.DoctorPatientRelationDao;
import com.yihu.jw.rehabilitation.PatientMedicalRecordsDao;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.util.common.IdCardUtil;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.mysql.query.BaseJpaService;
import com.yihu.utils.security.MD5;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
public class DoctorPatientRelationService <T, R extends CrudRepository> extends BaseJpaService<DoctorPatientRelationDO, DoctorPatientRelationDao> {

    @Autowired
    private BasePatientDao basePatientDao;
    @Autowired
    private BaseDoctorDao baseDoctorDao;
    @Autowired
    private HibenateUtils hibenateUtils;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private DoctorPatientRelationDao doctorPatientRelationDao;
    @Autowired
    private PatientMedicalRecordsDao patientMedicalRecordsDao;

    public MixEnvelop findDoctorPatients(String doctor, String patient, String patientName, String isdeal, String idcard,Integer page , Integer pageSize){
        MixEnvelop mixEnvelop = new MixEnvelop();
        String sql = "select t.id as \"id\"," +
                " t.discharge_record as \"dischargeRecord\"," +
                " t.doctor as \"doctor\"," +
                " t.doctor_name as \"doctorName\"," +
                " t.patient as \"patient\"," +
                " t.patient_name as \"patientName\"," +
                " t.create_time as \"createTime\"," +
                " t.isdeal as \"isdeal\"," +
                " b.idcard as \"idcard\"," +
                " t.status as \"status\"," +
                " t.relation_type as \"relationType\"" +
                " from wlyy_doctor_patient_relation t " +
                " left join base_patient b on t.patient = b.id where 1=1";
        if (StringUtils.isNoneBlank(doctor)){
            sql+=" and t.doctor='"+doctor+"'";
        }
        if (StringUtils.isNoneBlank(patient)){
            sql+=" and t.patient='"+patient+"'";
        }
        if (StringUtils.isNoneBlank(patientName)){
            sql+=" and t.patient_name like '%"+patientName+"%'";
        }
        if (StringUtils.isNoneBlank(isdeal)){
            sql+=" and t.isdeal = '"+isdeal+"'";
        }
        if (StringUtils.isNoneBlank(idcard)){
            sql+=" and b.idcard = '"+idcard+"'";
        }
        List<Map<String,Object>> list = hibenateUtils.createSQLQuery(sql,page,pageSize);
        for (Map<String,Object> map:list){
            String sex = map.get("idcard")==null?"未知": IdCardUtil.getSexForIdcard_new(map.get("idcard").toString());
            Integer age = map.get("idcard")==null?0: IdCardUtil.getAgeForIdcard(map.get("idcard").toString());
            map.put("sex",sex);
            map.put("age",age);
        }
        mixEnvelop.setDetailModelList(list);
        mixEnvelop.setPageSize(pageSize);
        mixEnvelop.setCurrPage(page);
        mixEnvelop.setTotalCount(list==null?0:list.size());
        return mixEnvelop;
    }
    public void saveSingleDoctorPatientRelation(String json,String relationType) throws  Exception{
        JSONObject jsonObject = JSON.parseObject(json);
        String doctor = jsonObject.getString("doctor");
        String idCard = jsonObject.getString("idCard");
        String patientName = jsonObject.getString("patientName");
        String patientRecord = jsonObject.getString("patientRecord");
        String reOutpatientId = jsonObject.getString("reOutatientId");
        String recordCode="";
        BasePatientDO basePatientDO = basePatientDao.findByIdcard(idCard);
        BaseDoctorDO baseDoctorDO = baseDoctorDao.findById(doctor);

        if (null==basePatientDO){
            basePatientDO.setIdcard(idCard);
            basePatientDO.setName(patientName);
            String salt = UUID.randomUUID().toString().substring(0,5);
            String pw = idCard.substring(idCard.length()-6,idCard.length());
            basePatientDO.setPassword(MD5.md5Hex(pw + "{" + salt + "}"));
            basePatientDO.setDel("1");
            basePatientDO.setLocked(0);
            basePatientDO.setEnabled(1);
            basePatientDO.setSex(Integer.valueOf(IdCardUtil.getSexForIdcard_new(idCard)));
            basePatientDO.setSalt(salt);
            basePatientDO.setBirthday(IdCardUtil.getBirthdayForIdcard(idCard));
            basePatientDO.setCreateTime(new Date());
            basePatientDO=basePatientDao.save(basePatientDO);
        }
        //保存医生居民关系映射表
        if ("1".equalsIgnoreCase(relationType)){
            //创建创建对应的出院记录
            PatientMedicalRecordsDO patientMedicalRecordsDO=objectMapper.readValue(patientRecord, PatientMedicalRecordsDO.class);
            patientMedicalRecordsDO = patientMedicalRecordsDao.save(patientMedicalRecordsDO);
            recordCode=patientMedicalRecordsDO.getCode();
        }else if ("2".equalsIgnoreCase(relationType)){
            recordCode=reOutpatientId;
        }
        DoctorPatientRelationDO doctorPatientRelationDO = doctorPatientRelationDao.findByDoctorAndPatientAndCode(doctor,basePatientDO.getId(),recordCode);
        if (doctorPatientRelationDO==null){
            doctorPatientRelationDO = new DoctorPatientRelationDO();
        }
        doctorPatientRelationDO.setPatient(basePatientDO.getId());
        doctorPatientRelationDO.setPatientName(basePatientDO.getName());
        doctorPatientRelationDO.setDoctor(doctor);
        doctorPatientRelationDO.setDoctorName(baseDoctorDO==null?"":baseDoctorDO.getName());
        doctorPatientRelationDO.setIsdeal("0");
        doctorPatientRelationDO.setStatus("0");
        doctorPatientRelationDO.setRelationType(relationType);
        doctorPatientRelationDO.setDischargeRecord(recordCode);
        doctorPatientRelationDO.setCreateTime(new Date());
        doctorPatientRelationDao.save(doctorPatientRelationDO);

    }
    public void savePatientDisease(){

    }

    /**
     *
     * @param patientInfo
     * @param doctorCode
     * @return
     */
    public JSONObject getPatientByIdcardOrSsc(String patientInfo, String doctorCode) {
        JSONObject data = new JSONObject();
        BasePatientDO patientList = basePatientDao.findByIdcardAndDel(patientInfo,"1");
        BasePatientDO patient = null;
        String recordCode="123";
        if(patientList==null){
            //未找到居民，从健康档案添加居民
            patient = new BasePatientDO();//todo 调用医院查询居民接口
            patient.setName("测试");
            patient.setSex(1);
            patient.setIdcard("210555111199992525");
            patient.setPhone("18877777777");
            basePatientDao.save(patient);
        }else{
            patient = patientList;
        }

        if(patient==null){
            data.put("status", -1);
            data.put("msg", "未查询到患者");
            return data;
        }

        BaseDoctorDO doctor = baseDoctorDao.findById(doctorCode);
        DoctorPatientRelationDO doctorPatientRelationDO = doctorPatientRelationDao.findByDoctorAndPatientAndCode(doctorCode,patient.getId(),recordCode);
        if (doctorPatientRelationDO==null){
            doctorPatientRelationDO = new DoctorPatientRelationDO();
        }
        doctorPatientRelationDO.setPatient(patient.getId());
        doctorPatientRelationDO.setPatientName(patient.getName());
        doctorPatientRelationDO.setDoctor(doctorCode);
        doctorPatientRelationDO.setDoctorName(doctor==null?"":doctor.getName());
        doctorPatientRelationDO.setIsdeal("0");
        doctorPatientRelationDO.setStatus("0");
        doctorPatientRelationDO.setRelationType("");
        doctorPatientRelationDO.setDischargeRecord("");
        doctorPatientRelationDO.setCreateTime(new Date());
        doctorPatientRelationDao.save(doctorPatientRelationDO);
        data.put("status",200);
        return data;
    }

}
