package thyyxxk.webserver.dao.his.zhuyuanyisheng;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.*;
import thyyxxk.webserver.entity.datamodify.GetDropdownBox;
import thyyxxk.webserver.entity.dictionary.CodeName;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.OpRecord;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.ShouShuFanHui;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.TReqSurgicalDiag;
import thyyxxk.webserver.entity.zhuyuanyisheng.shoushu.ZdIcd9Cm3;
import thyyxxk.webserver.entity.zhuyuanyisheng.yizhuluru.XinZhenYiZhu;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 描述： 手术申请
 * </p>
 *
 * @author xc
 * @date 2022-02-22 15:45
 */
@Mapper
public interface ShouShuShenQingDao extends BaseMapper<OpRecord> {

    @Select("<script>" +
            "select op_type_name = (select name from zd_operation_type where code = op_type), " +
            "       rtrim(code) as code," +
            "       rtrim(name) name,op_scale " +
            "from zd_icd9_cm3 " +
            "where (code like #{name} or name like #{name} or py_code like #{name} or d_code like #{name}) " +
            "<if test=\"type !=null and type != 0 \">" +
            " and op_type = #{type} " +
            "</if>" +
            "</script>")
    List<ZdIcd9Cm3> obtainSurgicalItems(String name,
                                        Integer type);

    @Select("select a.code      as code,\n" +
            "       name_doctor as name\n" +
            "from op_level_management a,\n" +
            "     a_employee_mi b\n" +
            "where a.code = b.code\n" +
            "  and code_op = #{code}\n" +
            "  and isnull(del_flag, '0') <> '1'")
    List<CodeName> getDoctorByOpCode(String code);

    @Select("select rtrim(op_name) as  value " +
            "from op_record with (NOLOCK) " +
            "where inpatient_no = #{patNo} " +
            "  and admiss_times = #{times}" +
            "  and op_name like #{name} ")
    List<Map<String, String>> huoQuShouShuMing(@Param("patNo") String patNo,
                                               @Param("times") Integer times,
                                               @Param("name") String name);

    @Select("select count(1) from op_record where inpatient_no = #{patNo} and admiss_times = #{times} and status <> 'd' and urgent_clinic_flag = '0' ")
    int currentPatientOpCount(String patNo, Integer times);

    @Select("select count(1) from emr_patient_data where pat_no = #{patNo} and times = #{times} and del_flag = 0  and emr_category_code = 'shuqiantaolun' ")
    int currentEmrPreoperativelyDiscussCount(String patNo, Integer times);

    @Select("SELECT a.code, a.name " +
            "FROM ysh_zd_ss_type a with (NOLOCK), " +
            "     yz_order_item b with (NOLOCK) " +
            "where a.code = b.ss_type " +
            "  and isnull(b.del_flag, '') <> '1' " +
            "  and b.operation = 'p' " +
            "group by a.code, a.name " +
            "order by a.name")
    List<GetDropdownBox> shouShuShenQingCeBianLan();

    @Select("select a.record_id /*申请单号*/," +
            "       a.op_name," +
            "       a.urgent_clinic_flag," +
            "       a.apply_date, " +
            "       part_code," +
            "       partCodeName = (select rtrim(name) from op_zd_part_new where code = part_code), " +
            "       dept_code, " +
            "       dept_code_name  = (select rtrim(name) from zd_unit_code with (NOLOCK) where code = dept_code), " +
            "       urgent_clinic_flag, " +
            "       inpatient_no, " +
            "       admiss_times, " +
            "       bed_no, " +
            "       patient_name, " +
            "       diag_before_op /* 术前诊断 */, " +
            "       diag_before_code, " +
            "       hocus_code, " +
            "       hocusName = (select rtrim(name) from zd_anaesthesia with (NOLOCK) where code = hocus_code), " +
            "       op_scale, " +
            "       doctor_zd_name  = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = doctor_zd)/*主刀医生*/, " +
            "       doctor_1_name   = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = doctor_1)/*第1助手*/, " +
            "       doctor_2_name   = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = doctor_2)/*第2助手*/, " +
            "       doctor_3_name   = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = doctor_3)/*第2助手*/, " +
            "       doctor_mz_name  = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = doctor_mz)/*麻醉医生*/, " +
            "       nurse_qx_name   = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = nurse_qx)/*器械护士*/, " +
            "       nurse_xh_name   = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = nurse_xh)/*巡回护士*/, " +
            "       req_date, " +
            "       op_datetime, " +
            "       remark/*附注说明*/ " +
            "from op_record a with (NOLOCK), " +
            "     op_record_join b with (NOLOCK)" +
            "where inpatient_no = #{patNo} " +
            "  and admiss_times = #{times} " +
            "  and a.record_id = #{recordId} " +
            "  and a.record_id = b.record_id")
    OpRecord daYingShouShu(@Param("patNo") String patNo,
                           @Param("times") Integer times,
                           @Param("recordId") Integer recordId);

