package thyyxxk.webserver.dao.his.zhuyuanyisheng.emr;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import thyyxxk.webserver.entity.datamodify.YzTemperature;
import thyyxxk.webserver.entity.fluorescenceTest.FluorescenceSpecimenResult;
import thyyxxk.webserver.entity.medicalinsurance.inpatient.ZyPatientInfo;
import thyyxxk.webserver.entity.outpatient.thmz.MzEmrPatientData;
import thyyxxk.webserver.entity.zhuyuanyisheng.ZyZkList;
import thyyxxk.webserver.entity.zhuyuanyisheng.emr.*;
import thyyxxk.webserver.entity.zhuyuanyisheng.jianyanjiancha.YshYjReq;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.OpRecord;

import java.util.List;
import java.util.Map;

@Mapper
public interface EmrPatientDao extends BaseMapper<EmrPatientData> {

    @Select("select id, " +
            "       pat_no, " +
            "       times, " +
            "       emr_document_id, " +
            "       emr_category_code, " +
            "       del_flag, " +
            "       emr_name, " +
            "       create_id," +
            "       create_name = (select rtrim(name) from a_employee_mi where code = create_id), " +
            "       create_date, " +
            "       modify_id, " +
            "       modify_date, " +
            "       name," +
            "       submit," +
            "       parent " +
            "from emr_patient_data " +
            "where pat_no = #{patNo} " +
            "  and times = #{times}" +
            "  and del_flag = 0 " +
            "  order by id ")
    List<EmrPatientData> getPatientData(@Param("patNo") String patNo,
                                        @Param("times") Integer times);


    @Select("select id " +
            "from emr_patient_data " +
            "where  emr_document_id = #{docmentId} ")
    Integer whetherThereIsAMedicalRecord(@Param("docmentId") String docmentId);

    @Insert("insert into emr_patient_data (pat_no, times, emr_document_id," +
            " emr_category_code, emr_name,create_id,name,parent,refer_physician,consult_physician,dept_director , " +
            " emr_data_element) " +
            "values (#{patNo},#{times},#{emrDocumentId}," +
            "#{emrCategoryCode},#{emrName},#{createId},#{name},#{parent},#{referPhysician},#{consultPhysician},#{deptDirector}, " +
            "#{emrDataElementStr})")
    void emrInsertForTheFirstTime(EmrPatientData param);

    @Delete("delete emr_progress_note where document_id = #{documentId} ")
    void delOldFragment(Integer documentId);

    @Insert("<script>" +
            "insert into emr_progress_note " +
            "(document_id, name, create_id, creation_time," +
            " refer_physician, consult_physician, dept_director) " +
            "values" +
            "<foreach collection='list' item='item' separator=','>" +
            " (#{documentId}, #{item.name},#{item.createId},#{item.creationTime}," +
            "#{item.referPhysician},#{item.consultPhysician},#{item.deptDirector})" +
            "</foreach>" +
            "</script>")
    void insertFragment(@Param("list") List<EmrProgressNote> list,
                        @Param("documentId") Integer documentId);

    @Update("update emr_patient_data " +
            "set name    = #{name}, " +
            "    modify_date = getdate() , " +
            "    modify_id   = #{createId} , " +
            "    emr_data_element = #{emrDataElementStr} " +
            "where pat_no = #{patNo} " +
            "  and times = #{times} " +
            "  and emr_document_id = #{emrDocumentId} ")
    void updateCreatedTemplate(EmrPatientData param);

    @Select("select * from emr_patient_data where emr_document_id = #{id} ")
    EmrPatientData getCategoryCodeByDocumentId(String id);

    @Update("update emr_patient_data " +
            "set del_flag = 1," +
            "    modify_id = #{userCode}," +
            "    modify_date = getdate() " +
            "where emr_document_id = #{documentId}")
    void deletePatientEmrByDocumentId(@Param("documentId") String documentId,
                                      @Param("userCode") String userCode);


