package thyyxxk.webserver.dao.his.inpatient.casefrontsheet;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;
import thyyxxk.webserver.entity.casefrontsheet.*;
import thyyxxk.webserver.entity.casefrontsheet.request.*;
import thyyxxk.webserver.entity.casefrontsheet.response.LendOutSheet;
import thyyxxk.webserver.entity.casefrontsheet.state.AuditState;
import thyyxxk.webserver.entity.covid.Region;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.dictionary.HisWjwMatchEntity;

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

/**
 * @author dj
 */
@Mapper
public interface CaseFrontSheetDao extends BaseMapper<CaseFrontsheetMain> {
    @Select("select count(1) from zy_actpatient where inpatient_no=#{bah} and admiss_times=#{times}")
    int selectActCount(String bah, int times);

    @Select("select bedNo=rtrim(bed_no),bah=rtrim(inpatient_no),times=rtrim(admiss_times),name=rtrim(name),sex," +
            "file_status,doctorCode=rtrim(refer_physician)," +
            "doctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=refer_physician), " +
            "admiss_date from zy_actpatient with(nolock) where charindex('$',inpatient_no)=0 and " +
            "(small_dept=#{ward} or ward=#{ward} or zk_ward=#{ward} or zk_dept=#{ward}) " +
            "ORDER BY cast(bed_no AS int)")
    List<SheetOverview> getPatientOverview(String ward);

    @Select("select bedNo=rtrim(bed_no),bah=rtrim(inpatient_no),times=rtrim(admiss_times),name=rtrim(name),sex," +
            "file_status,doctorCode=rtrim(refer_physician)," +
            "doctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=refer_physician) " +
            "from zy_inactpatient with(nolock) where dis_date>=#{start} and dis_date<=#{end} and " +
            "(small_dept=#{ward} or ward=#{ward} or zk_ward=#{ward} or zk_dept=#{ward}) and " +
            "charindex('$',inpatient_no)=0 ORDER BY cast(bed_no AS int)")
    List<SheetOverview> getOutPatients(DismissedSheetInquiry param);

    @Select("select healthCardNo=rtrim(health_card_no),bah=rtrim(inpatient_no),name=rtrim(name),sex=rtrim(sex), " +
            "birthDate=birth_date,country=rtrim(country),birthPlace=rtrim(birth_place),nation=rtrim(nation_code), " +
            "birthPlaceName=(select rtrim(name) from zd_district_code with(nolock) where code=birth_place), " +
            "socialNo=rtrim(social_no),occupation=rtrim(occupation_code),marriage=rtrim(marry_code), " +
            "livePlace=rtrim(home_street),phone=rtrim(home_tel),addrZipCode=rtrim(home_zipcode),hkZipCode=rtrim(account_zipcode), " +
            "unitName=rtrim(employer_name),unitPlace=rtrim(employer_street),unitPhone=rtrim(employer_tel), " +
            "unitZipCode=rtrim(employer_zipcode),contactName=rtrim(relation_name),contactRelation=rtrim(relation_code), " +
            "contactPhone=(rtrim(relation_tel)) from a_patient_mi with(nolock) where inpatient_no=#{bah}")
    CaseFrontsheetMain getAPatientMi(String bah);

    @Select("select top 1 serial_no from t_injury_si_pat_info with(nolock) where pat_no=#{patNo} and times=#{times} order by ledger_sn desc")
    String selectInjurySerialNo(String patNo, int times);

    @Select("select count(1) from view_zy_patient_all where inpatient_no = #{bah} and admiss_times = #{times}")
    int getInfant(String bah, int times);

    @Select("select max(start_time) from ${table} with(nolock) where inpatient_no=#{bah} " +
            "and admiss_times=#{times} and status_flag > '1' and isnull (group_no,'00')='00' " +
            "and order_code in " +
            "(select order_code from yz_zd_order_item_confirm where item_name in (N'出院',N'死亡'))")
    Date getDismissDateFromYzActOrder(String table, String bah, int times);

    @Select("select " +
            "admissTimes=#{times}, " +
            "rtrim(zk_ward) as transDeptCode," +
            "transDept=(select rtrim(name) from zd_unit_code with(nolock) where code=zk_ward)," +
            "rtrim(zk_ward) as dismissDeptCode," +
            "dismissDept=(select rtrim(name) from zd_unit_code with(nolock) where code=isnull(zk_ward,small_dept))," +
            "dismissWardCode=ward,admiss_date, " +
            "dismissWard=(select rtrim(name) from zd_unit_code with(nolock) where code=ward)," +
            "medType=(select top 1 med_type from t_si_pat_info with(nolock) where pat_no=#{bah} and times=#{times} order by ledger_sn desc), " +
            "insutype=(select top 1 insutype from t_si_pat_info with(nolock) where pat_no=#{bah} and times=#{times} order by ledger_sn desc), " +
            "dismissDate=(select max(start_time) from ${yzTable} with(nolock) where inpatient_no=#{bah} " +
            "and admiss_times=#{times} and status_flag > '1' and isnull (group_no,'00')='00' " +
            "and order_code in (select order_code from yz_zd_order_item_confirm where item_name in (N'出院',N'死亡'))), " +
            "rtrim(small_dept) as admissDeptCode, " +
            "admissDept=(select rtrim(name) from zd_unit_code with(nolock) where code=small_dept), " +
            "rtrim(admiss_ward) as admissWardCode, " +
            "admissWard=(select rtrim(name) from zd_unit_code with(nolock) where code=admiss_ward), " +
            "clinicDiagStr=rtrim(clinic_diag_str), " +
            "clinicDiagCode=rtrim(clinic_diag), " +
            "validClinicDiag=(select count(1) from zd_icd_code_new where yb_code=clinic_diag), " +
            "totalCost=total_charge, " +
            "selfPay=(select sum(last_balance) from zy_ledger_file with(nolock) " +
            "where inpatient_no=#{bah} and admiss_times=#{times} and ledger_sn>0)," +
            "autopsy=rtrim(autopsy_mark)," +
            "hasSurgery=rtrim(operation)," +
            "diagConform1=rtrim(diagnose_conform1)," +
            "diagConform2=rtrim(diagnose_conform2)," +
            "diagConform3=rtrim(diagnose_conform3)," +
            "diagConform4=rtrim(diagnose_conform4)," +
            "diagConform5=rtrim(diagnose_conform5)," +
            "pathologicDiagStr=rtrim(pathology_diag_comment)," +
            "pathologicDiagCode=rtrim(pathology_diag)," +
            "lendFlag=isnull(lend_flag, 0), " +
            "fileStatus=isnull(file_status, 0) " +
            "from ${table} with(nolock) where inpatient_no=#{bah} and admiss_times=#{times}")
    CaseFrontsheetMain getZyActPatient(String table, String yzTable, String bah, int times);


