<?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.njzscloud.supervisory.money.mapper.MoneyAccountMapper">

    <!-- 分页查询资金账户（关联用户或企业信息） -->
    <select id="selectMoneyAccountWithName" resultType="com.njzscloud.supervisory.money.pojo.result.MoneyAccountResult">
        SELECT 
            ma.id,
            ma.user_id as userId,
            ma.station_id as stationId,
            ma.money,
            ma.modify_time as modifyTime,
            CASE 
                WHEN ma.user_id IS NOT NULL THEN u.nickname
                WHEN ma.station_id IS NOT NULL THEN bc.company_name
                ELSE NULL
            END as name,
            CASE 
                WHEN ma.user_id IS NOT NULL THEN 1
                WHEN ma.station_id IS NOT NULL THEN 2
                ELSE NULL
            END as moneyType
        FROM money_account ma
        LEFT JOIN sys_user u ON ma.user_id = u.id
        LEFT JOIN biz_company bc ON ma.station_id = bc.id
        <where>
            <if test="entity.name != null and entity.name != ''">
                AND (
                    (ma.user_id IS NOT NULL AND u.nickname LIKE CONCAT('%', #{entity.name}, '%'))
                    OR 
                    (ma.station_id IS NOT NULL AND bc.company_name LIKE CONCAT('%', #{entity.name}, '%'))
                )
            </if>
            <if test="entity.moneyType != null">
                <choose>
                    <when test="entity.moneyType == 1">
                        AND ma.user_id IS NOT NULL
                    </when>
                    <when test="entity.moneyType == 2">
                        AND ma.station_id IS NOT NULL
                    </when>
                </choose>
            </if>
        </where>
        ORDER BY ma.modify_time DESC
    </select>

    <select id="selectMoneyAccountDetailById" resultType="com.njzscloud.supervisory.money.pojo.result.MoneyAccountResult">
        SELECT
            ma.id,
            ma.user_id as userId,
            ma.station_id as stationId,
            ma.money,
            ma.modify_time as modifyTime,
            CASE
                WHEN ma.user_id IS NOT NULL THEN u.nickname
                WHEN ma.station_id IS NOT NULL THEN bc.company_name
                ELSE NULL
                END as name,
            CASE
                WHEN ma.user_id IS NOT NULL THEN 1
                WHEN ma.station_id IS NOT NULL THEN 2
                ELSE NULL
                END as moneyType
        FROM money_account ma
                 LEFT JOIN sys_user u ON ma.user_id = u.id
                 LEFT JOIN biz_company bc ON ma.station_id = bc.id
        WHERE ma.id = #{id}
    </select>

</mapper>