<?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="ink.wgink.login.base.dao.log.ILoginLogDao">

    <cache flushInterval="3600000"/>

    <resultMap id="loginLogDTO" type="ink.wgink.login.base.pojo.dtos.log.LoginLogDTO">
        <result column="login_address" property="loginAddress"/>
        <result column="login_type" property="loginType"/>
        <result column="gmt_create" property="gmtCreate"/>
        <result column="creator_name" property="creatorName"/>
    </resultMap>

    <!-- 建表 -->
    <update id="createTable">
        CREATE TABLE IF NOT EXISTS `log_login_log` (
            `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
            `loginlog_id` char(36) NOT NULL COMMENT '主键',
            `login_address` varchar(255) DEFAULT NULL,
            `login_type` int(1) DEFAULT '1' COMMENT '登录类型',
            `creator` char(36) DEFAULT NULL,
            `gmt_create` datetime DEFAULT NULL,
            `creator_name` varchar(255) DEFAULT NULL,
            PRIMARY KEY (`id`,`loginlog_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    </update>

    <!-- 新增登录日志 -->
    <insert id="save" parameterType="map" flushCache="true">
        INSERT INTO log_login_log(
            loginlog_id,
            login_address,
            login_type,
            creator,
            gmt_create,
            creator_name
        ) VALUES(
            #{loginLogId},
            #{loginAddress},
            #{loginType},
            #{creator},
            #{gmtCreate},
            #{creatorName}
        )
    </insert>

    <!-- 登录日志统计 -->
    <select id="count" parameterType="map" resultType="Integer" useCache="true">
        SELECT
            COUNT(*)
        FROM
            log_login_log
        WHERE
            1 = 1
        <if test="day != null and day != ''">
        AND
            LEFT(gmt_create, 10) = #{day}
        </if>
    </select>

    <!-- 登录日志列表 -->
    <select id="list" parameterType="map" resultMap="loginLogDTO" useCache="true">
        SELECT
            login_address,
            login_type,
            LEFT(gmt_create, 19) gmt_create,
            creator_name
        FROM
            log_login_log
        WHERE
            1 = 1
        <if test="loginType != null and loginType != ''">
        AND
            login_type = #{loginType}
        </if>
        <if test="keywords != null and keywords != ''">
        AND (
            creator_name LIKE CONCAT('%', #{keywords}, '%')
        )
        </if>
        <if test="startTime != null and startTime != ''">
        AND
            LEFT(gmt_create, 10) <![CDATA[ >= ]]> #{startTime}
        </if>
        <if test="endTime != null and endTime != ''">
        AND
            LEFT(gmt_create, 10) <![CDATA[ <= ]]> #{endTime}
        </if>
        ORDER BY
            gmt_create DESC, id DESC
    </select>
</mapper>