    @Select("select req_no, code, name, type, sort " +
            "from t_req_surgical_diag where req_no = #{recordId}")
    List<TReqSurgicalDiag> selectReqSurgicalDiagByReqNo(@Param("recordId") Integer recordId);

    @Select("select refer_physician_name = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = refer_physician) /*住院医生*/, " +
            "       dept_director_name   = (select rtrim(name) from a_employee_mi with (NOLOCK) where code = dept_director) /*科主任*/, " +
            "       sex, " +
            "       birth_date           = (select (convert(varchar(10), birth_date, 21)) " +
            "                               from a_patient_mi with (NOLOCK) " +
            "                               where zy_actpatient.inpatient_no = a_patient_mi.inpatient_no) " +
            "from zy_actpatient with (NOLOCK) " +
            "where inpatient_no = #{patNo} " +
            "  and admiss_times = #{times};")
    OpRecord daYingHuanZheXinXi(@Param("patNo") String patNo,
                                @Param("times") Integer times);

    @Select("<script>" +
            "SELECT rtrim(order_code) as opCode, " +
            "       rtrim(order_name) as opName, " +
            "       rtrim(ss_type)    as orderType " +
            "FROM yz_order_item with (NOLOCK) " +
            "where operation = 'p' " +
            "<if test=\"code != null and code != '' \">" +
            " and  ss_type = #{code} " +
            "</if>" +
            "  and isnull(del_flag, '') &lt;&gt; '1' " +
            "  and (order_name like #{name} or order_code like #{name} or py_code like #{name} or d_code like #{name})" +
            "</script>")
    IPage<ShouShuFanHui> fenLeiXiangQing(IPage<ShouShuFanHui> page,
                                         @Param("code") String code,
                                         @Param("name") String name);

    @Select("<script>" +
            "select code,name, py_code, d_code as w_code from op_zd_part_new " +
            "with (NOLOCK) where 1=1 " +
            "<if test=\"code != null and code != '' \">" +
            "(name like #{code} or py_code like #{code} or d_code like #{code} or code like #{code})" +
            "</if>" +
            "</script>")
    List<GetDropdownBox> huoQuShouShuBuWei(String code);

    @Select("Select isnull(Max(op_times),0) " +
            "From op_record with (NOLOCK) " +
            "Where inpatient_no = #{patNo} " +
            "  And admiss_times = #{times} ")
    Integer shouShuShenQingCiShu(@Param("patNo") String patNo,
                                 @Param("times") Integer times);

