<?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.sundot.airport.attendance.mapper.AttendanceAreaMapper">

    <!-- 通用结果映射 -->
    <resultMap id="AttendanceAreaResult" type="AttendanceArea">
        <id column="id" property="id" jdbcType="INTEGER"/>
        <result column="area_name" property="areaName" jdbcType="VARCHAR"/>
        <result column="address" property="address" jdbcType="VARCHAR"/>
        <result column="longitude" property="longitude" jdbcType="DECIMAL"/>
        <result column="latitude" property="latitude" jdbcType="DECIMAL"/>
        <result column="radius" property="radius" jdbcType="INTEGER"/>
        <result column="status" property="status" jdbcType="TINYINT"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
        <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
    </resultMap>

    <!-- 带距离计算的结果映射 -->
    <resultMap id="DistanceResultMap" type="AttendanceArea"
               extends="AttendanceAreaResult">
        <result column="distance" property="distance" jdbcType="DECIMAL"/>
    </resultMap>

    <sql id="selectAttendanceCheckRecordVo">
        select id,
               area_name,
               address,
               longitude,
               latitude,
               radius,
               status,
               create_time,
               update_time
        from attendance_area
    </sql>

    <select id="findValidAreasEfficiently" resultMap="DistanceResultMap">
        SELECT id,
               area_name,
               address,
               longitude,
               latitude,
               radius,
               status,
               create_time,
               update_time,
               ST_Distance_Sphere(
                       POINT(longitude, latitude),
                       POINT(#{lng}, #{lat})
               ) AS distance
        FROM attendance_area
        WHERE status = 1
          AND longitude IS NOT NULL
          AND latitude IS NOT NULL
          AND longitude BETWEEN -180 AND 180
          AND latitude BETWEEN -90 AND 90
          AND ST_Distance_Sphere(
                POINT(longitude, latitude),
                POINT(#{lng}, #{lat})
              ) BETWEEN 0 AND radius
    </select>

    <select id="areaList" resultMap="DistanceResultMap">
        <include refid="selectAttendanceCheckRecordVo"/>
        WHERE
        status = 1
    </select>

</mapper>
