<?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.FinancialReconciliation.MobileYbReconciliationMapper">

    <!-- 银行侧汇总：微信医保账单 -->
    <select id="sumBankMobileYb" parameterType="HashMap" resultType="HashMap">
        SELECT
            CAST(IFNULL(SUM(CAST(MEDFEE_SUMAMT AS DECIMAL(19,2))),0) AS DECIMAL(19,2)) AS bank_medfee,
            CAST(IFNULL(SUM(CAST(ACCT_PAY AS DECIMAL(19,2))),0) AS DECIMAL(19,2)) AS bank_acct_pay,
            CAST(IFNULL(SUM(CAST(FUND_PAY_SUMAMT AS DECIMAL(19,2))),0) AS DECIMAL(19,2)) AS bank_fund_pay
        FROM bankbill_history
        <where>
            <if test="trade_date!=null and trade_date!=''">
                AND C_JYRQ = #{trade_date}
            </if>
            AND (
                bill_table_name = '微信医保账单'
                OR bill_table_name = '微信移动医保账单'
                OR bill_table_name LIKE '%医保%'
                OR bill_table_name IS NULL
            )
        </where>
    </select>

    <!-- HIS 侧汇总：HisOperCode='yb'（微信移动医保） -->
    <select id="sumHisMobileYb" parameterType="HashMap" resultType="HashMap">
        SELECT
            CAST(IFNULL(SUM(CAST(MEDFEE_SUMAMT AS DECIMAL(19,2))),0) AS DECIMAL(19,2)) AS his_medfee,
            CAST(IFNULL(SUM(CAST(ACCT_PAY AS DECIMAL(19,2))),0) AS DECIMAL(19,2)) AS his_acct_pay,
            CAST(IFNULL(SUM(CAST(FUND_PAY_SUMAMT AS DECIMAL(19,2))),0) AS DECIMAL(19,2)) AS his_fund_pay
        FROM hisbill_history
        <where>
            <if test="trade_date!=null and trade_date!=''">
                AND trade_date = #{trade_date}
            </if>
            AND HisOperCode = 'yb'
        </where>
    </select>

    <!-- 结果表：mobile_yb_reconciliation_result -->
    <insert id="insertResult" parameterType="HashMap">
        INSERT INTO mobile_yb_reconciliation_result
        (id, trade_date,
         bank_medfee, bank_acct_pay, bank_fund_pay,
         his_medfee,  his_acct_pay,  his_fund_pay,
         diff_medfee, diff_acct_pay, diff_fund_pay,
         stmt_rslt, stmt_rslt_dscr, create_time, modify_time)
        VALUES
        (#{id}, #{trade_date},
         #{bank_medfee}, #{bank_acct_pay}, #{bank_fund_pay},
         #{his_medfee}, #{his_acct_pay}, #{his_fund_pay},
         #{diff_medfee}, #{diff_acct_pay}, #{diff_fund_pay},
         #{stmt_rslt}, #{stmt_rslt_dscr}, now(), now())
    </insert>

    <delete id="deleteResultByDate" parameterType="HashMap">
        DELETE FROM mobile_yb_reconciliation_result
        WHERE trade_date = #{trade_date}
    </delete>

    <select id="findResultByDate" parameterType="HashMap" resultType="HashMap">
        SELECT *
        FROM mobile_yb_reconciliation_result
        WHERE trade_date = #{trade_date}
        LIMIT 1
    </select>

</mapper>