    @Select("select count(1) " +
            "from emr_patient_data " +
            "where pat_no = #{patNo} " +
            "  and times = #{times} " +
            "  and del_flag = 0 " +
            "  and emr_category_code = #{emrCategoryCode} ")
    Integer queryWhetherThePatientHasASpecifiedMedicalRecord(@Param("patNo") String patNo,
                                                             @Param("times") Integer times,
                                                             @Param("emrCategoryCode") String emrCategoryCode);

    @Select("select * " +
            "from emr_data_extract " +
            "where emr_category_code = #{code} ")
    EmrDataExtract extractDataSource(String code);

    @Select("select pat_no,times,data_element from emr_data_element where pat_no = #{patNo} and times = #{times}")
    EmrDataElement obtainPatientSOriginalData(@Param("patNo") String patNo,
                                              @Param("times") Integer times);

    @Insert("insert into emr_data_element (pat_no, times, data_element) " +
            "values (#{patNo},#{times},#{dataElement});")
    void insertDataSource(@Param("patNo") String patNo,
                          @Param("times") Integer times,
                          @Param("dataElement") String dataElement);

    @Update("update emr_data_element set data_element = #{dataElement} where " +
            "pat_no = #{patNo} and times = #{times}")
    void updatePatientDataSource(@Param("patNo") String patNo,
                                 @Param("times") Integer times,
                                 @Param("dataElement") String dataElement);

    @Select("select count(1) from hot_search_sorting where user_code = #{userCode} and code = #{code} and table_name = #{tableName}")
    Integer queryWhetherThereIsHotSearch(@Param("userCode") String userCode,
                                         @Param("code") String code,
                                         @Param("tableName") String tableName);

    @Insert("insert into hot_search_sorting (user_code, code, table_name, count) values (#{userCode}, #{code}, #{tableName}, 1)")
    void hotSearchSorting(@Param("userCode") String userCode,
                          @Param("code") String code,
                          @Param("tableName") String tableName);

    @Update("update hot_search_sorting set count = count + 1 where user_code = #{userCode} and code = #{code} and table_name = #{tableName}")
    void updateHotSearch(@Param("userCode") String userCode,
                         @Param("code") String code,
                         @Param("tableName") String tableName);

    @Select("select create_id from emr_patient_data where emr_document_id = #{id}")
    String getDocumentIdCreatedBy(String id);

    @Update("update emr_patient_data set submit = 1,submit_id = #{userCode},submit_time = getdate() where emr_document_id = #{id}")
    void updateSubmissionFlag(String id, String userCode);

    @Update("update emr_patient_data set review_doctors = #{userCode}, review_time = getdate() where emr_document_id = #{id} and review_time is null")
    int updateAuditByDocumentId(String id, String userCode);

    @Select("select emr_document_id from emr_patient_data where pat_no = #{patNo} and times = #{times} and emr_category_code = #{categoryCode} and del_flag = 0")
    List<String> getDocumentIdByPatietn(String patNo, int times, String categoryCode);

    @Select("select data_element from emr_data_element where pat_no = #{patNo} and times = #{times} ")
    String getEmrPatientData(@Param("patNo") String patNo, @Param("times") int times);


    @Select("select top 1 rtrim(a.name)                                                                                          as xm, " +
            "       dis_date                                                                                               as cysj, " +
            "       a.sex                                                                                                  as xb, " +
            "       (select DATEDIFF(yy, birth_date, GETDATE()) from a_patient_mi b where b.inpatient_no = a.inpatient_no) as nl, " +
            "       (select sum(charge_fee) " +
            "        from zy_detail_charge " +
            "        where zy_detail_charge.inpatient_no = a.inpatient_no " +
            "          and zy_detail_charge.admiss_times = a.admiss_times " +
            "          and ledger_sn = #{ledgerSn})                                                                                  as zfy, " +
            "       datediff(day, admiss_date, isnull(dis_date, getdate()))                                                as sjzyts, " +
            "       condition_code                                                                                         as rybq, " +
            "       route_of_admission                                                                                     as rytj, " +
            "       ''                                                                                                     as lyfs, " +
            "       (select insutype " +
            "        from t_si_setlinfo " +
            "        where a.inpatient_no = pat_no " +
            "          and admiss_times = times)                                                                           as insur_type_id, " +
            "       ''                                                                                                     as xsecstz, " +
            "       ''                                                                                                     as xserytz, " +
            "       ''                                                                                                     as bzyzsnl " +
            "from zy_actpatient a, " +
            "     a_patient_mi b left join mz_zy_req c on (b.mz_no = c.patient_id) " +
            "where a.inpatient_no = #{patNo} " +
            "  and admiss_times = #{times} " +
            "  and a.inpatient_no = b.inpatient_no " +
            "order by confirm_date desc")
    Map<String, String> drgPatientInfo(String patNo, int times, int ledgerSn);


