<?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.ezhizao.project.tenant.mapper.BizTenantMapper">
    <resultMap type="BizTenant" id="TenantResult">
        <id column="id" property="id"/>
        <result column="industry_category" property="industryCategory"/>
        <result column="industry_specific" property="industrySpecific"/>
        <association property="industryCategoryStr" javaType="java.lang.String" column="industry_category"  select="getIndustryCategoryStr"  />
        <association property="industrySpecificStr" javaType="java.lang.String" column="industry_specific"  select="getIndustrySpecificStr"  />
    </resultMap>

    <select id="getIndustryCategoryStr" resultType="java.lang.String">
        SELECT value FROM biz_dict WHERE deleted = 0 AND `key`= 'INDUSTRY_CATEGORY' AND code = #{industry_category};
    </select>

    <select id="getIndustrySpecificStr" resultType="java.lang.String">
        SELECT value FROM biz_dict WHERE deleted = 0 AND `key`= 'INDUSTRY_SPECIFIC' AND code = #{industry_specific};
    </select>

    <select id="getList" parameterType="BizTenant" resultMap="TenantResult">
        SELECT *
        <if test="operateType != null  and operateType != ''">
            <choose>
                <when test="operateType == 'join'">
                    ,(SELECT id FROM biz_tenant_apply WHERE deleted = 0 AND tenant_id = biz_tenant.id AND  user_id = #{userId}) AS apply_id,
                     (SELECT status FROM biz_tenant_apply WHERE deleted = 0 AND tenant_id = biz_tenant.id AND  user_id = #{userId}) AS apply_status
                </when>
            </choose>
        </if>
        FROM biz_tenant
        <trim prefix=" WHERE" suffix="" suffixOverrides="AND">
            deleted = 0
            <if test="id != null"> AND id = #{id}</if>
            <if test="orgName != null  and orgName != ''"> AND org_name like concat('%', #{orgName}, '%')</if>
            <if test="userName != null "> AND id IN (SELECT tenant_id FROM biz_user_tenant WHERE deleted = 0 AND user_id = ( SELECT user_id FROM sys_user WHERE del_flag = 0 AND user_name = #{userName}) )</if>
            <if test="operateType != null  and operateType != ''">
                <choose>
                    <when test="operateType == 'join'">
                    AND id NOT IN (SELECT tenant_id FROM biz_user_tenant WHERE deleted = 0  AND user_id = #{userId})
                    </when>
                    <when test="operateType == 'change'">
                    AND id IN (SELECT tenant_id FROM biz_user_tenant WHERE deleted = 0  AND user_id = #{userId})
                    </when>
                </choose>
            </if>
        </trim>
    </select>
</mapper>
