<?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.resourceManagement.company.mapper.SysUserLoginPortMapper">


    <select id="selectLoginPortListByPort" resultType="com.hotwj.platform.resourceManagement.company.domain.vo.SysUserLoginPortVo">
        SELECT
            ucr.id,
            ucr.user_id AS userId,
            ucr.username AS username,
            ucr.company_id AS companyId,
            ucr.avatar AS avatar,
            c.company_name AS companyName,
            ucr.login_port AS loginPort,
            CASE
                WHEN ucr.login_port = 'port-company_admin' THEN c.company_name
                WHEN ucr.login_port = 'port-government' OR ucr.login_port = 'port-agent' THEN unit.unit_name
                WHEN ucr.login_port = 'port-headquarters' THEN IFNULL(u.phonenumber, '总部管理员')
                WHEN ucr.login_port = 'port-driver' THEN ucr.username
                ELSE ucr.login_port
            END AS roleName,
            CASE
                WHEN ucr.login_port = 'port-company_admin' THEN '管理员'
                WHEN ucr.login_port = 'port-headquarters' THEN '总部管理员'
                WHEN ucr.login_port = 'port-driver' THEN '驾驶员'
                ELSE NULL
            END AS roleType,
            hd.person_type AS roleMod
        FROM sys_user_login_port ucr
        LEFT JOIN sys_company c ON ucr.company_id = c.id
        LEFT JOIN hot_gov_enterprise_unit unit ON ucr.company_id = unit.id
        LEFT JOIN sys_user u ON ucr.user_id = u.user_id
        LEFT JOIN hot_driver hd ON hd.phone = u.phonenumber AND hd.company_id = ucr.company_id AND hd.is_deleted = 0
        AND ucr.login_port ='port-driver'
        WHERE ucr.user_id = #{userId}
        AND ucr.status = 1
        <!-- 企业端和司机端需校验企业状态 -->
        AND (
            (ucr.login_port IN ('port-company_admin', 'port-driver') AND c.is_deleted = 0 AND c.status = 1)
            OR
            (ucr.login_port NOT IN ('port-company_admin', 'port-driver'))
        )
        <!-- 司机端需校验驾驶员是否在职 -->
        AND (
            ucr.login_port != 'port-driver' OR EXISTS (
                SELECT 1 FROM hot_driver hd 
                WHERE hd.phone = u.phonenumber 
                AND hd.company_id = ucr.company_id 
                AND hd.status = 1 
                AND hd.is_deleted = 0
            )
        )
        <!-- 企业端需校验管理人员是否在职 -->
        AND (
            ucr.login_port != 'port-company_admin' OR EXISTS (
                SELECT 1 FROM hot_company_safety_manager hcsm
                WHERE hcsm.user_id = ucr.user_id
                AND hcsm.company_id = ucr.company_id
                AND hcsm.status = 1
                AND hcsm.is_resigned = 0
                AND hcsm.is_deleted = 0
            )
        )
        <if test="port != null and port != ''">
            AND ucr.login_port = #{port}
        </if>
    </select>
</mapper>