    @Select("select max(admiss_times) " +
            "from zy_inactpatient " +
            "where inpatient_no = #{patNo} ")
    Integer getMaxTimes(String patNo);


    @Select("select data_element from emr_data_element where pat_no = #{patNo} and times = #{times}")
    Map<String, String> selectEmrDataElement(String patNo, Integer times);

    @Select("select admiss_times from zy_actpatient where inpatient_no = #{patNo} ")
    Integer getAdmissTimes(String patNo);

    @Select("<script>" +
            "select id, " +
            "       pat_no, " +
            "       times, " +
            "       emr_document_id, " +
            "       emr_category_code, " +
            "       del_flag, " +
            "       emr_name, " +
            "       name, " +
            "       create_id," +
            "       create_name = (select name from a_employee_mi where a_employee_mi.code = create_id), " +
            "       create_date, " +
            "       modify_id, " +
            "       modify_date, " +
            "       submit " +
            "from emr_patient_data " +
            "where pat_no = #{patNo} " +
            "  and times = #{times} " +
            "<if test=\"createId != null and createId != '' \">  " +
            "  and create_id = #{createId} " +
            "</if>" +
            "  and del_flag = 1" +
            "</script>")
    List<EmrPatientData> selectEmrDeteles(String patNo, Integer times, String createId);

    @Select("select id, " +
            "       pat_no, " +
            "       times, " +
            "       emr_document_id, " +
            "       emr_category_code, " +
            "       del_flag, " +
            "       emr_name, " +
            "       name, " +
            "       create_id, " +
            "       create_date, " +
            "       modify_id, " +
            "       modify_date, " +
            "       submit " +
            "from emr_patient_data " +
            "where emr_document_id = #{documentId} ")
    EmrPatientData selectemPatientDataOne(String documentId);

    @Update("update emr_patient_data " +
            "set del_flag = 0 " +
            "where id = #{id} ")
    void updateDeleteFlag(Integer id);


    @Select("select pat_no, req_remarks, req_status, req_id, edit_date, review_notes  " +
            "from discharged_emr_modify_apply ${ew.customSqlSegment} ")
    List<DischargedEmrModifyApply> getDisReqEmr(@Param(Constants.WRAPPER) QueryWrapper<?> queryWrapper);

    @Select("select pat_no, req_remarks, req_status, req_id,reqName = (select rtrim(name) from a_employee_mi where code = req_id)," +
            " edit_date, review_notes,creation_time " +
            "from discharged_emr_modify_apply where creation_time >= #{start} and  creation_time <= #{end}")
    List<DischargedEmrModifyApply> selectDisReqEmyDownload(String start, String end);

    @Delete("delete discharged_emr_modify_apply where pat_no = #{patNo} ")
    int deleteRequest(String patNo);

    @Insert("insert into discharged_emr_modify_apply (pat_no, req_remarks, req_id, edit_date) " +
            "values (#{dis.patNo},#{dis.reqRemarks},#{dis.reqId},#{dis.editDate})")
    void insertApplicationEmrDis(@Param("dis") DischargedEmrModifyApply dis);