    @Select("select payMethod=rtrim(pay_method),ageDays=rtrim(age_days),newBornWeight=rtrim(new_born_weight)," +
            "newBornAdmissWeight=rtrim(new_born_admiss_weight),zyAdmissWay=rtrim(rytj),nativePlace=rtrim(jg)," +
            "nativePlaceName=(select rtrim(name) from zd_district_code with(nolock) where code=jg)," +
            "hkPlace=rtrim(hkdz),hkPlaceName=rtrim(hkdz2),contactAddr=rtrim(lxdz),contactAddrName=rtrim(lxdz2)," +
            "hkZipCode=rtrim(hkyb) from batj_ba1 with(nolock) where bah=#{bah} and zycs=#{times}")
    CaseFrontsheetMain getBatjBa1(String bah, int times);

    @Select("select " +
            "blh=rtrim(a.blzd_qph)," +
            "allergy=rtrim(a.gm_flag)," +
            "allergicMedicine=rtrim(a.gmwy)," +
            "hbsAg=rtrim(a.hbsag)," +
            "hcvAb=rtrim(a.hcv_vb)," +
            "hivAb=rtrim(a.hiv_vb)," +
            "tpAb=rtrim(a.tp_ab)," +
            "bloodType=rtrim(a.xx)," +
            "rh=rtrim(a.xx_rh)," +
            "deptLeader=rtrim(isnull(kzr, b.dept_director))," +
            "deptLeaderName=(select rtrim(name) from a_employee_mi with(nolock) where code=(isnull(kzr, b.dept_director)))," +
            "leaderDoctor=rtrim(isnull(zrys, b.dept_director))," +
            "leaderDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=(isnull(zrys, b.dept_director)))," +
            "mainDoctor=rtrim(isnull(zzys, b.consult_physician))," +
            "mainDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=(isnull(zzys, b.consult_physician)))," +
            "admissDoctor=rtrim(isnull(zyys, b.refer_physician))," +
            "admissDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=isnull(zyys, b.refer_physician))," +
            "dutyNurse=rtrim(a.job_nurse)," +
            "dutyNurseName=(select rtrim(name) from a_employee_mi with(nolock) where code=a.job_nurse)," +
            "studyDoctor=rtrim(a.jxys)," +
            "studyDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=jxys)," +
            "internshipDoctor=rtrim(a.sxys)," +
            "internshipDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=sxys)," +
            "coder=rtrim(a.bmy)," +
            "coderName=(select rtrim(name) from a_employee_mi with(nolock) where code=bmy)," +
            "qualityControlLevel=rtrim(a.bazl)," +
            "qualityControlDoctor=rtrim(a.zkys)," +
            "qualityControlDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=zkys)," +
            "qualityControlNurse=rtrim(a.zkhs)," +
            "qualityControlNurseName=(select rtrim(name) from a_employee_mi with(nolock) where code=zkhs)," +
            "qualityControlDate=a.barq," +
            "zyDismissWay=rtrim(a.lyfs)," +
            "dismissDestination=rtrim(a.jsjg)," +
            "admissAgainInOneMonth=rtrim(a.zzy_flag)," +
            "admissAgainPurpose=rtrim(a.zzy_md)," +
            "comaDaysBeforeAdmiss=rtrim(a.ryq_hmsj_day)," +
            "comaHoursBeforeAdmiss=rtrim(a.ryq_hmsj_hour)," +
            "comaMinutesBeforeAdmiss=rtrim(a.ryq_hmsj_min)," +
            "comaDaysAfterAdmiss=rtrim(a.ryh_hmsj_day)," +
            "comaHoursAfterAdmiss=rtrim(a.ryh_hmsj_hour)," +
            "comaMinutesAfterAdmiss=rtrim(a.ryh_hmsj_min)," +
            "rescueTimes=rtrim(a.qjcs)," +
            "rescueSuccessTimes=rtrim(a.cgcs)," +
            "caseClassification=rtrim(a.blfx)," +
            "hasIcu=rtrim(a.zzjh)," +
            "icuDays=rtrim(a.zzjh_day)," +
            "icuHours=rtrim(a.zzjh_hour)," +
            "monopathyManagement=rtrim(a.dbz)," +
            "clinicalPathwayManagement=rtrim(a.lclj)," +
            "drgsManagement=rtrim(a.drgs)," +
            "useAntibiotic=rtrim(a.kss)," +
            "bacilliculture=rtrim(a.xjpy)," +
            "statutoryEpidemic=rtrim(a.fdcrb)," +
            "hurtReasonName=rtrim(a.hurt_reason_name)," +
            "hurtReasonCode=rtrim(a.hurt_reason_code)," +
            "tumorLevelT=rtrim(a.tumor_level_t)," +
            "tumorLevelN=rtrim(a.tumor_level_n)," +
            "tumorLevelM=rtrim(a.tumor_level_m)," +
            "a.tumor_level,a.fyzlyyy," +
            "xxeApgar=rtrim(a.apgar) " +
            "from batj_ba2 a with(nolock), zy_actpatient b with(nolock) where " +
            "b.inpatient_no=a.bah and " +
            "a.bah=#{bah} and a.zycs=#{times}")
    CaseFrontsheetMain getBatjBa2ForInPatient(String bah, int times);

