<?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.hotwj.platform.securityManagement.hiddenDangerInspection.mapper.HotHiddenDangerInspectionMapper">

    <!-- status: 进度状态 无异常:1=特处理、2=审核中、3=完结 有异常:4=特处理、5=审核中、6=评估、7=治理、8=复查、9=完结-->
    <select id="selectMobilePlanPage"
            resultType="com.hotwj.platform.securityManagement.hiddenDangerInspection.domain.vo.HotHiddenDangerInspectionVo">
        SELECT * FROM (
        SELECT
        i.*,
        p.plan_name AS planName,
        p.start_date AS planStartDate,
        p.end_date AS planEndDate,
        CASE
        WHEN (i.status IS NULL OR i.status = 1 OR i.status = 2) THEN 1
        ELSE 3
        END AS todoSortGroup,
        CASE
        WHEN (i.status IS NULL OR i.status = 1 OR i.status = 2) THEN '当月未做'
        ELSE '已完成'
        END AS todoSortLabel
        FROM hot_hidden_danger_inspection i
        LEFT JOIN hot_hidden_danger_plan p
        ON p.id = i.plan_id
        AND p.is_deleted = 0
        WHERE i.is_deleted = 0
        AND i.company_id = #{companyId}
        AND DATE_FORMAT(COALESCE(p.start_date, i.create_time), '%Y-%m') = #{currentMonth}
        <if test="isAdmin == false">
            AND (
            (i.project_type = 3 AND i.project_id = #{driverId})
            <if test="vehicleId != null and vehicleId != ''">
                OR (i.project_type = 2 AND i.project_id = #{vehicleId})
            </if>
            )
        </if>
        <if test="keyword != null and keyword != ''">
            AND i.project_name LIKE CONCAT('%', #{keyword}, '%')
        </if>

        UNION ALL

        SELECT
        i.*,
        p.plan_name AS planName,
        p.start_date AS planStartDate,
        p.end_date AS planEndDate,
        2 AS todoSortGroup,
        '未做' AS todoSortLabel
        FROM hot_hidden_danger_inspection i
        LEFT JOIN hot_hidden_danger_plan p
        ON p.id = i.plan_id
        AND p.is_deleted = 0
        WHERE i.is_deleted = 0
        AND i.company_id = #{companyId}
        AND DATE_FORMAT(COALESCE(p.start_date, i.create_time), '%Y-%m') != #{currentMonth}
        AND (i.status IS NULL OR i.status = 1 OR i.status = 2)
        <if test="isAdmin == false">
            AND (
            (i.project_type = 3 AND i.project_id = #{driverId})
            <if test="vehicleId != null and vehicleId != ''">
                OR (i.project_type = 2 AND i.project_id = #{vehicleId})
            </if>
            )
        </if>
        <if test="keyword != null and keyword != ''">
            AND i.project_name LIKE CONCAT('%', #{keyword}, '%')
        </if>
        ) t
        ORDER BY
        t.todoSortGroup ASC,
        COALESCE(t.planEndDate, t.planStartDate, t.create_time) ASC,
        t.id DESC
    </select>
</mapper>