    @Insert("<script>" +
            "Insert Into op_record_join (record_id, zy_serial_no, op_times, doctor_zd, doctor_wp, doctor_1, doctor_2, doctor_3,nurse_qx, nurse_xh,doctor_mz_ys) " +
            "Values " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.recordId}, '', #{item.opTimes}, #{item.doctorZd}, null, #{item.doctor1}, #{item.doctor2}, " +
            "#{item.doctor3}, #{item.nurseQx}, #{item.nurseXh},#{item.doctorMzYs})" +
            "</foreach>" +
            "</script>")
    void chaRuShouShuYiSheng(@Param("list") List<OpRecord> list);

    @Insert("Insert Into op_record_join (record_id, zy_serial_no, op_times, doctor_zd, doctor_wp, doctor_1, doctor_2, " +
            "doctor_3,nurse_qx, nurse_xh,doctor_mz_ys) " +
            "Values " +
            "(#{item.recordId}, '', #{item.opTimes}, #{item.doctorZd}, null, #{item.doctor1}, #{item.doctor2}, " +
            "#{item.doctor3}, #{item.nurseQx}, #{item.nurseXh},#{item.doctorMzYs})")
    void insertOpRecordJoin(@Param("item") OpRecord item);

    @Insert("<script>" +
            "INSERT INTO op_record (record_id, inpatient_no, patient_name, admiss_times, op_times, dept_code, ward_code, op_code, " +
            "                       op_datetime, infection_flag, urgent_clinic_flag, isolation_indicator, op_scale, input_id, status, " +
            "                       input_date, apply_date, apply_doc, op_name, act_order_no, patient_type, req_date, req_id, bed_no, " +
            "                       ssbc, ssyz_flag, ward_dept,remark,hocus_code,diag_before_op,diag_before_code," +
            "                       part_code) " +
            " VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            " (#{item.recordId}, #{patNo}, #{name}, #{times}, #{item.opTimes}, #{dept}, #{ward}, #{item.opCode}, " +
            "        #{item.opDatetime}, '0', #{item.urgentClinicFlag}, '0', #{item.opScale}, " +
            "        #{userCode}, '1', getdate(), #{item.applyDate}, #{userCode}, #{item.opName}, #{item.actOrderNo}, '2', " +
            "        getdate(), #{userCode}, #{bedNo}, #{item.ssbc}, #{item.ssyzFlag}, #{admissWard},#{item.remark},#{item.hocusCode}," +
            "#{item.diagBeforeOp},#{item.diagBeforeCode}," +
            "        #{item.partCode})" +
            "</foreach>" +
            "</script>")
    void chaRuShouShu(@Param("list") List<OpRecord> list,
                      @Param("patNo") String patNo,
                      @Param("name") String name,
                      @Param("times") Integer times,
                      @Param("dept") String dept,
                      @Param("ward") String ward,
                      @Param("userCode") String userCode,
                      @Param("bedNo") String bedNo,
                      @Param("admissWard") String admissWard);

    @Insert("INSERT INTO op_record (record_id, inpatient_no, patient_name, admiss_times, op_times, dept_code, ward_code, op_code, " +
            "                       op_datetime, infection_flag, urgent_clinic_flag, isolation_indicator, op_scale, input_id, status, " +
            "                       input_date, apply_date, apply_doc, op_name, act_order_no, patient_type, req_date, req_id, bed_no, " +
            "                       ssbc, ssyz_flag, ward_dept,remark,hocus_code,diag_before_op,diag_before_code," +
            "                       part_code) " +
            " VALUES " +
            " (#{item.recordId}, #{patNo}, #{name}, #{times}, #{item.opTimes}, #{dept}, #{ward}, #{item.opCode}, " +
            "        #{item.opDatetime}, '0', #{item.urgentClinicFlag}, '0', #{item.opScale}, " +
            "        #{userCode}, '1', getdate(), #{item.applyDate}, #{userCode}, #{item.opName}, #{item.actOrderNo}, '2', " +
            "        getdate(), #{userCode}, #{bedNo}, #{item.ssbc}, #{item.ssyzFlag}, #{admissWard},#{item.remark},#{item.hocusCode}," +
            "#{item.diagBeforeOp},#{item.diagBeforeCode}," +
            "#{item.partCode})")
    void insertOpRecord(@Param("item") OpRecord item,
                        @Param("patNo") String patNo,
                        @Param("name") String name,
                        @Param("times") Integer times,
                        @Param("dept") String dept,
                        @Param("ward") String ward,
                        @Param("userCode") String userCode,
                        @Param("bedNo") String bedNo,
                        @Param("admissWard") String admissWard);

    @Insert("INSERT INTO yz_act_order (order_code, order_name, frequ_code, infant_flag, order_time, physician, start_time, " +
            "                          act_order_no, inpatient_no, admiss_times, drug_flag, enter_oper, enter_time, status_flag, " +
            "                          signer, confirm_time, " +
            "                          self_buy, pay_self, serial, group_no, doctor_flag, dept_code, ward_code, reg_flag," +
            "yb_self_flag,emergency_flag,exec_unit) " +
            " VALUES " +
            " ('${yzCode}',  '${item.orderName}', 'ONCE', #{p.infantFlag}, getdate(), #{userCode}, getdate(), " +
            "        #{item.actOrderNo}, #{p.inpatientNo}, " +
            "        #{p.admissTimes}, 'p', #{userCode}, getdate(), '1', #{userCode}, getdate(), '0', '0', '00', '00', '1'," +
            " #{p.deptCode}, #{p.deptCode}," +
            "'1',#{item.ybSelfFlag},#{item.urgentClinicFlag},#{execUnit})")
    void insertYzOrderData(@Param("item") OpRecord item,
                           @Param("p") XinZhenYiZhu p,
                           @Param("userCode") String userCode,
                           @Param("execUnit") String execUnit,
                           @Param("yzCode") String yzCode);

    @Delete("delete op_record where record_id = #{reqNo};" +
            "delete op_record_join where record_id = #{reqNo};" +
            "delete yz_act_order where act_order_no = #{orderNo};" +
            "delete t_req_surgical_diag where req_no = #{reqNo};")
    void delOpRecord(Integer reqNo, BigDecimal orderNo);


    @Select("select * from op_record with (NOLOCK) where record_id = #{id}")
    OpRecord shouShuXinXi(Integer id);

    @Update("update op_record set status = 'd' where record_id = #{id}")
    void genXingShanChuBiaoZhi(Integer id);

    @Select("select count(1) from op_zd_part_new where name = #{name} and del_flag = 0")
    Boolean repeatPartName(String name);

    @Select("select cast(max(code) as INTEGER) as code from op_zd_part_new")
    Integer getTheMaximumSurgicalCode();

    @Insert("insert into op_zd_part_new(code, name, py_code, d_code) " +
            "values (#{code}, #{name}, #{py}, #{wb})")
    void insertNewSurgicalSite(@Param("code") String code,
                               @Param("name") String name,
                               @Param("py") String py,
                               @Param("wb") String wb);

    @Update("update op_zd_part_new set del_flag = 1 where code = #{code}")
    void removeSurgicalSite(String code);

    @Select("select op_name,\n" +
            "       op_datetime,\n" +
            "       status,\n" +
            "       a.record_id,\n" +
            "       diag_before_op,\n" +
            "       b.doctor_zd,\n" +
            "       doctor_zd_name  = (select rtrim(name) from a_employee_mi where code = b.doctor_zd),\n" +
            "       b.doctor_1,\n" +
            "       doctor_1_name   = (select rtrim(name) from a_employee_mi where code = doctor_1),\n" +
            "       hocus_code,\n" +
            "       hocusName = (select rtrim(name) from zd_anaesthesia where hocus_code = code)\n," +
            "       inpatient_no, admiss_times,urgent_clinic_flag " +
            "from op_record a\n" +
            "         left join op_record_join b on (a.record_id = b.record_id) ${ew.customSqlSegment} ")
    List<OpRecord> selectOpRecord(@Param(Constants.WRAPPER) QueryWrapper<OpRecord> queryWrapper);

    @Insert("<script>" +
            "insert into t_req_surgical_diag (req_no, code, name, type, sort) values " +
            "<foreach collection='list' item='item' index='index' separator=','>" +
            "(#{item.reqNo},#{item.code},#{item.name},#{item.type},#{item.sort})" +
            "</foreach>" +
            "</script>")
    void insertReqSurgicalDiag(@Param("list") List<TReqSurgicalDiag> list);
}
