<?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.saye.hospitalgd.mapper.HisDetailMapper">

    <select id="findHisDetail" parameterType="HashMap" resultType="HashMap">
        select PayMethod
        ,TradingStatus
        ,BizType
        ,PayType
        ,TradeTime
        ,HisOperCode
        ,Amount
        ,remarks
        ,PlatformTransId
        ,PatientId
        ,PatientName
        ,trade_date
        ,his_wsdl_id
        ,HisTransId
        ,clr_type
        ,insutype
        ,ybzhAmount
        ,ybtcAmount
        from hisbill_history
        <where>
            <if test="payType!=null and payType!=''">
                and PayType = #{payType}
            </if>
            <if test="bizType!=null and bizType!=''">
                and BizType = #{bizType}
            </if>
            <if test="startTime!=null and startTime!=''">
                and trade_date &gt;= #{startTime}
            </if>
            <if test="endTime!=null and endTime!=''">
                and trade_date &lt;= #{endTime}
            </if>
            <if test="likeFiled!=null and likeFiled!=''">
                and PlatformTransId like concat('%',concat(#{likeFiled},'%'))
            </if>
        </where>
        order by trade_date,TradeTime
    </select>

    <!-- 添加一个明确的count查询，避免分页插件的自动生成问题 -->
    <select id="findHisDetailCount" parameterType="HashMap" resultType="long">
        select count(1)
        from hisbill_history
        <where>
            <if test="payType!=null and payType!=''">
                and PayType = #{payType}
            </if>
            <if test="bizType!=null and bizType!=''">
                and BizType = #{bizType}
            </if>
            <if test="startTime!=null and startTime!=''">
                and trade_date &gt;= #{startTime}
            </if>
            <if test="endTime!=null and endTime!=''">
                and trade_date &lt;= #{endTime}
            </if>
            <if test="likeFiled!=null and likeFiled!=''">
                and PlatformTransId like concat('%',concat(#{likeFiled},'%'))
            </if>
        </where>
    </select>

    <!-- 查询有自费金额的HIS账单记录 -->
    <select id="findHisDetailWithZfAmount" parameterType="HashMap" resultType="HashMap">
        select 
            PayMethod,
            TradingStatus,
            BizType,
            PayType,
            TradeTime,
            HisOperCode,
            Amount,
            zfAmount,
            PlatformTransId,
            PatientId,
            PatientName,
            trade_date,
            his_wsdl_id,
            HisTransId,
            clr_type,
            insutype,
            ybzhAmount,
            ybtcAmount
        from hisbill_history
        <where>
            <if test="trade_date!=null and trade_date!=''">
                and trade_date = #{trade_date}
            </if>
            <if test="has_zf_amount!=null and has_zf_amount!=''">
                and zfAmount is not null 
                and zfAmount != '' 
                and zfAmount != '0' 
                and zfAmount != '0.00'
                and ABS(CAST(zfAmount AS DECIMAL(18,2))) > 0
            </if>
        </where>
        order by TradeTime, PlatformTransId
    </select>

    <delete id="deleteHisBillOriginalByParam" parameterType="HashMap">
        delete from hisbill_original where trade_date=#{trade_date}
    </delete>

    <delete id="deleteHisBillOriginalWNByParam" parameterType="HashMap">
        delete from hisbill_original_wn where trade_date=#{trade_date}
    </delete>

    <delete id="deleteHisBillOriginalHYByParam" parameterType="HashMap">
        delete from hisbill_original_hy where trade_date=#{trade_date}
    </delete>

    <delete id="deleteHisBillByParam" parameterType="HashMap">
        delete from hisbill_history where trade_date=#{trade_date}
    </delete>

    <insert id="insertAllHisBillOriginal" parameterType="java.util.List">
        insert into
        hisbill_original(PayMethod,TradingStatus,BizType,PayType,TradeTime,HisOperCode,Amount,remarks,PlatformTransId,PatientId,PatientName,trade_date,his_wsdl_id)
        values
        <foreach collection="list" index="index" item="itm" separator=",">
            (
            #{itm.payMethod},#{itm.tradingStatus},#{itm.bizType},#{itm.payType},#{itm.tradeTime},#{itm.hisOperCode},#{itm.amount},
            #{itm.remarks},#{itm.platformTransId},#{itm.patientId},#{itm.patientName},#{itm.trade_date},#{itm.his_wsdl_id}
            )
        </foreach>
    </insert>

    <insert id="insertAllHisBillOriginalWN" parameterType="java.util.List">
        insert into hisbill_original_wn(sjlx, hzxm, patid, jyje, tyje, zflsh, jyrq, sftkjl, zffs, jylx, czyh,
        trade_date, his_wsdl_id)
        values
        <foreach collection="list" index="index" item="itm" separator=",">
            (
            #{itm.sjlx},#{itm.hzxm},#{itm.patid},#{itm.jyje},#{itm.tyje},#{itm.zflsh},#{itm.jyrq},
            #{itm.sftkjl},#{itm.zffs},#{itm.jylx},#{itm.czyh},#{itm.trade_date},#{itm.his_wsdl_id}
            )
        </foreach>
    </insert>

    <insert id="insertAllHisBillOriginalHY" parameterType="java.util.List">
        insert into
        hisbill_original_hy(VisitzOrg,BizType,PayType,Amount,ZFAmount,YBZHAmount,YBTCAmount,Receipt_no,PatientID,PatientName,TradeTime,HisTime,HisOperNum,PowerTranID,trade_date,clr_type,insutype)
        values
        <foreach collection="list" index="index" item="itm" separator=",">
            (
            #{itm.visitzOrg},#{itm.bizType},#{itm.payType},#{itm.amount},#{itm.zfAmount},#{itm.ybzhAmount},#{itm.ybtcAmount},
            #{itm.receiptNO},#{itm.patientID},#{itm.patientName},#{itm.tradeTime},#{itm.hisTime},#{itm.hisOperNum},#{itm.powerTranID},#{itm.trade_date},
            #{itm.clrType},#{itm.insutype}
            )
        </foreach>
    </insert>

    <insert id="insertAllHisBillHistory" parameterType="java.util.List">
        insert into
        hisbill_history(PayMethod,TradingStatus,BizType,PayType,TradeTime,HisOperCode,Amount,remarks,PlatformTransId,PatientId,PatientName,trade_date,his_wsdl_id,HisTransId,clr_type,insutype,ybzhAmount,ybtcAmount,zfAmount)
        values
        <foreach collection="list" index="index" item="itm" separator=",">
            (
            #{itm.payMethod},#{itm.tradingStatus},#{itm.bizType},#{itm.payType},#{itm.tradeTime},#{itm.hisOperCode},#{itm.amount},#{itm.remarks},#{itm.platformTransId},#{itm.patientId}
            ,#{itm.patientName},#{itm.trade_date},#{itm.his_wsdl_id},#{itm.hisTransId},#{itm.clrType},#{itm.insutype},#{itm.ybzhAmount},#{itm.ybtcAmount},#{itm.zfAmount}
            )
        </foreach>
    </insert>

    <delete id="deleteTempTable">
        delete from temp_hisbill_history
    </delete>

    <insert id="findHisDetailToTemp" parameterType="HashMap">
        insert into temp_hisbill_history
        select a.PayMethod,a.TradingStatus,a.BizType,a.PayType,a.TradeTime,a.HisOperCode,a.Amount,a.remarks,a.PlatformTransId,a.PatientId,a.PatientName,a.trade_date,a.his_wsdl_id
        from hisbill_history a
        left join (select PlatformTransId from hisbill_history where TradingStatus='2' and trade_date=#{trade_date}) b
        on a.PlatformTransId=b.PlatformTransId
        where a.trade_date=#{trade_date} and b.PlatformTransId is null and a.PayType!='5'
    </insert>

    <select id="findHisDetailByParam" parameterType="HashMap" resultType="HashMap">
        select PayMethod
        ,TradingStatus
        ,BizType
        ,PayType
        ,TradeTime
        ,HisOperCode
        ,Amount
        ,remarks
        ,PlatformTransId
        ,PatientId
        ,PatientName
        ,trade_date
        ,his_wsdl_id
        ,HisTransId
        ,clr_type
        ,insutype
        ,ybzhAmount
        ,ybtcAmount
        from hisbill_history
        where trade_date=#{trade_date}
        <if test="payType!=null and payType!=''">
            and PayType = #{payType}
        </if>
        <if test="tradingStatus!=null and tradingStatus!=''">
            and TradingStatus = #{tradingStatus}
        </if>
        <if test="orderby_amount!=null and orderby_amount!=''">
            order by Amount desc
        </if>
    </select>

    <select id="findHisDetailByTimeAndYSDDH" parameterType="HashMap" resultType="HashMap">
        select PayMethod,TradingStatus,BizType,PayType,TradeTime,HisOperCode,Amount,remarks,PlatformTransId,
               PatientId,PatientName,HisTransId,clr_type,insutype,ybzhAmount,ybtcAmount
        from hisbill_history
        where trade_date=#{searchTime}
        and PlatformTransId = #{c_ysddh}
    </select>

    <select id="findHisDetailFirmNumByTime" parameterType="HashMap" resultType="HashMap">
        select his_wsdl_id,count(1) as firmNum
        from hisbill_history
        where TradeTime &gt;= #{startTime}
        and TradeTime &lt;= #{endTime}
        group by his_wsdl_id
    </select>

    <select id="findHisCashDetail" parameterType="HashMap" resultType="HashMap">
        select PayMethod, TradingStatus, BizType, PayType, TradeTime, HisOperCode, Amount, remarks, PlatformTransId, PatientId, PatientName, trade_date, his_wsdl_id, HisTransId, clr_type, insutype, ybzhAmount, ybtcAmount
        from hisbill_history
        where trade_date=#{trade_date} and PayType='5'
    </select>

    <select id="findHisDetailCountData" parameterType="HashMap" resultType="HashMap">
        select count(1) as num,cast(IFNULL(sum(Amount),0) as decimal(19,2)) as money
        from hisbill_history
        <where>
            <if test="payType!=null and payType!=''">
                and (PayType = #{payType} or PayType = CAST(#{payType} AS UNSIGNED))
            </if>
            <if test="startTime!=null and startTime!=''">
                and trade_date &gt;= #{startTime}
            </if>
            <if test="endTime!=null and endTime!=''">
                and trade_date &lt;= #{endTime}
            </if>
            <if test="likeFiled!=null and likeFiled!=''">
                and PlatformTransId like concat('%',concat(#{likeFiled},'%'))
            </if>
        </where>
    </select>

    <!-- 医保对账：按险种和清算类别分组统计（去重规则：HisTransId + ZFAmount 都相同才视为同一记录）
         1. 医疗总金额（MEDFEE_SUMAMT）：统计同一收据号（HisTransId）且同一自费金额（ZFAmount）下的金额，累计统筹 + 非退款账户 + 自费
         2. 统筹金额（FUND_PAY_SUMAMT）：累计统筹金额（不受退款影响）
         3. 账户金额（ACCT_PAY）：累计账户金额（包含退款） -->
    <select id="findMedicalInsuranceGroupData" parameterType="HashMap" resultType="HashMap">
        select
            t.insutype as INSUTYPE,
            t.clr_type as CLR_TYPE,
            count(distinct t.HisTransId) as FIXMEDINS_SETL_CNT,
            cast(
                IFNULL(sum(t.ybtc),0)
                + IFNULL(sum(case when t.is_inpatient = 1 then 0 else t.ybzh_non_refund end),0)
                + IFNULL(sum(t.zf),0)
            as decimal(19,2)) as MEDFEE_SUMAMT,
            cast(IFNULL(sum(t.ybtc),0) as decimal(19,2)) as FUND_PAY_SUMAMT,
            cast(IFNULL(sum(t.ybzh),0) as decimal(19,2)) as ACCT_PAY
        from (
            select
                insutype,
                clr_type,
                HisTransId,
                max(cast(IFNULL(ybtcAmount,0) as decimal(19,2))) as ybtc,
                max(cast(IFNULL(ybzhAmount,0) as decimal(19,2))) as ybzh,
                max(case when TradingStatus != '2' then cast(IFNULL(ybzhAmount,0) as decimal(19,2)) else 0 end) as ybzh_non_refund,
                max(cast(IFNULL(zfAmount,0) as decimal(19,2))) as zf,
                max(case when PayMethod = '2' then 1 else 0 end) as is_inpatient
            from hisbill_history
            where trade_date = #{trade_date}
              and insutype is not null
              and insutype != ''
              and clr_type is not null
              and clr_type != ''
              and HisTransId is not null
              and HisTransId != ''
            group by insutype, clr_type, HisTransId, cast(IFNULL(zfAmount,0) as decimal(19,2))
        ) as t
        group by t.insutype, t.clr_type
        order by t.insutype, t.clr_type
    </select>
</mapper>
