<?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="cn.iocoder.yudao.module.system.dal.mysql.biz.ExpenseOrderMapper">

    <!--
        一般情况下，尽可能使用 Mapper 进行 CRUD 增删改查即可。
        无法满足的场景，例如说多表关联查询，才使用 XML 编写 SQL。
        代码生成器暂时只生成 Mapper XML 文件本身，更多推荐 MybatisX 快速开发插件来生成查询。
        文档可见：https://www.iocoder.cn/MyBatis/x-plugins/
     -->
    <select id="getExpenseBillPage"
            resultType="cn.iocoder.yudao.module.system.dal.dataobject.biz.ExpenseOrderDO">
        SELECT
        eeb.*,
        ei.elder_name,
        CASE
        WHEN eeb.pay_status = 0 THEN 0  -- 未缴账单优先
        ELSE 1
        END as pay_priority,
        CASE
        WHEN eeb.pay_status = 0 THEN eeb.billing_month
        ELSE NULL
        END as unpaid_month
        FROM elderly_expense_order eeb
        LEFT JOIN elderly_info ei ON ei.id = eeb.elder_id
        WHERE eeb.is_show = 1
        <if test="params.elderName != null and params.elderName != '' ">
            and ei.elder_name like concat('%',#{params.elderName} ,'%')
        </if>
        <if test="params.isPushKingdeeReceiveBill != null and params.isPushKingdeeReceiveBill != ''">
            and eeb.is_push_kingdee_receive_bill = #{params.isPushKingdeeReceiveBill}
        </if>
        <if test="params.bedId != null">
            and ei.bed_id = #{params.bedId}
        </if>
        <if test="params.payStatus != null">
            and eeb.pay_status = #{params.payStatus}
        </if>
        <if test="params.attributionBillTime != null and params.attributionBillTime != ''">
            and eeb.billing_month = #{params.attributionBillTime}
        </if>
        <if test="params.type != null">
            and eeb.type = #{params.type}
        </if>
        <if test="params.payTime != null">
            and eeb.pay_time between #{params.payTime[0]} and #{params.payTime[1]}
        </if>
        <if test="params.orgType != null">
            and ei.org_type = #{params.orgType}
        </if>
        <if test="params.tenantIds != null">
            and ei.tenant_id in
            <foreach item="id" collection="params.tenantIds" open="(" separator="," close=")">
                #{id}
            </foreach>
        </if>
        ORDER BY
        pay_priority ASC,  -- 未缴账单优先
        unpaid_month ASC,  -- 未缴账单按月份升序排列
        eeb.created_time DESC
    </select>

    <select id="selectListByMonth" resultType="cn.iocoder.yudao.module.system.api.order.DTO.OrderItemRespDTO">
        SELECT
            ei.id,
            ei.elder_name,
            ei.elder_sex,
            ei.elder_age,
            ei.address,
            ei.in_status,
            ei.check_in_time,
            ei.check_out_time,
            ei.nurse_level_name,
            ei.care_type AS 'careType',

            eeo.id AS 'orderId',
            eeo.pay_status,
            eeo.payable_amount,
            eeo.actual_amount,
            eeo.billing_month,
            eeo.arrears_note,
            eeo.type AS 'orderType',

            ec.contract_number,
            ec.begin_time,
            ec.expire_time,
            ec.contract_term,

            eei.item_name,
            ob.build_name,
            obb.bed_name,
            eesa.amount AS 'expenseSubsidyBalance',
            eb.amount AS 'virtualBalance',
            ei.org_type,
            ei.tenant_id
        FROM
            elderly_info ei
                INNER JOIN elderly_contract ec ON ei.id = ec.elder_id
                    AND ec.status = 1
                INNER JOIN elderly_expense_order eeo ON ei.id = eeo.elder_id

                INNER JOIN elderly_expense ee ON ei.id = ee.elder_id
                INNER JOIN elderly_expense_item eei ON eei.expense_id = ee.id
                INNER JOIN sys_charge_category scc ON scc.id = eei.item_category_id

                LEFT JOIN org_build ob ON ob.id = ei.build_id
                LEFT JOIN org_build_bed obb ON ei.bed_id = obb.id
                LEFT JOIN elderly_expense_subsidy_account eesa ON eesa.elder_id = ei.id
                LEFT JOIN elderly_balance eb ON eb.elder_id = ei.id

        WHERE scc.identification = 1
          <if test="billMonth != null">
              AND eeo.billing_month = #{billMonth}
          </if>
        <if test="orgType != null">
            AND ei.org_type = #{orgType}
        </if>
        <if test="tenantId != null">
            AND ei.tenant_id = #{tenantId}
        </if>
        <if test="inStatus != null">
              AND ei.in_status = #{inStatus}
        </if>
        <if test="payStatus != null">
            AND eeo.pay_status = #{payStatus}
        </if>
          AND ee.created_time = (SELECT MAX(ee2.created_time) FROM elderly_expense ee2 WHERE ee2.elder_id = ei.id)
        ORDER BY ee.created_time DESC
    </select>

    <select id="countLastInByMonth" resultType="java.lang.Integer">
        SELECT COUNT(DISTINCT eeo.elder_id)
        FROM elderly_expense_order eeo
        LEFT JOIN elderly_info ei ON ei.id = eeo.elder_id
        WHERE 1 = 1
          AND eeo.billing_month = #{billMonth}
          <if test="orgType != null">
              AND eeo.org_type = #{orgType}
          </if>
          <if test="tenantId != null">
              AND eeo.tenant_id = #{tenantId}
          </if>
          <if test="payStatus != null">
              AND eeo.pay_status = #{payStatus}
          </if>
          AND (
                ei.in_status = 1
                OR (
                    ei.in_status = 2
                    AND ei.check_out_time IS NOT NULL
                    AND DATE_FORMAT(ei.check_out_time, '%Y-%m') <![CDATA[ > ]]> #{billMonth}
                )
                OR (
                    ei.check_in_time IS NOT NULL
                    AND DATE_FORMAT(ei.check_in_time, '%Y-%m') = #{billMonth}
                )
          )
    </select>

</mapper>