    @Update("update discharged_emr_modify_apply " +
            "set req_status   = #{status}, " +
            "    review_notes = #{reviewNotes} " +
            "where pat_no = #{patNo} ")
    int adoptEmrDisReq(String patNo,
                       String reviewNotes,
                       int status);

    @Select("select id, creator_id, creator_data, content, dept, type_code,query_key " +
            "from medical_history_prompts where creator_id = #{id} ")
    List<MedicalHistoryPrompts> selectEmrTips(String id);


    @Insert("insert into medical_history_prompts (creator_id, content, dept, type_code, query_key) " +
            "values (#{creatorId},#{content},#{dept},#{typeCode},#{queryKey})")
    void insertEmrTips(MedicalHistoryPrompts param);

    @Update("update medical_history_prompts " +
            "set content   = #{content}, " +
            "    type_code = #{typeCode}, " +
            "    query_key = #{queryKey} " +
            "where id = #{id} ")
    void updateEmrTips(MedicalHistoryPrompts param);

    @Delete("delete medical_history_prompts where id = #{id} ")
    void delEmrTips(Integer id);

    @Select("select id, " +
            "       creator_id, " +
            "       creator_data, " +
            "       content, " +
            "       dept, " +
            "       type_code, " +
            "       query_key, " +
            "       user_code, " +
            "       code, " +
            "       table_name, " +
            "       count " +
            "from medical_history_prompts a " +
            "         left join hot_search_sorting b on (a.query_key = b.code and b.table_name = 'medical_history_prompts' and a.creator_id = b.user_code) " +
            " ${ew.customSqlSegment} ")
    List<MedicalHistoryPrompts> getEmrTipsData(@Param(Constants.WRAPPER) QueryWrapper<?> queryWrapper);


    @Select("select bed_no, " +
            "       admiss_times," +
            "       rtrim(inpatient_no) as inpatient_no, " +
            "       name, " +
            "       admiss_date, " +
            "       dis_date, " +
            "       zk_ward      = (select rtrim(name) from zd_unit_code where code = zk_ward), " +
            "       admiss  = (select rtrim(name) from zd_unit_code where code = admiss_ward), " +
            "       dis_ward    = (select rtrim(name) from zd_unit_code where code = dis_ward) " +
            "from zy_inactpatient where inpatient_no = #{patNo} ")
    List<ZyPatientInfo> getListOfDischargedPatients(String patNo);


    @Select("select patientName=(select rtrim(name) name " +
            "                    from a_patient_mi " +
            "                    where a_patient_mi.inpatient_no = yz_temperature.inpatient_no), " +
            "       inpatient_no, " +
            "       temp_date  = (convert(varchar(10), rec_date, 23) + ' ' + convert(varchar(10), rec_time, 24))," +
            "       rec_date_str = (convert(varchar(10), rec_date, 23))," +
            "       rec_time_str = (convert(varchar(5), rec_time, 24)), " +
            "       temperature_1," +
            "       temperature_1_type,col_1_name,col_1_am,col_2_name,col_2_am,urine_color,urine_quan_color,shit_shape," +
            "       patient_state, " +
            "       pulse_1, " +
            "       breathe_1, " +
            "       pressure_1_am, " +
            "       pressure_1_pm," +
            "       spo2, " +
            "       mind, " +
            "       skin, " +
            "       tubes_name, " +
            "       tubes_status, " +
            "       rtrim(other_info) other_info, " +
            "       ward, " +
            "       admiss_times, " +
            "       detail_no, " +
            "       userid=(select rtrim(name) name from a_employee_mi where code = userid)," +
            "       GLU as glu," +
            "       heart " +
            "from yz_temperature " +
            " ${ew.customSqlSegment} " +
            "order by temp_date ")
    List<YzTemperature> getYzTemperature(@Param(Constants.WRAPPER) QueryWrapper<?> queryWrapper);

