<?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.cordys.crm.system.mapper.ExtOrganizationUserMapper">

    <sql id="combine">
        <if test="${combineSearch} != null and ${combineSearch}.conditions != null and ${combineSearch}.conditions.size() > 0">
            <trim prefix="and">
                <trim prefix="(" suffix=")" suffixOverrides="and|or">
                    <foreach collection="${combineSearch}.conditions" index="i" item="condition">
                        <include refid="condition">
                            <property name="condition" value="condition"/>
                            <property name="fieldTable" value="combine_${i}.field_value"/>
                            <property name="table" value="combine_${i}"/>
                        </include>
                        <include refid="cn.cordys.common.mapper.CommonMapper.searchMode">
                            <property name="searchMode" value="${combineSearch}.searchMode"/>
                        </include>
                    </foreach>
                </trim>
            </trim>
        </if>
    </sql>


    <select id="countUserByDepartmentIds" resultType="java.lang.Integer">
        select count(user_id)
        from sys_organization_user
        where department_id in
        <foreach collection="departmentIds" item="departmentId" index="index" open="(" close=")" separator=",">
            #{departmentId}
        </foreach>
        and organization_id = #{orgId}
    </select>

    <select id="list" resultType="cn.cordys.crm.system.dto.response.UserPageResponse">
        SELECT
        sou.id,
        sou.user_id,
        sou.organization_id,
        sou.department_id,
        su.name userName,
        sou.`enable`,
        su.gender,
        su.phone,
        su.email,
        sou.supervisor_id,
        sou.employee_id,
        sou.position,
        sou.employee_type,
        sou.work_city,
        sou.create_time,
        sou.update_time,
        sou.create_user,
        sou.update_user,
        sou.onboarding_date,
        sou.position
        FROM
        sys_organization_user sou
        INNER JOIN sys_user su ON sou.user_id = su.id
        left JOIN (
        SELECT
        user_id,
        1 AS is_commander
        FROM
        sys_department_commander
        GROUP BY user_id
        ) uc ON su.id = uc.user_id
        LEFT JOIN sys_user su_create ON sou.create_user = su_create.id
        LEFT JOIN sys_user su_update ON sou.update_user = su_update.id
        where sou.department_id in
        <foreach collection="request.departmentIds" item="departmentId" open="(" separator="," close=")">
            #{departmentId}
        </foreach>
        <if test="request.keyword != null and request.keyword != ''">
            and (
            su.name like concat('%', #{request.keyword},'%')
            or su.phone like concat('%', #{request.keyword},'%')
            )
        </if>
        <include refid="filters">
            <property name="filters" value="request.filters"/>
        </include>
        <include refid="combine">
            <property name="combineSearch" value="request.combineSearch"/>
        </include>
        <include refid="sorts">
            <property name="sort" value="request.sort"/>
        </include>
    </select>

    <sql id="sorts">
        <choose>
            <when test="${sort} != null and ${sort}.valid() > 0">
                <bind name="sortName" value="${sort}.name"/>
                <bind name="sortType" value="${sort}.type"/>
                order by
                <choose>
                    <when test="sortName == 'user_name'">
                        su.name ${sortType},
                    </when>
                    <when test="sortName == 'work_city_name'">
                        sou.work_city ${sortType},
                    </when>
                    <otherwise>
                        sou.${sortName} ${sortType},
                    </otherwise>
                </choose>
                sou.enable DESC,
                ${orderByClause},
                is_commander DESC,
                sou.create_time DESC,
                su.name DESC
            </when>
            <otherwise>
                order by
                sou.enable DESC,
                ${orderByClause},
                is_commander DESC,
                sou.create_time DESC,
                su.name DESC
            </otherwise>
        </choose>
    </sql>

    <sql id="filters">
        <if test="${filters} != null and ${filters}.size() > 0">
            <trim prefix="and">
                <foreach collection="${filters}" item="condition" open="(" close=")" index="i" separator="and">
                    <include refid="condition">
                        <property name="condition" value="condition"/>
                        <property name="fieldTable" value="filter_${i}.field_value"/>
                    </include>
                </foreach>
            </trim>
        </if>
    </sql>


    <sql id="condition">
        <choose>
            <when test="condition.name == 'userName'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="su.name"/>
                </include>
            </when>
            <when test="condition.name == 'status'">
                <if test="condition.operator == 'IN'">
                    <if test="condition.value == true">
                        sou.enable is true
                    </if>
                    <if test="condition.value == false">
                        sou.enable is false
                    </if>
                </if>
                <if test="condition.operator == 'NOT_IN'">
                    <if test="condition.value == true">
                        sou.enable is false
                    </if>
                    <if test="condition.value == false">
                        sou.enable is true
                    </if>
                </if>
                <if test="condition.operator == 'EMPTY'">
                    sou.enable IS NULL
                </if>
                <if test="condition.operator == 'NOT_EMPTY'">
                    sou.enable IS NOT NULL
                </if>
            </when>
            <when test="condition.name == 'gender'
                and (condition.value == 'female' or condition.value == 'male'
                or condition.operator == 'EMPTY' or condition.operator == 'NOT_EMPTY')">
                <if test="condition.operator == 'IN'">
                    <if test="condition.value == 'female'">
                        su.gender is true
                    </if>
                    <if test="condition.value == 'male'">
                        su.gender is false
                    </if>

                </if>
                <if test="condition.operator == 'NOT_IN'">
                    <if test="condition.value == 'female'">
                        su.gender is false
                    </if>
                    <if test="condition.value == 'male'">
                        su.gender is true
                    </if>
                </if>
                <if test="condition.operator == 'EMPTY'">
                    su.gender IS NULL
                </if>
                <if test="condition.operator == 'NOT_EMPTY'">
                    su.gender IS NOT NULL
                </if>
            </when>
            <when test="condition.name == 'email'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="su.email"/>
                </include>
            </when>
            <when test="condition.name == 'phoneNumber'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="su.phone"/>
                </include>
            </when>
            <when test="condition.name == 'supervisorId'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.supervisor_id"/>
                </include>
            </when>
            <when test="condition.name == 'departmentId'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.department_id"/>
                </include>
            </when>
            <when test="condition.name == 'employeeId'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.employee_id"/>
                </include>
            </when>
            <when test="condition.name == 'employeeType'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.employee_type"/>
                </include>
            </when>
            <when test="condition.name == 'updateUser'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.update_user"/>
                </include>
            </when>
            <when test="condition.name == 'createUser'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.create_user"/>
                </include>
            </when>
            <when test="condition.name == 'onboardingDate'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.onboarding_date"/>
                </include>
            </when>
            <when test="condition.name == 'createTime'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.create_time"/>
                </include>
            </when>
            <when test="condition.name == 'updateTime'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.update_time"/>
                </include>
            </when>
            <when test="condition.name == 'workCity'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.work_city"/>
                </include>
            </when>
            <when test="condition.name == 'positionId'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.position"/>
                </include>
            </when>
            <when test="condition.name == 'enable'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="sou.enable"/>
                </include>
            </when>
            <when test="condition.name == 'gender'">
                <include refid="cn.cordys.common.mapper.CommonMapper.condition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="su.gender"/>
                </include>
            </when>
            <otherwise>
                <include refid="cn.cordys.common.mapper.CommonMapper.moduleFieldCondition">
                    <property name="condition" value="condition"/>
                    <property name="column" value="${fieldTable}"/>
                </include>
            </otherwise>
        </choose>
    </sql>

    <update id="enable">
        update sys_organization_user
        set `enable` = #{request.enable},
        update_time = UNIX_TIMESTAMP() * 1000,
        update_user = #{operatorId}
        where id in
        <foreach collection="request.ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </update>

    <select id="getUserList" resultType="cn.cordys.crm.system.domain.User">
        SELECT
        su.id,
        su.name,
        su.phone,
        su.password
        from sys_user su
        inner join sys_organization_user sou on su.id = sou.user_id
        where sou.id in
        <foreach collection="request.ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
        and phone is not null and
        <![CDATA[ phone <> '' ]]>
    </select>

    <select id="getEnableUser" resultType="cn.cordys.security.UserDTO">
        SELECT su.id,
               su.name,
               su.email,
               su.phone,
               su.password,
               sou.enable
        from sys_user su
                 inner join sys_organization_user sou on su.id = sou.user_id
        where sou.resource_user_id = #{resourceUserId}
    </select>

    <delete id="deleteUserByOrgId">
        DELETE
        FROM sys_organization_user
        WHERE organization_id = #{orgId}
    </delete>

    <select id="selectEnableOrgUser" resultType="cn.cordys.common.dto.OptionDTO">
        SELECT
        su.id,
        su.name
        from sys_user su
        inner join sys_organization_user sou on su.id = sou.user_id
        where sou.id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>

    <update id="updateUserByIds">
        update sys_organization_user
        <set>
            <if test="request.departmentId != null">
                department_id = #{request.departmentId},
            </if>
            <if test="request.supervisorId != null">
                supervisor_id = #{request.supervisorId},
            </if>
            <if test="request.workCity != null">
                work_city = #{request.workCity},
            </if>
            <if test="request.onboardingDate != null">
                onboarding_date = #{request.onboardingDate},
            </if>
            update_time = UNIX_TIMESTAMP() * 1000,
            update_user = #{operatorId}
        </set>
        <where>
            id in
            <foreach collection="request.ids" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </where>
    </update>


    <select id="selectSupervisor" resultType="cn.cordys.crm.system.dto.response.UserImportDTO">
        select user_id, department_id, name
        from sys_organization_user sou
        INNER JOIN sys_user su on sou.user_id = su.id
        where sou.organization_id = #{orgId}
        and su.name in
        <foreach collection="nameList" item="name" open="(" separator="," close=")">
            #{name}
        </foreach>
    </select>

    <select id="getUserByOrgId" resultType="cn.cordys.crm.system.domain.OrganizationUser">
        select *
        from sys_organization_user
        where organization_id = #{orgId}
    </select>

    <select id="getOrgUserIdByUserId" resultType="java.lang.String">
        select id
        from sys_organization_user
        where organization_id = #{orgId}
          and user_id = #{userId}
    </select>

    <update id="updateOrganizationUser" parameterType="cn.cordys.crm.system.domain.OrganizationUser">
        update sys_organization_user
        <set>
            <if test="organizationUser.organizationId != null">
                organization_id = #{organizationUser.organizationId},
            </if>
            <if test="organizationUser.departmentId != null">
                department_id = #{organizationUser.departmentId},
            </if>
            <if test="organizationUser.resourceUserId != null">
                resource_user_id = #{organizationUser.resourceUserId},
            </if>
            <if test="organizationUser.userId != null">
                user_id = #{organizationUser.userId},
            </if>
            <if test="organizationUser.enable != null">
                `enable` = #{organizationUser.enable},
            </if>
            <if test="organizationUser.employeeId != null">
                employee_id = #{organizationUser.employeeId},
            </if>
            <if test="organizationUser.position != null">
                `position` = #{organizationUser.position},
            </if>
            <if test="organizationUser.employeeType != null">
                employee_type = #{organizationUser.employeeType},
            </if>
            <if test="organizationUser.supervisorId != null">
                supervisor_id = #{organizationUser.supervisorId},
            </if>
            <if test="organizationUser.workCity != null">
                work_city = #{organizationUser.workCity},
            </if>
            <if test="organizationUser.createTime != null">
                create_time = #{organizationUser.createTime},
            </if>
            <if test="organizationUser.updateTime != null">
                update_time = #{organizationUser.updateTime},
            </if>
            <if test="organizationUser.createUser != null">
                create_user = #{organizationUser.createUser},
            </if>
            <if test="organizationUser.updateUser != null">
                update_user = #{organizationUser.updateUser},
            </if>
        </set>
        where id = #{organizationUser.id}
    </update>

    <delete id="deleteUserByIds">
        DELETE FROM sys_organization_user WHERE id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>


    <select id="selectUserByUserIds" resultType="cn.cordys.crm.system.domain.OrganizationUser">
        select id,user_id,department_id from sys_organization_user
        where user_id in
        <foreach collection="userIds" item="userId" open="(" separator="," close=")">
            #{userId}
        </foreach>
    </select>


    <select id="getUserDepAndPhoneByUserIds" resultType="cn.cordys.crm.system.dto.response.UserResponse">
        SELECT
        su.id as userId,
        su.phone,
        sou.department_id as departmentId,
        sd.NAME AS departmentName
        FROM
        sys_user su
        INNER JOIN sys_organization_user sou on su.id = sou.user_id
        INNER JOIN sys_department sd on sd.id = sou.department_id
        where
        sou.organization_id = #{orgId}
        and su.id in
        <foreach collection="userIds" item="userId" open="(" separator="," close=")">
            #{userId}
        </foreach>
    </select>

    <select id="selectByIds" resultType="cn.cordys.crm.system.dto.response.UserResponse">
        select su.name as userName, sou.user_id, sou.department_id, sou.supervisor_id, sou.work_city, sou.onboarding_date
        from sys_organization_user sou
        inner join sys_user su on sou.user_id = su.id
        where sou.id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>


    <update id="updateById" parameterType="cn.cordys.crm.system.domain.OrganizationUser">
        update sys_organization_user
        set department_id   = #{organizationUser.departmentId},
            `enable`        = #{organizationUser.enable},
            employee_id     = #{organizationUser.employeeId},
            `position`      = #{organizationUser.position},
            employee_type   = #{organizationUser.employeeType},
            supervisor_id   = #{organizationUser.supervisorId},
            work_city       = #{organizationUser.workCity},
            update_time     = #{organizationUser.updateTime},
            update_user     = #{organizationUser.updateUser},
            onboarding_date = #{organizationUser.onboardingDate}
        where id = #{organizationUser.id}
    </update>


    <update id="disableUser" parameterType="cn.cordys.crm.system.domain.OrganizationUser">
        update sys_organization_user
        set enable = 0
        where id = #{organizationUser.id}
    </update>


    <update id="updateUserByUserId">
        update sys_organization_user
        set update_time = #{time},
            update_user = #{operatorId}
        where user_id = #{userId}
    </update>


    <select id="getDepartmentByUserId" resultType="java.lang.String">
        select department_id
        from sys_organization_user
        where user_id = #{userId} limit 1
    </select>
</mapper>