    @Select("select " +
            "lateFlag=(select late_flag from t_case_frontsheet_main t where t.bah=#{bah} and t.admiss_times=#{times}), " +
            "fileStatus=(select file_status from t_case_frontsheet_main t where t.bah=#{bah} and t.admiss_times=#{times}), " +
            "signDate=(select sign_date from t_case_frontsheet_main t where t.bah=#{bah} and t.admiss_times=#{times}), " +
            "blh=rtrim(a.blzd_qph)," +
            "allergy=rtrim(a.gm_flag)," +
            "allergicMedicine=rtrim(a.gmwy)," +
            "hbsAg=rtrim(a.hbsag)," +
            "hcvAb=rtrim(a.hcv_vb)," +
            "hivAb=rtrim(a.hiv_vb)," +
            "tpAb=rtrim(a.tp_ab)," +
            "bloodType=rtrim(a.xx)," +
            "rh=rtrim(a.xx_rh)," +
            "deptLeader=rtrim(isnull(kzr, b.dept_director))," +
            "deptLeaderName=(select rtrim(name) from a_employee_mi with(nolock) where code=(isnull(kzr, b.dept_director)))," +
            "leaderDoctor=rtrim(isnull(zrys, b.dept_director))," +
            "leaderDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=(isnull(zrys, b.dept_director)))," +
            "mainDoctor=rtrim(isnull(zzys, b.consult_physician))," +
            "mainDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=(isnull(zzys, b.consult_physician)))," +
            "admissDoctor=rtrim(isnull(zyys, b.refer_physician))," +
            "admissDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=isnull(zyys, b.refer_physician))," +
            "dutyNurse=rtrim(a.job_nurse)," +
            "dutyNurseName=(select rtrim(name) from a_employee_mi with(nolock) where code=a.job_nurse)," +
            "studyDoctor=rtrim(a.jxys)," +
            "studyDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=jxys)," +
            "internshipDoctor=rtrim(a.sxys)," +
            "internshipDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=sxys)," +
            "coder=rtrim(a.bmy)," +
            "coderName=(select rtrim(name) from a_employee_mi with(nolock) where code=bmy)," +
            "qualityControlLevel=rtrim(a.bazl)," +
            "qualityControlDoctor=rtrim(a.zkys)," +
            "qualityControlDoctorName=(select rtrim(name) from a_employee_mi with(nolock) where code=zkys)," +
            "qualityControlNurse=rtrim(a.zkhs)," +
            "qualityControlNurseName=(select rtrim(name) from a_employee_mi with(nolock) where code=zkhs)," +
            "qualityControlDate=a.barq," +
            "zyDismissWay=rtrim(a.lyfs)," +
            "dismissDestination=rtrim(a.jsjg)," +
            "admissAgainInOneMonth=rtrim(a.zzy_flag)," +
            "admissAgainPurpose=rtrim(a.zzy_md)," +
            "comaDaysBeforeAdmiss=rtrim(a.ryq_hmsj_day)," +
            "comaHoursBeforeAdmiss=rtrim(a.ryq_hmsj_hour)," +
            "comaMinutesBeforeAdmiss=rtrim(a.ryq_hmsj_min)," +
            "comaDaysAfterAdmiss=rtrim(a.ryh_hmsj_day)," +
            "comaHoursAfterAdmiss=rtrim(a.ryh_hmsj_hour)," +
            "comaMinutesAfterAdmiss=rtrim(a.ryh_hmsj_min)," +
            "rescueTimes=rtrim(a.qjcs)," +
            "rescueSuccessTimes=rtrim(a.cgcs)," +
            "caseClassification=rtrim(a.blfx)," +
            "hasIcu=rtrim(a.zzjh)," +
            "icuDays=rtrim(a.zzjh_day)," +
            "icuHours=rtrim(a.zzjh_hour)," +
            "monopathyManagement=rtrim(a.dbz)," +
            "clinicalPathwayManagement=rtrim(a.lclj)," +
            "drgsManagement=rtrim(a.drgs)," +
            "useAntibiotic=rtrim(a.kss)," +
            "bacilliculture=rtrim(a.xjpy)," +
            "statutoryEpidemic=rtrim(a.fdcrb)," +
            "hurtReasonName=rtrim(a.hurt_reason_name)," +
            "hurtReasonCode=rtrim(a.hurt_reason_code)," +
            "tumorLevelT=rtrim(a.tumor_level_t)," +
            "tumorLevelN=rtrim(a.tumor_level_n)," +
            "tumorLevelM=rtrim(a.tumor_level_m)," +
            "a.tumor_level,a.fyzlyyy," +
            "xxeApgar=rtrim(a.apgar) " +
            "from batj_ba2 a with(nolock), zy_inactpatient b with(nolock) where " +
            "b.inpatient_no=a.bah and b.admiss_times=a.zycs and " +
            "a.bah=#{bah} and a.zycs=#{times}")
    CaseFrontsheetMain getBatjBa2ForOutPatient(String bah, int times);

    @Select("select c.sheet_column as code,sum(a.charge_fee) as name " +
            "from zy_detail_charge a,zd_charge_item b,zd_charge_ba_class c " +
            "where inpatient_no=#{bah} and admiss_times=#{times} " +
            "and a.charge_code_mx=b.code " +
            "and b.zd_charge_ba_class=c.code " +
            "group by c.sheet_column " +
            "union " +
            "select case when charge_code='BILL01' then 'westMedicineFee' when charge_code='BILL28' " +
            "then 'chinesePatentMedicineFee' else 'chineseHerbalMedicineFee' end sheet_column, " +
            "SUM(charge_fee) as name " +
            "from zy_detail_charge " +
            "where inpatient_no=#{bah} and admiss_times=#{times} and charge_code in ('BILL01','BILL02','BILL28') " +
            "group by charge_code")
    List<CodeName> selectPatCharges(String bah, int times);

