<?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="shop.alien.mapper.SubAccountStoreMapper">

    <!-- 根据用户ID查询子账号关联的门店列表（包含主账号的门店） -->
    <select id="selectSubAccountStoreListByUserId" resultType="shop.alien.entity.store.vo.SubAccountStoreListVo">
        -- 查询子账号通过store_platform_user_role关联的门店
        SELECT
            si.id AS storeId,
            si.store_name COLLATE utf8mb4_unicode_ci AS storeName,
            si.store_address COLLATE utf8mb4_unicode_ci AS storeAddress,
            si.store_tel COLLATE utf8mb4_unicode_ci AS storeTel,
            si.business_status AS businessStatus,
            spur.role_id AS roleId,
            spr.role_name COLLATE utf8mb4_unicode_ci AS roleName,
            spur.user_id AS userId,
            spur.account_name COLLATE utf8mb4_unicode_ci AS accountName,
            su.phone COLLATE utf8mb4_unicode_ci AS phone
        FROM
            store_platform_user_role spur
        INNER JOIN store_user su ON spur.user_id = su.id
        INNER JOIN store_info si ON spur.store_id = si.id
        LEFT JOIN store_platform_role spr ON spur.role_id = spr.role_id 
            AND (spr.del_flag = '0' OR spr.del_flag IS NULL)
        WHERE
            spur.user_id = #{userId}
            AND spur.delete_flag = 0
            AND su.delete_flag = 0
            AND si.delete_flag = 0
        
        UNION
        
        -- 查询主账号的门店（通过store_user.store_id关联）
        SELECT
            si_main.id AS storeId,
            si_main.store_name COLLATE utf8mb4_unicode_ci AS storeName,
            si_main.store_address COLLATE utf8mb4_unicode_ci AS storeAddress,
            si_main.store_tel COLLATE utf8mb4_unicode_ci AS storeTel,
            si_main.business_status AS businessStatus,
            NULL AS roleId,
            NULL AS roleName,
            su_main.id AS userId,
            su_main.name COLLATE utf8mb4_unicode_ci AS accountName,
            su_main.phone COLLATE utf8mb4_unicode_ci AS phone
        FROM
            store_user su_main
        INNER JOIN store_info si_main ON su_main.store_id = si_main.id
        WHERE
            (
                -- 如果传入的是子账号，查询其主账号的门店
                (su_main.id = (SELECT sub_account_id FROM store_user WHERE id = #{userId} AND account_type = 2 AND delete_flag = 0 LIMIT 1))
                OR
                -- 如果传入的是主账号，查询自己的门店
                (su_main.id = #{userId} AND su_main.account_type = 1)
            )
            AND su_main.delete_flag = 0
            AND si_main.delete_flag = 0
            AND su_main.store_id IS NOT NULL
        
        ORDER BY storeId DESC
    </select>

</mapper>
