<?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.sunxung.factoring.mapper.sys.LoginLogMapper">
	<resultMap type="LoginLog" id="loginLogResult">
		<result property="id" column="id"/>
		<result property="loginName" column="login_name"/>
		<result property="name" column="name"/>
		<result property="userId" column="user_id"/>
		<result property="accessIp" column="access_ip"/>
		<result property="logType.id" column="log_type"/>
		<result property="remark" column="remark"/>
		<result property="gmtCreate" column="gmt_create"/>
	</resultMap>
	
	<sql id="_search">
		<if test="logTypeId != null ">
			and lg.log_type=#{logTypeId}
		</if>
		<if test="loginTime != null">
			and DATE_FORMAT(lg.gmt_create,'%Y-%m-%d')=DATE_FORMAT(#{loginTime},'%Y-%m-%d')
		</if>
		<if test="userName != null and userName !=''">
			and (lg.login_name like CONCAT('%',#{userName},'%')  or lg.name like CONCAT('%',#{userName},'%')
			or u.full_pinyin like CONCAT('%',#{userName},'%')  or u.simple_pinyin like CONCAT('%',#{userName},'%'))
		</if>
		
	</sql>
	
	<sql id="fields">
		lg.id,
		lg.login_name,
		lg.name,
		lg.user_id,
		lg.access_ip,
		lg.log_type,
		lg.remark,
		lg.gmt_create
	</sql>
	
	<insert id="add" useGeneratedKeys="true" keyColumn="id" keyProperty="id" parameterType="LoginLog">
		insert into sys_login_log
			(login_name,name,user_id,access_ip,log_type,remark)
		values
			(#{loginName},#{name},#{userId},#{accessIp},#{logType.id},#{remark})
	</insert>
	
	<select id="get" parameterType="java.lang.Long" resultMap="loginLogResult">
		select <include refid="fields"/> from sys_login_log lg where lg.id=#{value}
	</select>
	
	<select id="findBySearch" parameterType="SearchLoginLogVo" resultMap="loginLogResult">
		select <include refid="fields" /> from sys_login_log lg
		left join t_dictionary t on t.id=lg.log_type
		left join sys_user u on lg.user_id=u.id
		<where>
			<include refid="_search" />
		</where>
		order by lg.gmt_create desc,t.gradation 
	</select>
	
	<select id="countBySearch" parameterType="SearchLoginLogVo" resultType="java.lang.Integer">
		select count(*) from sys_login_log lg
		left join t_dictionary t on t.id=lg.log_type
		left join sys_user u on lg.user_id=u.id
		<where>
			<include refid="_search" />
		</where>
	</select>
	<select id="findLastLogInByUserAndIp" resultMap="loginLogResult">
		select <include refid="fields" /> from sys_login_log lg
		left join t_dictionary d on lg.log_type = d.id
		where login_name = #{loginName} and access_ip = #{clientIP} and d.code = 'userLogin'
		order by gmt_create desc limit 1;
	</select>

</mapper>