    @Select("select no=rtrim(dis_diag_no), name=rtrim(dis_diag_comment), " +
            "code=rtrim(dis_diag), admissStatus=rtrim(admiss_status), " +
            "dismissStatus=rtrim(dis_diag_status) from ba_first_page1 with(nolock) " +
            "where inpatient_no=#{bah} and admiss_times=#{times}")
    List<CaseFrontsheetDisdiag> getDisdiags(String bah, int times);

    @Select("select rtrim(code) as code,rtrim(name) as name from zd_icd_code_new where code=#{code}")
    CaseFrontsheetDisdiag selectDiagInfoByCode(String code);

    @Select("select no=rtrim(ssxh),name=rtrim(ssmc),date=ssrq, " +
            "op_end_date,anst_start_date,anst_end_date,anaesthesiaor=rtrim(mzys), " +
            "level=rtrim(ssjb),code=rtrim(ssbm),operator=rtrim(ssys), " +
            "operatorName=(select rtrim(name) from a_employee_mi with(nolock) where code=ssys)," +
            "assistantOne=rtrim(sszs1),assistantTwo=rtrim(sszs2), " +
            "assistantOneName=(select rtrim(name) from a_employee_mi with(nolock) where code=sszs1)," +
            "assistantTwoName=(select rtrim(name) from a_employee_mi with(nolock) where code=sszs2)," +
            "cut=rtrim(qkjb),heal=rtrim(yhqk),anaesthesia=rtrim(mzff)," +
            "anaesthesiaorName=(select rtrim(name) from a_employee_mi with(nolock) where code=mzys) " +
            "from batj_ba4 with(nolock) where bah=#{bah} and zycs=#{times} order by ssxh")
    List<CaseFrontsheetSurgery> getSurgeries(String bah, int times);

    @Select("select top 1 rtrim(yb_code) as code,rtrim(yb_name) as name from zd_icd9_cm3 where code=#{code}")
    CaseFrontsheetSurgery selectSurgeryByCode(String code);

    @Update("update a_patient_mi set name=#{name}, " +
            "sex=#{sex}, " +
            "health_card_no=#{healthCardNo}," +
            "birth_date=#{birthDate}, " +
            "country=#{country}, " +
            "birth_place=#{birthPlace}, " +
            "nation_code=#{nation}, " +
            "social_no=#{socialNo}, " +
            "occupation_code=#{occupation}, " +
            "marry_code=#{marriage}, " +
            "home_street=#{livePlace}, " + // max 32 char
            "home_tel=#{phone}, " +
            "home_zipcode=#{addrZipCode}, " +
            "account_street=#{hkPlaceName}, " + // max 20 char
            "account_zipcode=#{hkZipCode}, " +
            "employer_name=#{unitName}, " +
            "employer_street=#{unitPlace}, " + // max 32 char
            "employer_tel=#{unitPhone}, " +
            "employer_zipcode=#{unitZipCode}, " +
            "relation_name=#{contactName}, " +
            "relation_code=#{contactRelation}, " +
            "relation_street=#{contactAddrName}, " + // max 32 char
            "relation_tel=#{contactPhone} " +
            "where inpatient_no=#{bah}")
    void updateAPatientMi(CaseFrontsheetMain sheet);

    @Update("update a_patient_mi set province_code=#{province},city_code=#{city},district_code=#{district} " +
            "where inpatient_no=#{bah}")
    void updateAddressCascader(String bah, Integer province, Integer city, Integer district);

    @Update("update zy_actpatient set autopsy_mark=#{autopsy},clinic_diag_str=#{clinicDiagStr}, " +
            "diagnose_conform1=#{dc1},diagnose_conform2=#{dc2},diagnose_conform3=#{dc3}," +
            "diagnose_conform4=#{dc4}, diagnose_conform5=#{dc5}, operation=#{hasSurgery}," +
            "pathology_diag_comment=#{pathologicDiagStr},pathology_diag=#{pathologicDiagCode}, " +
            "clinic_diag=#{clinicDiagCode} where inpatient_no=#{bah} and admiss_times=#{times}")
    void updateZyActPatient(String bah, int times, String autopsy, String dc1, String dc2,
                            String dc3, String dc4, String dc5, String hasSurgery,
                            String pathologicDiagStr, String pathologicDiagCode,
                            String clinicDiagCode, String clinicDiagStr);

    @Update("update zy_inactpatient set autopsy_mark=#{autopsy},clinic_diag_str=#{clinicDiagStr}, " +
            "diagnose_conform1=#{dc1},diagnose_conform2=#{dc2},diagnose_conform3=#{dc3}," +
            "diagnose_conform4=#{dc4}, diagnose_conform5=#{dc5}, operation=#{hasSurgery}," +
            "pathology_diag_comment=#{pathologicDiagStr},pathology_diag=#{pathologicDiagCode}, " +
            "clinic_diag=#{clinicDiagCode} where inpatient_no=#{bah} and admiss_times=#{times}")
    void updateZyInActPatient(String bah, int times, String autopsy, String dc1, String dc2,
                              String dc3, String dc4, String dc5, String hasSurgery,
                              String pathologicDiagStr, String pathologicDiagCode,
                              String clinicDiagCode, String clinicDiagStr);

    @Select("select count(1) from batj_ba1 with(nolock) where bah=#{bah} and zycs=#{times}")
    int isBatjBa1Exist(String bah, int times);

    @Select("select count(1) from batj_ba2 with(nolock) where bah=#{bah} and zycs=#{times}")
    int isBatjBa2Exist(String bah, int times);

