<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.lemon.lifecenter.mapper.PatientMapper">
    <select id="selectPatientCount" parameterType="PatientDTO" resultType="int">
        <![CDATA[
            SELECT count(*) AS total
              FROM PATIENT_CARE
             WHERE 1 = 1
        ]]>
        <if test='state != "ALL"'>
            <![CDATA[
               AND STATE = #{state}
            ]]>
        </if>
        <if test='patientName != null and patientName != ""'>
            <![CDATA[
               AND PATIENT_NAME LIKE CONCAT('%', #{patientName}, '%')
            ]]>
        </if>
        <if test='startDate != null and startDate != "" and endDate != null and endDate != ""'>
            <![CDATA[
               AND DATE_FORMAT(FINAL_CLINIC_DATE, '%Y-%m-%d') BETWEEN #{startDate} AND #{endDate}
            ]]>
        </if>
    </select>
    
    <select id="selectPatientList" parameterType="PatientDTO" resultType="PatientDTO">
        <![CDATA[
            SELECT PATIENT_IDX                                                        AS patientIdx,
                   PATIENT_NAME                                                       AS patientName,
                   CASE WHEN GENDER = 'M' THEN '남'
                        WHEN GENDER = 'F' THEN '여'
                        ELSE ''
                   END                                                                AS gender,
                   (SELECT TRUNC((SYSDATE-TO_DATE(JUMIN, 'YYYYMMDD'))/365) + 1) AS age,
                   ward_number                                                        AS wardNumber,
                   room_number                                                        AS roomNumber,
                   DATE_FORMAT(FINAL_CLINIC_DATE, '%Y-%m-%d %H:%i')                   AS finamClinicDate,
                   DATE_FORMAT(HOSPITALIZATION_DATE, '%Y-%m-%d %H:%i')                AS hospitalizationDate,
                   DATE_FORMAT(DISISOLATION_DATE, '%Y-%m-%d %H:%i')                   AS disisolationDate,
                   CASE WHEN STATE = 'H' THEN '입소'
                        WHEN STATE = 'D' THEN '여'
                        WHEN STATE = 'T' THEN '지정병원 이송'
                        WHEN STATE = 'E' THEN '기타'
                        ELSE ''
                   END                                                                AS state
              FROM PATIENT_CARE
             WHERE 1 = 1
        ]]>
    <if test='state != "ALL"'>
        <![CDATA[
            AND STATE = #{state}
        ]]>
    </if>
    <if test='patientName != null and patientName != ""'>
        <![CDATA[
            AND PATIENT_NAME LIKE CONCAT('%', #{patientName}, '%')
        ]]>
    </if>
    <if test='startDate != null and startDate != "" and endDate != null and endDate != ""'>
        <![CDATA[
            AND DATE_FORMAT(FINAL_CLINIC_DATE, '%Y-%m-%d') BETWEEN #{startDate} AND #{endDate}
        ]]>
    </if>
        <![CDATA[
             ORDER BY HOSPITALIZATION_DATE DESC
             LIMIT ${limit}, ${limitMax}
        ]]>
    </select>
    
    
    <insert id="insertPatientCare" parameterType="PatientDTO" useGeneratedKeys="true">
        <selectKey keyProperty="patientIdx" resultType="int" order="AFTER">
            <![CDATA[
                SELECT CURRENT_VAL AS patientIdx FROM db_serial WHERE NAME = 'patient_care_ai_patient_idx';
            ]]>
        </selectKey>
        <![CDATA[
            INSERT 
              INTO patient_care
                   ( patient_name,      gender,      ward_number,     room_number,        hospitalization_date, state, 
                     center_code,       jumin,       patient_phone,   guardian_phone,     symptom_start_date,   confirmation_date,    disisolation_date, 
                     basal_disease_yn,  drug_yn,     drug_content,    pregnancy_status,   pregnancy_week,       id,                   pw, 
                     create_date,       create_by,   update_by )
                      
            VALUES ( #{patientName},    #{gender},   #{wardNumber},   #{roomNumber},      #{hospitalizationDate}, #{state}, 
                     #{centerCode},     #{jumin},    #{patientPhone}, #{guardianPhone},   #{symptomStartDate},    #{confirmationDate},    #{disisolationDate}, 
                     #{basalDiseaseYn}, #{drugYn},   #{drugContent},  #{pregnancyStatus}, #{pregnancyWeek},       #{id},                  #{pw}, 
                     NOW(),             #{createBy}, '' )
        ]]>
    </insert>
    
    <insert id="insertPatientDisease" parameterType="PatientDTO" useGeneratedKeys="true">
        <![CDATA[
            INSERT
              INTO patient_disease
                   ( patient_idx,                high_blood_pressure_check,    low_blood_pressure_check, organ_transplant_check,  diabetes_check, 
                     respiratory_disease_check,  immunological_disease_check,  dyspnea_check,            cold_fit_check,          muscle_pain_check,
                     headache_check,             sore_throat_check,            smell_palate_check,       fatigue_check,           heart_disease,
                     liver_disease,              `operation`,                  operation_content,        allergy_check,           kidney_disease,
                     cancer_check,               cancer_name,                  etc_check,                etc_content )
            VALUES ( #{patientIdx},              #{highBloodPressureCheck},    #{lowBloodPressureCheck}, #{organTransplantCheck}, #{diabetesCheck}, 
                     #{respiratoryDiseaseCheck}, #{immunologicalDiseaseCheck}, #{dyspneaCheck},          #{coldFitCheck},         #{musclePainCheck}, 
                     #{headacheCheck},           #{soreThroatCheck},           #{smellPalateCheck},      #{fatigueCheck},         #{heartDisease},
                     #{liverDisease},            #{operation},                 #{operationContent},      #{allergyCheck},         #{kidneyDisease}, 
                     #{cancerCheck},             #{cancerName},                #{etcCheck},              #{etcContent} )
        ]]>
    </insert>
    
    <insert id="insertPatientSymptom" parameterType="PatientDTO" useGeneratedKeys="true">
        <![CDATA[
            INSERT 
              INTO patient_symptom
                   ( patient_idx,      fever_check,     cough_check,      colic,              cold_fit_check,        sputum_check, 
                     ocin_check,       fever_right,     fever_left,       fatigue_check,      etc_check,             etc_content, 
                     chest_pain,       nose_check,      vomiting_check,   muscle_pain_check,  sore_throat_check,     diarrhea_check, 
                     headache_check,   dyspnea_check,   pulse_rate,       respiration_rate,   blood_pressure_level,  oxygen_saturation )
                     
            VALUES ( #{patientIdx},    #{feverCheck},   #{coughCheck},    #{colic},           #{coldFitCheck},       #{sputumCheck}, 
                     #{ocinCheck},     #{feverRight},   #{feverLeft},     #{fatigueCheck},    #{etcCheck},           #{etcContent}, 
                     #{chestPain},     #{noseCheck},    #{vomitingCheck}, #{musclePainCheck}, #{soreThroatCheck},    #{diarrheaCheck}, 
                     #{headacheCheck}, #{dyspneaCheck}, #{pulseRate},     #{respirationRate}, #{bloodPressureLevel}, #{oxygenSaturation} )
        ]]>
    </insert>
    
    <select id="selectPatientOne" parameterType="PatientDTO" resultType="PatientDTO">
        <![CDATA[
            SELECT PC.PATIENT_IDX AS patientIdx,
                   PC.PATIENT_NAME AS patientName,
                   PC.GENDER AS gender,
                   PC.WARD_NUMBER AS wardNumber,
                   PC.ROOM_NUMBER AS roomNumber,
                   PC.FINAL_CLINIC_DATE AS finalClinicDate,
                   DATE_FORMAT(PC.HOSPITALIZATION_DATE, '%Y-%m-%d %h:%i') AS hospitalizationDate,
                   PC.STATE AS state,
                   PC.CENTER_CODE AS centerCode,
                   PC.JUMIN AS jumin,
                   PC.PATIENT_PHONE AS patientPhone,
                   PC.GUARDIAN_PHONE AS guardianPhone,
                   DATE_FORMAT(PC.SYMPTOM_START_DATE, '%Y-%m-%d %h:%i') AS symptomStartDate,
                   DATE_FORMAT(PC.CONFIRMATION_DATE, '%Y-%m-%d %h:%i') AS confirmationDate,
                   DATE_FORMAT(PC.DISISOLATION_DATE, '%Y-%m-%d %h:%i') AS disisolationDate,
                   PC.BASAL_DISEASE_YN AS basalDiseaseYn,
                   PC.DRUG_YN AS drugYn,
                   PC.DRUG_CONTENT AS drugContent,
                   PC.PREGNANCY_STATUS AS pregnancyStatus,
                   PC.PREGNANCY_WEEK AS pregnancyWeek,
                   PC.ID AS id,
                   PC.PW AS pw,
                   PC.CREATE_DATE AS createDate,
                   PC.CREATE_BY AS createBy,
                   PC.UPDATE_BY AS updateBy,
            
                   PS.FEVER_CHECK AS feverCheck,
                   PS.COUGH_CHECK AS coughCheck,
                   PS.COLIC AS colic,
                   PS.COLD_FIT_CHECK AS coldFitCheck,
                   PS.SPUTUM_CHECK AS sputumCheck,
                   PS.OCIN_CHECK AS ocinCheck,
                   PS.FEVER_RIGHT AS feverRight,
                   PS.FEVER_LEFT AS feverLeft,
                   PS.FATIGUE_CHECK AS fatigueCheck,
                   PS.ETC_CHECK AS etcCheckSymptom,
                   PS.ETC_CONTENT AS etcContentSymptom,
                   PS.CHEST_PAIN AS chestPain,
                   PS.NOSE_CHECK AS noseCheck,
                   PS.VOMITING_CHECK AS vomitingCheck,
                   PS.MUSCLE_PAIN_CHECK AS musclePainCheck,
                   PS.SORE_THROAT_CHECK AS soreThroatCheck,
                   PS.DIARRHEA_CHECK AS diarrheaCheck,
                   PS.HEADACHE_CHECK AS headacheCheck,
                   PS.DYSPNEA_CHECK AS dyspneaCheck,
                   PS.PULSE_RATE AS pulseRate,
                   PS.RESPIRATION_RATE AS respirationRate,
                   PS.BLOOD_PRESSURE_LEVEL AS bloodPressureLevel,
                   PS.OXYGEN_SATURATION AS oxygenSaturation,
                   
                   PD.HIGH_BLOOD_PRESSURE_CHECK AS highBloodPressureCheck,
                   PD.LOW_BLOOD_PRESSURE_CHECK AS lowBloodPressureCheck,
                   PD.ORGAN_TRANSPLANT_CHECK AS organTransplantCheck,
                   PD.DIABETES_CHECK AS diabetesCheck,
                   PD.RESPIRATORY_DISEASE_CHECK AS respiratoryDiseaseCheck,
                   PD.IMMUNOLOGICAL_DISEASE_CHECK AS immunologicalDiseaseCheck,
                   PD.DYSPNEA_CHECK AS dyspneaCheck,
                   PD.COLD_FIT_CHECK AS coldFitCheck,
                   PD.MUSCLE_PAIN_CHECK AS musclePainCheck,
                   PD.HEADACHE_CHECK AS headacheCheck,
                   PD.SORE_THROAT_CHECK AS soreThroatCheck,
                   PD.SMELL_PALATE_CHECK AS smellPalateCheck,
                   PD.FATIGUE_CHECK AS fatigueCheck,
                   PD.HEART_DISEASE AS heartDisease,
                   PD.LIVER_DISEASE AS liverDisease,
                   PD.`OPERATION` AS `operation`,
                   PD.OPERATION_CONTENT AS operationContent,
                   PD.ALLERGY_CHECK AS allergyCheck,
                   PD.KIDNEY_DISEASE AS kidneyDisease,
                   PD.CANCER_CHECK AS cancerCheck,
                   PD.CANCER_NAME AS cancerName,
                   PD.ETC_CHECK AS etcCheckDisease,
                   PD.ETC_CONTENT AS etcContentDisease,
                   (SELECT CI.CENTER_NAME
                      FROM CENTER_INFO CI
                     WHERE CI.CENTER_CODE = PC.CENTER_CODE) AS centerName
              FROM PATIENT_CARE PC
              LEFT JOIN PATIENT_SYMPTOM PS
                ON PC.PATIENT_IDX = PS.PATIENT_IDX
              LEFT JOIN PATIENT_DISEASE PD
                ON PC.PATIENT_IDX = PD.PATIENT_IDX
             WHERE 1 = 1
               AND PC.PATIENT_IDX = #{patientIdx}
        ]]>
    </select>
    
    <update id="updatePatientCare" parameterType="PatientDTO" useGeneratedKeys="true">
        <![CDATA[
            UPDATE patient_care
               SET patient_name = #{patientName},
                   gender = #{gender},
                   ward_number = #{wardNumber},
                   room_number = #{roomNumber},
                   hospitalization_date = #{hospitalizationDate},
                   state = #{state},
                   center_code = #{centerCode},
                   jumin = #{jumin},
                   patient_phone = #{patientPhone},
                   guardian_phone = #{guardianPhone},
                   symptom_start_date = #{symptomStartDate},
                   confirmation_date = #{confirmationDate},
                   disisolation_date = #{disisolationDate},
                   basal_disease_yn = #{basalDiseaseYn},
                   drug_yn = #{drugYn},
                   drug_content = #{drugContent},
                    pregnancy_status = #{pregnancyStatus},
                   pregnancy_week = #{pregnancyWeek},
                   id = #{id},
                   pw = #{pw},
                   update_date = NOW(),
                   update_by = #{updateBy}
             WHERE patient_idx = #{patientIdx}
        ]]>
    </update>
    
    <update id="updatePatientDisease" parameterType="PatientDTO" useGeneratedKeys="true">
        <![CDATA[
            UPDATE patient_disease
               SET high_blood_pressure_check = #{highBloodPressureCheck},
                   low_blood_pressure_check = #{lowBloodPressureCheck}, 
                   organ_transplant_check = #{organTransplantCheck},  
                   diabetes_check = #{diabetesCheck}, 
                   respiratory_disease_check = #{respiratoryDiseaseCheck}, 
                   immunological_disease_check = #{immunologicalDiseaseCheck}, 
                   dyspnea_check = #{dyspneaCheck},
                   cold_fit_check = #{coldFitCheck},
                   muscle_pain_check =   #{musclePainCheck},
                   headache_check = #{headacheCheck},
                   sore_throat_check = #{soreThroatCheck},
                   smell_palate_check = #{smellPalateCheck},
                   fatigue_check = #{fatigueCheck},
                   heart_disease = #{heartDisease},
                   liver_disease = #{liverDisease},
                   `operation` = #{operation},
                   operation_content = #{operationContent},
                   allergy_check = #{allergyCheck},
                   kidney_disease =   #{kidneyDisease},
                   cancer_check = #{cancerCheck},
                   cancer_name = #{cancerName},
                   etc_check =   #{etcCheck},
                   etc_content=#{etcContent}
             WHERE patient_idx = #{patientIdx}
        ]]>
    </update>
    
    <update id="updatePatientSymptom" parameterType="PatientDTO" useGeneratedKeys="true">
        <![CDATA[
            UPDATE patient_symptom
               SET fever_check = #{feverCheck},
                   cough_check = #{coughCheck},
                   colic = #{colic},
                   cold_fit_check = #{coldFitCheck},
                   sputum_check = #{sputumCheck},
                   ocin_check = #{ocinCheck},
                   fever_right = #{feverRight},
                   fever_left = #{feverLeft},
                   fatigue_check = #{fatigueCheck},
                   etc_check = #{etcCheck},
                   etc_content = #{etcContent},
                   chest_pain = #{chestPain},
                   nose_check = #{noseCheck},
                   vomiting_check = #{vomitingCheck},
                   muscle_pain_check = #{musclePainCheck},
                   sore_throat_check = #{soreThroatCheck},
                   diarrhea_check = #{diarrheaCheck},
                   headache_check = #{headacheCheck},
                   dyspnea_check = #{dyspneaCheck},
                   pulse_rate = #{pulseRate},
                   respiration_rate = #{respirationRate},
                   blood_pressure_level = #{bloodPressureLevel},
                   oxygen_saturation = #{oxygenSaturation}
             WHERE patient_idx = #{patientIdx}
        ]]>
    </update>
</mapper>