    @Select("select order_name, req_no, act_order_no, start_time, inpatient_no, admiss_times, receive_flag,RTRIM(order_type) AS order_type " +
            "from ysh_yj_req with (NOLOCK) " +
            "where inpatient_no = #{patNo} " +
            "  and admiss_times = #{times} " +
            "  and req_type = '3'" +
            "  order by act_order_no desc ")
    List<YshYjReq> getExamine(String patNo,
                              Integer times);

    @Select("select top 1 op_time,f_dept_code " +
            "from zy_zk_list " +
            "where inpatient_no = #{patNo} " +
            "  and admiss_times = #{times} " +
            "order by op_time desc")
    ZyZkList getMaxTransferDateByPatNo(String patNo,
                                       Integer times);

    @Update("update emr_patient_data " +
            "set parent = #{parent} " +
            "where id = #{id} ")
    void updateTheNode(String parent, Integer id);


    @Select("select * from emr_patient_data")
    List<EmrPatientData> 查询历史数据();

    @Select("select id, " +
            "       pat_no, " +
            "       times, " +
            "       emr_document_id, " +
            "       emr_category_code, " +
            "       del_flag, " +
            "       emr_name, " +
            "       name, " +
            "       create_id, " +
            "       create_date, " +
            "       modify_id, " +
            "       modify_date, " +
            "       submit, " +
            "       parent, " +
            "       sort, " +
            "       refer_physician, " +
            "       consult_physician, " +
            "       dept_director, " +
            "       submit_id, " +
            "       review_doctors, " +
            "       review_time, " +
            "       submit_time " +
            "from emr_patient_data " +
            "where pat_no = #{patNo} " +
            "  and times <> #{times} " +
            "  and del_flag = 0 ")
    List<EmrPatientData> getHisPatInfo(String patNo, Integer times);


    @Select("select id, " +
            "       hospital_name, " +
            "       sample, " +
            "       specimen, " +
            "       patient_name, " +
            "       patient_age, " +
            "       diagnosis, " +
            "       office, " +
            "       doctor, " +
            "       send_time, " +
            "       proofer, " +
            "       test_time, " +
            "       reporter, " +
            "       report_time, " +
            "       bed_no, " +
            "       outcome, " +
            "       pat_no, " +
            "       times " +
            "from fluorescence_specimen_result where pat_no = #{patNo} and times = #{times} ")
    List<FluorescenceSpecimenResult> selectFluorescenceSpecimenResult(String patNo,
                                                                      Integer times);