    @Insert("insert into batj_ba1 (bah, zyh, zycs, xm, ryrq, ryks, rybf) values " +
            "(#{bah}, #{bah}, #{times}, #{name}, #{ryrq}, " +
            "(select code from zd_unit_code with(nolock) where name=#{dept} and isnull(del_flag,'')!='1'), " +
            "(select code from zd_unit_code with(nolock) where name=#{ward} and isnull(del_flag,'')!='1'))")
    void createBatjBa1(String bah, int times, String name, Date ryrq, String dept, String ward);

    @Insert("insert into batj_ba2 (bah, zyh, zycs) values (#{bah}, #{bah}, #{times})")
    void createBatjBa2(String bah, int times);

    @Insert("insert into t_frontsheet_supplement (bah, times) values (#{bah}, #{times})")
    void createSheetSupplement(String bah, int times);

    @Update("update batj_ba1 set " +
            "pay_method=#{payMethod}," +
            "age_days=#{ageDays}," +
            "jg=#{nativePlace}," +
            "new_born_weight=#{newBornWeight}," +
            "new_born_admiss_weight=#{newBornAdmissWeight}," +
            "xm=#{name}, " +
            "xb=#{sex}, " +
            "csrq=#{birthDate}, " +
            "hyzk=#{marriage}, " +
            "zy=#{occupation}, " +
            "csd=#{birthPlace}, " +
            "mz=#{nation}, " +
            "gj=#{country}, " +
            "sfzh=#{socialNo}, " +
            "gzdw=#{unitName}, " +
            "gzdh=#{unitPhone}, " +
            "gzyb=#{unitZipCode}, " +
            "hkdz=#{hkPlace}, " +
            "hkdz2=#{hkPlaceName}," +
            "hkyb=#{hkZipCode}, " +
            "lxr=#{contactName}, " +
            "lxrgx=#{contactRelation}, " +
            "lxdh=#{contactPhone}, " +
            "lxdz=#{contactAddr}, " +
            "lxdz2=#{contactAddrName}," +
            "rytj=#{zyAdmissWay}, " +
            "xzz=#{livePlace}, " +
            "xdh=#{phone} " +
            "where bah=#{bah} and zycs=#{admissTimes}")
    void updateBatjBa1(CaseFrontsheetMain info);

    @Update("update batj_ba2 set " +
            "blzd_qph=#{blh}," +
            "gm_flag=#{allergy}," +
            "gmwy=#{allergicMedicine}," +
            "hbsag=#{hbsAg}," +
            "hcv_vb=#{hcvAb}," +
            "hiv_vb=#{hivAb}," +
            "tp_ab=#{tpAb}," +
            "xx=#{bloodType}," +
            "xx_rh=#{rh}," +
            "kzr=#{deptLeader}," +
            "zrys=#{leaderDoctor}," +
            "zzys=#{mainDoctor}," +
            "zyys=#{admissDoctor}," +
            "job_nurse=#{dutyNurse}," +
            "jxys=#{studyDoctor}," +
            "sxys=#{internshipDoctor}," +
            "bmy=#{coder}," +
            "bazl=#{qualityControlLevel}," +
            "zkys=#{qualityControlDoctor}," +
            "zkhs=#{qualityControlNurse}," +
            "barq=#{qualityControlDate}," +
            "lyfs=#{zyDismissWay}," +
            "fyzlyyy=#{fyzlyyy}, " +
            "jsjg=#{dismissDestination}," +
            "zzy_flag=#{admissAgainInOneMonth}," +
            "zzy_md=#{admissAgainPurpose}," +
            "ryq_hmsj_day=#{comaDaysBeforeAdmiss}," +
            "ryq_hmsj_hour=#{comaHoursBeforeAdmiss}," +
            "ryq_hmsj_min=#{comaMinutesBeforeAdmiss}," +
            "ryh_hmsj_day=#{comaDaysAfterAdmiss}," +
            "ryh_hmsj_hour=#{comaHoursAfterAdmiss}," +
            "ryh_hmsj_min=#{comaMinutesAfterAdmiss}," +
            "qjcs=#{rescueTimes}," +
            "cgcs=#{rescueSuccessTimes}," +
            "blfx=#{caseClassification}," +
            "zzjh=#{hasIcu}," +
            "zzjh_day=#{icuDays}," +
            "zzjh_hour=#{icuHours}," +
            "dbz=#{monopathyManagement}," +
            "lclj=#{clinicalPathwayManagement}," +
            "drgs=#{drgsManagement}," +
            "kss=#{useAntibiotic}," +
            "xjpy=#{bacilliculture}," +
            "fdcrb=#{statutoryEpidemic}," +
            "hurt_reason_name=#{hurtReasonName}," +
            "hurt_reason_code=#{hurtReasonCode}," +
            "tumor_level_t=#{tumorLevelT}," +
            "tumor_level_n=#{tumorLevelN}," +
            "tumor_level_m=#{tumorLevelM}," +
            "tumor_level=#{tumorLevel}, " +
            "apgar=#{xxeApgar} " +
            "where bah=#{bah} and zycs=#{admissTimes}")
    void updateBatjBa2(CaseFrontsheetMain info);

    @Delete("delete from ba_first_page1 where inpatient_no=#{bah} and admiss_times=#{times}")
    void deleteOldDisdiag(String bah, int times);

    @Delete("delete from batj_ba4 where bah=#{bah} and zycs=#{times}")
    void deleteOldSurgeryRecord(String bah, int times);

    @Insert("insert into ba_first_page1 (inpatient_no, admiss_times, dis_diag_no," +
            "dis_diag_comment, dis_diag, admiss_status, dis_diag_status, op_id_code) " +
            "values (#{bah}, #{times}, #{no}, #{name}, #{code}, #{admissStatus}, " +
            "#{dismissStatus}, #{opIdCode})")
    void writeNewDisdiag(CaseFrontsheetDisdiag disDiag);

