<?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.ym.mec.biz.dal.dao.EmployeeDao">

    <resultMap type="com.ym.mec.biz.dal.entity.Employee" id="Employee">
        <result column="user_id_" property="userId"/>
        <result column="organ_id_list_" property="organIdList"/>
        <result column="job_nature_" property="jobNature"/>
        <result column="is_probation_period_" property="isProbationPeriod"/>
        <result column="education_background_" property="educationBackground"/>
        <result column="graduate_school_" property="graduateSchool"/>
        <result column="technical_titles_" property="technicalTitles"/>
        <result column="entry_date_" property="entryDate"/>
        <result column="certificate_type_" property="certificateType"/>
        <result column="certificate_num_" property="certificateNum"/>
        <result column="update_time_" property="updateTime"/>
        <result column="create_time_" property="createTime"/>
        <result column="introduction_" property="introduction"/>
        <result column="demission_date_" property="demissionDate"/>
        <result column="contact_address_" property="contactAddress"/>
        <result column="postal_code_" property="postalCode"/>
        <result column="dept_id_" property="deptId"/>
        <result column="dept_ids_" property="deptIds"/>
        <result column="post_ids_" property="postIds"/>
        <result column="post_dept_ids_" property="postDeptIds"/>
        <result column="bank_card_" property="bankCard"/>
        <result column="open_bank_address_" property="openBankAddress"/>
		<result column="tenant_id_" property="tenantId" />
    </resultMap>

    <resultMap type="com.ym.mec.auth.api.entity.SysUser" id="SysUser">
        <result column="id_" property="id"/>
        <result column="username_" property="username"/>
        <result column="password_" property="password"/>
        <result column="salt_" property="salt"/>
        <result column="phone_" property="phone"/>
        <result column="avatar_" property="avatar"/>
        <result column="organ_id_" property="organId"/>
        <result column="create_time_" property="createTime"/>
        <result column="update_time_" property="updateTime"/>
        <result column="lock_flag_" property="lockFlag"/>
        <result column="del_flag_" property="delFlag" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result column="wx_openid_" property="wxOpenid"/>
        <result column="qq_openid_" property="qqOpenid"/>
        <result column="user_type_" property="userType"/>
        <result column="gender_" property="gender"/>
        <result column="nation_" property="nation"/>
        <result column="birthdate_" property="birthdate"/>
        <result column="email_" property="email"/>
        <result column="im_token_" property="imToken"/>
        <result column="real_name_" property="realName"/>
        <result column="id_card_no_" property="idCardNo"/>
        <result column="wechat_id_" property="wechatId"/>
    </resultMap>

    <!-- 根据主键查询一条记录 -->
    <select id="get" resultMap="Employee">
		SELECT * FROM employee WHERE user_id_ = #{userId}
	</select>

    <!-- 全查询 -->
    <select id="findAll" resultMap="Employee">
		SELECT * FROM employee where tenant_id_ = #{tenantId} ORDER BY user_id_
	</select>

    <!-- 向数据库增加一条记录 -->
    <insert id="insert" parameterType="com.ym.mec.biz.dal.entity.Employee" useGeneratedKeys="true" keyColumn="id"
            keyProperty="id">
        INSERT INTO employee
        (user_id_,organ_id_list_,job_nature_,is_probation_period_,education_background_,graduate_school_,technical_titles_,
        entry_date_,certificate_type_,certificate_num_,update_time_,create_time_,introduction_,demission_date_,contact_address_,postal_code_,dept_id_,dept_ids_,post_ids_,post_dept_ids_,tenant_id_)
        VALUES(#{userId},#{organIdList},#{jobNature},#{isProbationPeriod},#{educationBackground},#{graduateSchool},
        #{technicalTitles},#{entryDate},#{certificateType},#{certificateNum},now(),now(),#{introduction},#{demissionDate},#{contactAddress},#{postalCode},#{deptId},#{deptIds},#{postIds},#{postDeptIds},#{tenantId})
    </insert>

    <insert id="batchAddEmployeeRole">
        INSERT INTO sys_user_role(user_id_,role_id_,tenant_id_) values
        <foreach collection="roleIds" item="item" index="index" separator=",">
            (#{userId},#{item},#{tenantId})
        </foreach>
    </insert>

    <insert id="batchInsertRoleMenu">
        INSERT INTO sys_role_menu (role_id_,menu_id_,tenant_id_) VALUES
        <foreach collection="menuIds" item="item" index="index" separator=",">
            (#{roleId}, #{item},#{tenantId})
        </foreach>
    </insert>

    <delete id="delRoleMenu">
        DELETE FROM `sys_role_menu`
        WHERE  tenant_id_ = #{tenantId}
        and menu_id_ in
        <foreach collection="menuIds" open="(" close=")" item="item" separator=",">
            #{item}
        </foreach>
    </delete>

    <insert id="insertSysRole" keyColumn="id_" keyProperty="id" parameterType="com.ym.mec.auth.api.entity.SysRole"
            useGeneratedKeys="true">
        INSERT INTO `sys_role` (`role_name_`, `role_code_`, `role_desc_`, `create_time_`,
                                `update_time_`, `del_flag_`, `organ_id_`, `tenant_id_`)
        VALUES (#{roleName}, #{roleCode}, #{roleDesc}, #{createTime},
                #{updateTime}, #{delFlag}, #{organId}, #{tenantId});
    </insert>

    <select id="queryByPhone" resultMap="SysUser">
		select * from sys_user where phone_ = #{phone} OR username_ = #{phone}
	</select>

    <!-- 根据主键查询一条记录 -->
    <update id="update" parameterType="com.ym.mec.biz.dal.entity.Employee">
        UPDATE employee
        <set>
            <if test="contactAddress != null">
                contact_address_ = #{contactAddress},
            </if>
            <if test="postalCode != null">
                postal_code_ = #{postalCode},
            </if>
            <if test="isProbationPeriod != null">
                is_probation_period_ = #{isProbationPeriod},
            </if>
            <if test="graduateSchool != null">
                graduate_school_ = #{graduateSchool},
            </if>
            <if test="organIdList != null">
                organ_id_list_ = #{organIdList},
            </if>
            <if test="introduction != null">
                introduction_ = #{introduction},
            </if>
            <if test="technicalTitles != null">
                technical_titles_ = #{technicalTitles},
            </if>
            <if test="entryDate != null">
                entry_date_ = #{entryDate},
            </if>
            <if test="jobNature != null">
                job_nature_ = #{jobNature},
            </if>
            <if test="certificateType != null">
                certificate_type_ = #{certificateType},
            </if>
            <if test="updateTime != null">
                update_time_ = NOW(),
            </if>
            <if test="educationBackground != null">
                education_background_ = #{educationBackground},
            </if>
            <if test="certificateNum != null">
                certificate_num_ = #{certificateNum},
            </if>
            <if test="demissionDate != null">
                demission_date_ = #{demissionDate},
            </if>
                dept_id_ = #{deptId},
            <if test="deptIds != null">
                dept_ids_ = #{deptIds},
            </if>
            <if test="postIds != null">
                post_ids_ = #{postIds},
            </if>
            <if test="postDeptIds != null">
                post_dept_ids_ = #{postDeptIds},
            </if>
        </set>
        WHERE user_id_ = #{userId} and tenant_id_ = #{tenantId}
    </update>

    <update id="updatePassword">
        UPDATE sys_user SET password_ = #{password} WHERE id_ = #{userID}
    </update>

    <update id="updateUserLockStatus">
		UPDATE sys_user SET lock_flag_ = IF(lock_flag_=0,1,0) WHERE id_=#{userID}
	</update>
    <update id="updateUserDemissionDate">
        UPDATE employee SET demission_date_ = IF(demission_date_ IS NULL,now(),NULL) WHERE user_id_=#{userID}
    </update>
    <update id="updateUserLock">
        UPDATE sys_user SET lock_flag_ = #{status} WHERE id_=#{userID}
    </update>

    <update id="updateEducationTeacherId">
        UPDATE music_group SET educational_teacher_id_ = #{targetUserId} WHERE educational_teacher_id_ = #{currentUserId} AND status_ != 'CANCELED';
        UPDATE vip_group SET educational_teacher_id_ = #{targetUserId} WHERE educational_teacher_id_ = #{currentUserId} AND group_status_ IN (0,1,5,2,6,4);
        UPDATE practice_group SET educational_teacher_id_ = #{targetUserId} WHERE educational_teacher_id_ = #{currentUserId} AND group_status_ != 'CANCEL';
    </update>

    <!-- 根据主键删除一条记录 -->
    <delete id="delete">
		DELETE FROM employee WHERE user_id_ = #{userId}
	</delete>
    <delete id="delEmployeeRole">
        DELETE FROM sys_user_role WHERE user_id_ = #{userId}
    </delete>

    <!-- 分页查询 -->
    <select id="queryPage" resultMap="Employee" parameterType="map">
        SELECT * FROM employee where tenant_id_ = #{tenantId} ORDER BY user_id_
        <include refid="global.limit"/>
    </select>

    <!-- 查询当前表的总记录数 -->
    <select id="queryCount" resultType="int">
		SELECT COUNT(*) FROM employee where tenant_id_ = #{tenantId}
	</select>


    <resultMap type="com.ym.mec.biz.dal.dto.EmployeeDto" id="EmployeeDto">
        <result property="id" column="user_id_"/>
        <result property="realName" column="real_name_"/>
        <result property="gender" column="gender_" typeHandler="com.ym.mec.common.dal.CustomEnumTypeHandler"/>
        <result property="phone" column="phone_"/>
        <result property="lockFlag" column="lock_flag_"/>
        <result property="jobNature" column="job_nature_"/>
        <result property="entryDate" column="entry_date_"/>
        <result property="demissionDate" column="demission_date_"/>
        <result property="contactAddress" column="contact_address_"/>
        <result property="postalCode" column="postal_code_"/>
        <result property="organIdStr" column="organ_id_str_"/>
        <result property="deptId" column="dept_id_"/>
        <result property="deptIds" column="dept_ids_"/>
        <result property="postIds" column="post_ids_"/>
        <result property="postDeptIds" column="post_dept_ids_"/>
        <collection property="roleNames" ofType="string" javaType="list">
            <result column="role_name_"/>
        </collection>
        <collection property="roleIds" ofType="integer" javaType="list">
            <result column="role_id_"/>
        </collection>
    </resultMap>
    <select id="queryEmployByOrganId" resultMap="EmployeeDto">
        SELECT ue.*,ue.organ_id_ organ_id_str_,sr.role_name_,sr.id_ role_id_
        FROM (SELECT e.user_id_,su.real_name_,su.gender_,su.phone_,su.user_type_,e.job_nature_,su.lock_flag_,
        e.entry_date_,e.demission_date_,e.organ_id_list_ organ_id_,e.create_time_,e.contact_address_,
        e.postal_code_,e.dept_id_,e.dept_ids_,e.post_ids_,e.post_dept_ids_
        FROM employee e
        LEFT JOIN sys_user su ON e.user_id_ = su.id_
        <if test="roleId != null">
            LEFT JOIN sys_user_role sur ON sur.user_id_ = e.user_id_
        </if>
        <where>
            su.del_flag_ = 0 and su.tenant_id_ = #{tenantId}
            <if test="lockFlag != null">
                AND su.lock_flag_ = #{lockFlag}
            </if>
            <if test="demissionflag != null and demissionflag == 1">
                AND e.demission_date_ IS NOT NULL
            </if>
            <if test="demissionflag != null and demissionflag == 0">
                AND e.demission_date_ IS NULL
            </if>
            <if test="organId != null">
                AND INTE_ARRAY(e.organ_id_list_,#{organId})
            </if>
            <if test="roleId != null">
                AND sur.role_id_ = #{roleId}
            </if>
            <if test="jobNature != null">
                AND e.job_nature_ = #{jobNature}
            </if>
            <if test="search != null">
                AND (su.real_name_ LIKE CONCAT('%',#{search},'%') OR su.phone_ LIKE CONCAT('%',#{search},'%') or su.id_ like CONCAT('%',#{search},'%'))
            </if>
        </where>
        ORDER BY e.create_time_ DESC <include refid="global.limit"/>) ue
        LEFT JOIN sys_user_role sur ON sur.user_id_ = ue.user_id_
        LEFT JOIN sys_role sr ON sr.id_ = sur.role_id_
    </select>

    <select id="queryEmployByOrganIdCount" resultType="int">
        SELECT COUNT(DISTINCT e.user_id_)
        FROM employee e
        LEFT JOIN sys_user su ON e.user_id_ = su.id_
        <if test="roleId != null">
            LEFT JOIN sys_user_role sur ON sur.user_id_ = e.user_id_
        </if>
        <where>
            su.del_flag_ = 0 and su.tenant_id_ = #{tenantId}
            <if test="organId != null">
                AND INTE_ARRAY(e.organ_id_list_,#{organId})
            </if>
            <if test="demissionflag != null and demissionflag == 1">
                AND e.demission_date_ IS NOT NULL
            </if>
            <if test="demissionflag != null and demissionflag == 0">
                AND e.demission_date_ IS NULL
            </if>
            <if test="jobNature != null">
                AND e.job_nature_ = #{jobNature}
            </if>
            <if test="search != null">
                AND (su.real_name_ LIKE CONCAT('%',#{search},'%') OR su.phone_ LIKE CONCAT('%',#{search},'%') or su.id_ like CONCAT('%',#{search},'%'))
            </if>
            <if test="roleId != null">
                AND sur.role_id_ = #{roleId}
            </if>
        </where>
    </select>
    <select id="queryUserRole" resultType="java.lang.Integer">
        SELECT sur.role_id_ FROM sys_user_role sur WHERE sur.user_id_ = #{userId}
    </select>

    <select id="findByRole" resultType="com.ym.mec.biz.dal.dto.SimpleUserDto">
        SELECT DISTINCT su.id_ userId,
            su.real_name_ userName,
            su.avatar_ avatar,
            e.organ_id_list_ organIds
        FROM
            sys_user su
            LEFT JOIN sys_user_role sur ON su.id_ = sur.user_id_
            LEFT JOIN employee e ON e.user_id_ = su.id_
        WHERE
            su.lock_flag_ = 0 AND su.del_flag_ = 0 AND FIND_IN_SET(sur.role_id_, #{roleIds})
            <if test="organIds!=null and organIds!=''">
                AND INTE_ARRAY(e.organ_id_list_,#{organIds})
            </if>
    </select>
    <select id="findByIds" resultType="com.ym.mec.biz.dal.dto.SimpleUserDto">
        SELECT su.id_ userId,su.real_name_ userName
        FROM sys_user su
        WHERE id_ IN
        <foreach collection="userIds" item="userId" separator="," open="(" close=")">
            #{userId}
        </foreach>
    </select>
    <select id="hasCourseGroupRelation" resultType="java.lang.Integer">
        SELECT SUM(a.num) FROM
        (SELECT COUNT(vg.id_) num FROM vip_group vg WHERE vg.educational_teacher_id_  = #{employeeId} AND vg.group_status_ IN (0,1,5,2,6,4)
        UNION ALL
        SELECT COUNT(mg.id_) num FROM music_group mg WHERE mg.educational_teacher_id_ = #{employeeId} AND mg.status_ != 'CANCELED'
        UNION ALL
        SELECT COUNT(pg.id_) num FROM practice_group pg WHERE pg.educational_teacher_id_ = #{employeeId} AND pg.group_status_ != 'CANCEL')a
    </select>
    <select id="hasCourseSchedule" resultType="java.lang.Integer">
        SELECT COUNT(DISTINCT cs.id_)
        FROM course_schedule_teacher_salary csts
        LEFT JOIN course_schedule cs ON cs.id_ = csts.course_schedule_id_
        AND CONCAT(cs.class_date_,' ',cs.start_class_time_) > NOW() AND cs.del_flag_ = 0 AND cs.pre_course_flag_ = 0
        WHERE csts.user_id_ = #{employeeId}
    </select>

    <select id="queryRepairOrganList" resultType="java.lang.Integer">
        SELECT DISTINCT organ_id_ FROM music_group mg
        WHERE repair_user_id_ = #{userId}
    </select>
    <select id="queryEducationOrganList" resultType="java.lang.Integer">
        SELECT DISTINCT c.organ_id_ FROM (
             SELECT organ_id_ FROM music_group
             WHERE educational_teacher_id_ = #{userId}
             UNION
             SELECT organ_id_ FROM practice_group
             WHERE educational_teacher_id_ = #{userId}
             UNION
             SELECT organ_id_ FROM vip_group
             WHERE educational_teacher_id_ = #{userId}) c
    </select>
    <select id="queryTeamTeacherOrganList" resultType="java.lang.Integer">
        SELECT DISTINCT organ_id_ FROM music_group
        WHERE team_teacher_id_ = #{userId}
    </select>
    <select id="queryDirectorOrganList" resultType="java.lang.Integer">
        SELECT DISTINCT organ_id_ FROM music_group
        WHERE director_user_id_ = #{userId}
    </select>

    <update id="employeeLevel">
        <foreach collection="employeeLevelDtos" item="item">
            <if test="item.roleName == 'repair'">
                UPDATE music_group SET repair_user_id_ = #{item.transferUserId} WHERE repair_user_id_ = #{item.levelUserId} AND organ_id_ = #{item.organId};
            </if>
            <if test="item.roleName == 'education'">
                UPDATE music_group SET educational_teacher_id_ = #{item.transferUserId} WHERE educational_teacher_id_ = #{item.levelUserId} AND organ_id_ = #{item.organId};
                UPDATE practice_group SET educational_teacher_id_ = #{item.transferUserId} WHERE educational_teacher_id_ = #{item.levelUserId} AND organ_id_ = #{item.organId};
                UPDATE vip_group SET educational_teacher_id_ = #{item.transferUserId} WHERE educational_teacher_id_ = #{item.levelUserId} AND organ_id_ = #{item.organId};
            </if>
            <if test="item.roleName == 'teamTeacher'">
                UPDATE music_group SET team_teacher_id_ = #{item.transferUserId} WHERE team_teacher_id_ = #{item.levelUserId} AND organ_id_ = #{item.organId};
            </if>
            <if test="item.roleName == 'director'">
                UPDATE music_group SET director_user_id_ = #{item.transferUserId} WHERE director_user_id_ = #{item.levelUserId} AND organ_id_ = #{item.organId};
            </if>
        </foreach>
    </update>

    <select id="findAllByRole" resultType="com.ym.mec.biz.dal.dto.SimpleUserDto">
        SELECT DISTINCT su.id_ userId,
        su.real_name_ userName,
        su.avatar_ avatar,
        e.organ_id_list_ organIds
        FROM
        sys_user su
        LEFT JOIN sys_user_role sur ON su.id_ = sur.user_id_
        LEFT JOIN employee e ON e.user_id_ = su.id_
        WHERE FIND_IN_SET(sur.role_id_, #{roleIds})
        <if test="organIds!=null and organIds!=''">
            AND INTE_ARRAY(e.organ_id_list_,#{organIds})
        </if>
    </select>

    <select id="queryMusicGroupIdByUserId" resultType="java.lang.String">
        SELECT DISTINCT id_ FROM music_group
        WHERE (director_user_id_ = #{levelUserId} OR educational_teacher_id_ = #{levelUserId} OR team_teacher_id_ = #{levelUserId} OR repair_user_id_ = #{levelUserId})
        AND status_ IN ('PROGRESS','PAUSE','PREPARE')
    </select>

    <select id="queryPracticeGroupIdByUserId" resultType="java.lang.String">
        SELECT DISTINCT id_ FROM practice_group
        WHERE educational_teacher_id_ = #{levelUserId} AND group_status_ = 'NORMAL'
    </select>

    <select id="queryVipGroupIdByUserId" resultType="java.lang.String">
        SELECT DISTINCT id_ FROM vip_group
        WHERE educational_teacher_id_ = #{levelUserId} AND group_status_ IN (2,6)
    </select>

    <select id="getUsers" resultMap="SysUser">
        select * from sys_user where id_ IN
        <foreach collection="userIds" open="(" close=")" separator="," item="userId">
            #{userId}
        </foreach>
    </select>
    <select id="countEmployeeBasicInfo" resultType="java.lang.Integer">
        SELECT COUNT(e.user_id_)
        FROM employee e
        LEFT JOIN sys_user su ON su.id_ = e.user_id_
        <include refid="queryEmployeeBasicInfoSql"/>
    </select>
    <select id="queryEmployeeBasicInfo" resultMap="com.ym.mec.biz.dal.dao.StudentDao.SysUserDto">
        SELECT e.user_id_,su.real_name_ username_,su.phone_
        FROM employee e
        LEFT JOIN sys_user su ON su.id_ = e.user_id_
        <include refid="queryEmployeeBasicInfoSql"/>
        <include refid="global.limit"/>
    </select>
    <sql id="queryEmployeeBasicInfoSql">
        <where>
            e.demission_date_ IS NULL AND su.lock_flag_ = 0 AND su.del_flag_ = 0
            <if test="search != null and search != ''">
                AND (e.user_id_ = #{search} OR su.real_name_ LIKE CONCAT('%',#{search},'%') OR su.phone_ LIKE CONCAT('%',#{search},'%'))
            </if>
            <if test="organId != null and organId != ''">
                AND INTE_ARRAY(e.organ_id_list_,#{organId})
            </if>
            <if test="imGroupId != null and imGroupId != ''">
                AND e.user_id_ NOT IN (SELECT user_id_ FROM im_group_member WHERE im_group_id_ = #{imGroupId})
            </if>
        </where>
    </sql>
</mapper>