    @Select("select a.record_id, " +
            "       a.zy_serial_no, " +
            "       a.op_times, " +
            "       patient_name, " +
            "       dept_code, " +
            "       ward_code, " +
            "       apply_date, " +
            "       apply_user, " +
            "       apply_doc, " +
            "       schedule_date, " +
            "       schedule_user, " +
            "       status, " +
            "       patient_type, " +
            "       act_order_no, " +
            "       op_code, " +
            "       op_name, " +
            "       op_datetime, " +
            "       room_code, " +
            "       op_group_code, " +
            "       hocus_code, " +
            "       hocus_name        = (select rtrim(name) from zd_anaesthesia where zd_anaesthesia.code = hocus_code), " +
            "       diag_before_op, " +
            "       diag_after_op, " +
            "       infection_flag, " +
            "       urgent_clinic_flag, " +
            "       avocation_flag, " +
            "       blood_amount, " +
            "       blood_type, " +
            "       op_stastics_id, " +
            "       isolation_indicator, " +
            "       op_scale, " +
            "       op_endtime, " +
            "       diag_before_code, " +
            "       diag_after_code, " +
            "       hbsag, " +
            "       body_code, " +
            "       part_code, " +
            "       specialreq_code, " +
            "       instrument_code, " +
            "       aspesis_scale, " +
            "       remark, " +
            "       op_dept, " +
            "       input_id, " +
            "       input_date, " +
            "       req_id, " +
            "       req_date, " +
            "       last_modify_id, " +
            "       arrange_id, " +
            "       arrange_date, " +
            "       inpatient_no, " +
            "       admiss_times, " +
            "       cancel_id, " +
            "       cancel_time, " +
            "       sstc, " +
            "       bed_no, " +
            "       tw_flag, " +
            "       ssbc, " +
            "       ssyz_flag, " +
            "       status_flag, " +
            "       ward_dept, " +
            "       op_start_date, " +
            "       op_end_date, " +
            "       anst_start_date, " +
            "       anst_end_date, " +
            "       arrangement_executed, " +
            "       preoperative_visit, " +
            "       preoperative_preparation, " +
            "       doctor_zd, " +
            "       doctor_zd_name    = (select rtrim(name) from a_employee_mi where code = doctor_zd), " +
            "       doctor_wp, " +
            "       doctor_1, " +
            "       doctor_1_name     = (select rtrim(name) from a_employee_mi where code = doctor_1), " +
            "       doctor_2, " +
            "       doctor_2_name     = (select rtrim(name) from a_employee_mi where code = doctor_2), " +
            "       doctor_3, " +
            "       doctor_3_name     = (select rtrim(name) from a_employee_mi where code = doctor_3), " +
            "       doctor_mz, " +
            "       nurse_xh, " +
            "       nurse_xh_name     = (select rtrim(name) from a_employee_mi where code = nurse_xh), " +
            "       nurse_qx, " +
            "       nurse_qx_name     = (select rtrim(name) from a_employee_mi where code = nurse_qx), " +
            "       doctor_mz_hs, " +
            "       doctor_mz_ys, " +
            "       doctor_mz_ys_name = (select rtrim(name) from a_employee_mi where code = doctor_mz_ys), " +
            "       nurse_qx_name     = (select rtrim(name) from a_employee_mi where code = nurse_qx), " +
            "       doctor_zd_sj " +
            "from op_record a " +
            "         left join op_record_join b on (a.record_id = b.record_id) " +
            "where inpatient_no = #{patNo} " +
            "  and admiss_times = #{times}")
    List<OpRecord> getOpRecordList(String patNo, Integer times);

    @Select(" select *  from emr_patient_data where pat_no=#{patNo} and del_flag=0")
    List<MzEmrPatientData> selectDataByPatNo(String patNo);

    @Select("select mz_no from a_patient_mi where inpatient_no = #{patNo}")
    String getMzNoByPatNo(String patNo);

    @Select("select emr_document_id, emr_name,times, pat_no,name " +
            "from mz_emr_patient_data " +
            "where pat_no = #{mzNo} ")
    List<MzEmrPatientData> getEmrPatientMz(String mzNo);

    @Delete("delete emr_patient_data\n" +
            "where emr_document_id = #{id}\n" +
            "  and create_id = #{code}  and emr_category_code = 'This is Dir'")
    int delDir(String id, String code);

    @Update("update emr_patient_data\n" +
            "set emr_name = #{name},\n" +
            "    name     = #{name}\n" +
            "where emr_document_id = #{id}")
    int rename(String name, String id);

    default boolean dirHasFile(String id) {
        EmrPatientData data = this.selectById(id);
        if (data == null) return false;
        LambdaQueryWrapper<EmrPatientData> qw = EmrPatientData
                .lambdaQueryWrapper()
                .eq(EmrPatientData::getPatNo, data.getPatNo())
                .eq(EmrPatientData::getTimes, data.getTimes())
                .eq(EmrPatientData::getParent, id)
                .eq(EmrPatientData::getDelFlag, 0);

        return this.selectCount(qw) > 0;
    }


    @Select("select top 1 emr_data_element\n" +
            "from emr_patient_data\n" +
            "where emr_category_code = 'ruyuanjiluzhuanyong' and pat_no = #{patNo} and times = #{times} " +
            "order by create_date desc")
    String obtainAdmissionDiagnosis(String patNo, Integer times);


    @Select("select top 1 emr_data_element\n" +
            "from emr_patient_data\n" +
            "where emr_category_code = '${code}' and pat_no = #{patNo} and times = #{times} " +
            "order by create_date desc")
    String findEmrByCode(String patNo, Integer times, String code);

}