    @Insert("insert into batj_ba4 (bah,zyh,zycs,ssxh,ssmc,ssrq,ssjb,ssbm,ssys,sszs1,sszs2,qkjb,yhqk," +
            "mzff,mzys,op_start_date,op_end_date,anst_start_date,anst_end_date) " +
            "values (#{bah},#{bah},#{times},#{no},#{name},#{date},#{level},#{code},#{operator},#{assistantOne}," +
            "#{assistantTwo},#{cut},#{heal},#{anaesthesia},#{anaesthesiaor},#{date},#{opEndDate},#{anstStartDate},#{anstEndDate})")
    void writeNewZySurgeryRecord(CaseFrontsheetSurgery surgery);

    @Update("update t_case_frontsheet_main set file_status=0,unsign_date=getdate() " +
            "where bah=#{bah} and admiss_times=#{times}")
    void updateSignStateToUnsigned(String bah, int times);

    @Insert("insert into ba_op_log (op_type, op_id, op_time, inpatient_no, admiss_times) values " +
            "(#{opType}, #{staffId}, getDate(), #{bah}, #{times})")
    void writeBaOpLog(int opType, String staffId, String bah, int times);

    @Select("select rtrim(dis_diag_no) no, rtrim(dis_diag) code, " +
            "rtrim(dis_diag_comment) name, rtrim(dis_diag_status) cyzg, " +
            "rtrim(op_id_code) operId, convert(varchar(19), op_diag_date, 21) opDate, " +
            "diagType='13',si_diag_type,bzfx='普通', admiss_cond " +
            "from zy_dis_diag_yb with(nolock) where inpatient_no=#{bah} and admiss_times=#{times}")
    List<YiBaoDisdiag> getYbDiags(String bah, int times);

    @Delete("delete from zy_dis_diag_yb where inpatient_no=#{bah} and admiss_times=#{times}")
    void deleteOldYbDiag(String bah, int times);

    @Insert("insert into zy_dis_diag_yb (inpatient_no, admiss_times, dis_diag_no, dis_diag_type, dis_diag, " +
            "dis_diag_comment, op_id_code, op_diag_date, dis_diag_bzfx, dis_diag_status, si_diag_type, admiss_cond) " +
            "values (#{bah},#{times},#{no},13,#{code},#{name},#{operId},#{opDate},'普通',#{cyzg},#{siDiagType},#{admissCond})    ")
    void insertNewYbDiag(YiBaoDisdiag diag);

    @Select("<script>" +
            "select distinct " +
            "a.bah,a.admiss_times as times, " +
            "a.name,a.sex,fileStatus=1, " +
            "a.admiss_doctor_name as doctorName," +
            "a.admiss_doctor as doctorCode, " +
            "a.sign_date, " +
            "a.dismiss_date," +
            "a.admiss_dept, " +
            "a.dismiss_dept, " +
            "a.case_classification as blfx " +
            "from t_case_frontsheet_main a with(nolock), " +
            "t_case_frontsheet_disdiag c with(nolock), " +
            "t_case_frontsheet_surgery d with(nolock) " +
            "where " +
            "a.dismiss_date&gt;=#{start} and " +
            "a.dismiss_date&lt;=#{end} and " +
            "<if test=\"blfxChkbox!=null and blfxChkbox.size>0 \">" +
            "a.case_classification in " +
            "<foreach collection='blfxChkbox' item='item' open='(' close=')' separator=','>" +
            "#{item}" +
            "</foreach> and " +
            "</if>" +
            "<if test=\"medType!=null and medType!='' \">" +
            "a.med_type=#{medType} and " +
            "</if>" +
            "<if test=\"doctorCode!=null and doctorCode!='' \">" +
            "a.admiss_doctor=#{doctorCode} and " +
            "</if>" +
            "<if test=\"sex!=null and sex!='' \">" +
            "a.sex=#{sex} and " +
            "</if>" +
            "<if test=\"icdCode!=null and icdCode!='' \">" +
            "c.code=#{icdCode} and " +
            "</if>" +
            "<if test=\"surgeryCode!=null and surgeryCode!='' \">" +
            "d.code=#{surgeryCode} and " +
            "</if>" +
            "c.bah=a.bah and " +
            "c.times=a.admiss_times and " +
            "d.bah=a.bah and " +
            "d.times=a.admiss_times " +
            "</script>")
    List<SheetOverview> advanceSearch(AdvanceSearch param);

    @Select("select file_status from t_case_frontsheet_main with(nolock) where bah=#{bah} and admiss_times=#{times}")
    Integer selectFileStatus(String bah, int times);

    @Select("select min(op_time) from ba_op_log with(nolock) where " +
            "inpatient_no=#{bah} and admiss_times=#{times} and op_type=2")
    Date selectFirstSignDate(String bah, int times);

    @Select("select sign_staff from t_case_frontsheet_main with(nolock) where bah=#{bah} and admiss_times=#{times}")
    String selectSignStaff(String bah, int times);

    @Select("select role_id from dj_user_role where user_code=#{code}")
    List<Integer> getUserRoles(String code);

    @Select("select count(1) from t_yb_setl_modify_req where pat_no=#{bah} and times=#{times}")
    Integer selectModified(String bah, int times);

    @Select("select top 1 * from t_si_disefamily_diagnose with(nolock) where dise_code=#{code} ")
    DisefamilyGrade selectDisefamilyGrade(String code);

    @Select("select yb_code from zd_icd9_cm3 where code in " +
            "(select ssbm from ${table} with(nolock) where zyh=#{bah} and zycs=#{times} and isnull(ssbm,'')!='') " +
            "union select ssbm from ${table} with(nolock) where zyh=#{bah} and zycs=#{times} and isnull(ssbm,'')!=''")
    List<String> selectPatientSurgeryCodes(String bah, int times, String table);

    @Select("select * from t_si_operation_disefamily with(nolock) where disefamily_code=#{code}")
    List<OprnDisefamilyGrade> selectOperationDisefamilies(String code);

    @Update("update zd_icd_code set weight=(weight+1) where code=#{code}")
    void increaseDiagWeight(String code);

    @Select("select *, " +
            "duplicated=(select count(1) from t_case_frontsheet_duplicate where bah=#{bah} and times=#{times})," +
            "lendout=(select count(1) from t_case_frontsheet_lendout where bah=#{bah} and times=#{times} and state='LEND_OUT')," +
            "closedown=(select count(1) from t_case_frontsheet_closedown where bah=#{bah} and times=#{times}) " +
            "from t_case_frontsheet_main where bah=#{bah} and admiss_times=#{times} and file_status=1")
    CaseFrontsheetMain selectStoredSheetMain(String bah, int times);

    @Select("select * from t_case_frontsheet_disdiag where bah=#{bah} and times=#{times} ")
    List<CaseFrontsheetDisdiag> selectSignedSheetDiags(String bah, int times);

    @Select("select * from t_case_frontsheet_surgery where bah=#{bah} and times=#{times} ")
    List<CaseFrontsheetSurgery> selectSignedSheetSurgeries(String bah, int times);

    @Update("update t_case_frontsheet_main set age_days=#{agedays} where bah=#{bah} and admiss_times=#{times}")
    void updateNewBornAge(String bah, int times, Integer agedays);

    @Select("select rtrim(yb_code) as code, rtrim(yb_name) as name from zd_icd_code_new where code=#{code} and del_flag=0")
    CodeName selectSiDiagByBaDiag(String code);

    @Select("select province_code,city_code,district_code," +
            "provinceName=(select name from t_region where code=province_code), " +
            "cityName=(select name from t_region where code=city_code), " +
            "districtName=(select name from t_region where code=district_code) " +
            "from a_patient_mi where inpatient_no=#{bah}")
    StandardAddressMember selectStandardAddressMember(String bah);

    @Select("select rtrim(social_no) from a_patient_mi where inpatient_no=#{bah}")
    String selectSocialNo(String bah);

    @Select("select parent_code as code, name=(select t.name from t_region t where t.code=a.parent_code) " +
            "from t_region a where code=#{region}")
    Region selectParentRegion(Integer region);

    @Select("select name from t_region where code=#{region}")
    String selectRegionName(Integer region);

    @Select("select name from zd_district_code where code=#{code}")
    String getDistrictName(String code);

    @Select("select top 1 med_type from t_si_pat_info where pat_no=#{patNo} and times=#{times} order by " +
            "ledger_sn desc")
    String selectMedType(String patNo, int times);

    @Select("select provinceName=(select name from t_region where code=#{province}), " +
            "cityName=(select name from t_region where code=#{city}), " +
            "districtName=(select name from t_region where code=#{district}) ")
    StandardAddressMember selectStandardAddressMember2(int province, int city, int district);

    @Select("select audit_flag from t_yb_setl_modify_req where pat_no=#{patNo} and times=#{times} ")
    Integer qualityPass(String patNo, int times);

    @Select("<script>" +
            "select rtrim(yb_code) as code,rtrim(yb_name) as name,charge_code as wjwCode," +
            "charge_name as wjwName from zd_icd9_cm3 where yb_code in " +
            "<foreach collection='surgeries' item='surgery' open='(' separator=',' close=')'>" +
            "#{surgery.code}" +
            "</foreach>" +
            "</script>")
    List<HisWjwMatchEntity> selectSurgeryChargeCode(List<CaseFrontsheetSurgery> surgeries);

    @Select("<script>" +
            "select sum(charge_amount) from zy_detail_charge where inpatient_no=#{patNo} and admiss_times=#{times} " +
            "and charge_code_mx in " +
            "<foreach collection='list' item='code' open='(' separator=',' close=')'>" +
            "#{code}" +
            "</foreach>" +
            "</script>")
    Integer selectChargeSumamt(String patNo, int times, String[] list);

    @Select("select code,yb_name as name,yb_code from zd_anaesthesia where yb_code is not null")
    List<CodeName> selectZdAnstWays();

    @Select("select code,rtrim(name) as name,si_code as ybCode from zd_country_code where si_code is not null")
    List<CodeName> selectZdCountries();

    @Select("select code,rtrim(name) as name,code2 as ybCode from zd_nation_code where code2 is not null ")
    List<CodeName> selectZdNations();

    @Select("select top 1 insuplc_admdvs from t_si_setlinfo where pat_no=#{patNo} and times=#{times} and revoked=0")
    String selectSetlInsuplcAdmdvs(String patNo, int times);

    @Select("select top 1 isnull(op_type,9) from zd_icd9_cm3 where yb_code=#{code}")
    Integer selectOperationType(String code);

    // 病历分型
    @Select("select data_element from emr_data_element where pat_no=#{patNo} and times=#{times}")
    String selectBlfxElement(String patNo, int times);

    // 细菌培养次数
    @Select("select count(1) from ysh_yj_req where inpatient_no=#{patNo} and admiss_times=#{times} " +
            "and req_type=2 and order_type='011'")
    int selectBacillicultureCount(String patNo, int times);

    // 法定传染病
    @Select("SELECT rtrim(contagion) as a,rtrim(contagion2) as b,rtrim(contagion3) as c " +
            "FROM crb_main_card where patient_id=#{patNo} and times=#{times}")
    List<Map<String, String>> selectStatutoryEpidemic(String patNo, int times);

    // 抗生素使用次数
    @Select("select count(1) from zy_detail_charge a left join yp_zd_dict b on (code=charge_code_mx " +
            "and b.serial='01') where a.serial!='00' and ori_detail_sn is null and trans_flag_yb!='2' " +
            "and kss_flag='1' and inpatient_no=#{patNo} and admiss_times=#{times}")
    int selectAntibiotics(String patNo, int times);

    @Select("select top 1 audit_state from t_frontsheet_quality_verification " +
            "where pat_no=#{patNo} and times=#{times} order by application_time desc ")
    AuditState selectStates(String patNo, int times);

    @Delete("delete from t_case_frontsheet_main where bah=#{bah} and admiss_times=#{times}")
    void deleteOldSheet(String bah, int times);

    @Insert("insert into t_case_frontsheet_duplicate (bah,times,duplicate_time,duplicate_staff, " +
            "visit_staff,remark) " +
            "values (#{bah},#{times},#{markTime},#{opStaff},#{visitStaff},#{remark})")
    int executeDuplicate(MarkStateRequest request);

    @Insert("insert into t_case_frontsheet_closedown (bah,times,closedown_time,closedown_staff," +
            "remark,visit_staff) " +
            "values (#{bah},#{times},#{markTime},#{opStaff},#{remark},#{visitStaff})")
    int executeClosedown(MarkStateRequest request);

    @Select("select bah,admiss_times as times,name,sex,sign_staff, " +
            "signTime=convert(varchar(8),sign_date,14), " +
            "signStaffName=(select rtrim(d.name) from a_employee_mi d where d.code=sign_staff) " +
            "from t_case_frontsheet_main where file_status=1 and sign_date>=#{start} " +
            "and sign_date<=#{end} order by sign_date")
    List<SheetOverview> signedListByDate(String start, String end);

    @Select("select bah,admiss_times as times,sign_date as signDateOrigin,sign_staff,late_flag " +
            "from t_case_frontsheet_main where file_status=0 and sign_staff is not null " +
            "and sign_date is not null and unsign_date is not null " +
            "and datediff(day,unsign_date,getdate())>=3 ")
    List<SheetOverview> selectSheetsForAutoSign();

    @Select("select bah,admiss_times as times,name,dismiss_date as disDate, " +
            "dismiss_dept as deptName, " +
            "lendOutCount=(select count(1) from t_case_frontsheet_lendout " +
            "where bah=#{bah} and times=a.admiss_times and state='LEND_OUT') " +
            "from t_case_frontsheet_main a " +
            "where bah=#{bah} and file_status=1")
    List<SheetOverview> getSimpleSheetForLendOut(String bah);

    @Insert("<script>" +
            "insert into t_case_frontsheet_lendout (bah,times,lend_staff,lend_time,remark,op_staff, " +
            "pat_name,dis_date,dis_dept,lend_staff_phone) " +
            "values " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.bah},#{item.times},#{lendStaff},#{lendTime}," +
            "#{remark},#{opStaff},#{item.name},#{item.disDate}," +
            "#{item.deptName},#{lendStaffPhone})" +
            "</foreach>" +
            "</script>")
    int insertLendOutInfo(LendOutRequest request);

    @Select("select * from t_case_frontsheet_lendout where state='LEND_OUT'")
    List<LendOutSheet> selectLendOutSheets();

    @Update("update t_case_frontsheet_lendout set state='RETURNED',return_time=getdate() where id=#{id}")
    int returnSheet(int id);

    @Select("select top 1 bah,times, " +
            "opStaff=(select rtrim(d.name) from a_employee_mi d where d.code=duplicate_staff), " +
            "visit_staff,remark,duplicate_time as markTime " +
            "from t_case_frontsheet_duplicate a where a.bah=#{bah} and a.times=#{times} " +
            "order by duplicate_time desc")
    MarkStateRequest selectExistRequest(String bah, int times);

    @Select("select top 1 bah,times, " +
            "opStaff=(select rtrim(d.name) from a_employee_mi d where d.code=closedown_staff), " +
            "visit_staff,remark,closedown_time as markTime " +
            "from t_case_frontsheet_closedown a where a.bah=#{bah} and a.times=#{times} " +
            "order by closedown_time desc")
    MarkStateRequest selectExistRequest2(String bah, int times);

    @Select("select top 1 bah,times,lend_staff,lend_staff_phone,remark,lend_time, " +
            "opStaff=(select rtrim(d.name) from a_employee_mi d where d.code=op_staff) " +
            "from t_case_frontsheet_lendout where bah=#{bah} and times=#{times} and state='LEND_OUT' " +
            "order by lend_time desc")
    LendOutRequest selectExistLendOut(String bah, int times);

    @Select("select * from t_frontsheet_supplement where bah=#{bah} and times=#{times}")
    FrontSheetSupplement getSheetSupplement(String bah, int times);

    @Update("update t_frontsheet_supplement set " +
            "adm_diag_code=#{admDiagCode},adm_diag_name=#{admDiagName},adm_status=#{admStatus}, " +
            "diagnosis_confirm_date=#{diagnosisConfirmDate,jdbcType=DATE}, " +
            "ventilator_use_time=#{ventilatorUseTime}, " +
            "had_icu=#{hadIcu},icu_name=#{icuName},start_icu_time=#{startIcuTime,jdbcType=TIMESTAMP}, " +
            "end_icu_time=#{endIcuTime,jdbcType=TIMESTAMP},had_ecmo=#{hadEcmo},ecmo_mode=#{ecmoMode}, " +
            "start_ecmo_time=#{startEcmoTime,jdbcType=TIMESTAMP},end_ecmo_time=#{endEcmoTime,jdbcType=TIMESTAMP}, " +
            "memlung_change_times=#{memlungChangeTimes},erythrocyte=#{erythrocyte,jdbcType=REAL}, " +
            "platelet=#{platelet,jdbcType=REAL},plasma=#{plasma,jdbcType=REAL}, " +
            "whole_blood=#{wholeBlood,jdbcType=REAL}, " +
            "autotransfusion=#{autotransfusion,jdbcType=REAL},infusion=#{infusion}, " +
            "infusion_reaction=#{infusionReaction},transfusion=#{transfusion}, " +
            "transfusion_reaction=#{transfusionReaction} where bah=#{bah} and times=#{times}")
    void updateSheetSupplement(FrontSheetSupplement sheetSupplement);
}
