<?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.ylx.massage.mapper.MaProjectMapper">

    <resultMap type="MaProject" id="MaProjectResult">
        <result property="id"    column="id"    />
        <result property="projectId"    column="project_id"    />
        <result property="projectName"    column="project_name"    />
        <result property="projectDescribe"    column="project_describe"    />
        <result property="projectDuration"    column="project_duration"    />
        <result property="projectUsersNum"    column="project_users_num"    />
        <result property="projectOriginalPrice"    column="project_original_price"    />
        <result property="projectCurrentPrice"    column="project_current_price"    />
        <result property="projectMasterImage"    column="project_master_image"    />
        <result property="projectDetailImage"    column="project_detail_image"    />
        <result property="projectIsEnable"    column="project_is_enable"    />
        <result property="merchantId"    column="merchant_id"    />
        <result property="auditStatus"    column="audit_status"    />
        <result property="applyReason"    column="apply_reason"    />
        <result property="reason"    column="reason"    />
        <result property="applyTime"    column="apply_time"    />
        <result property="approveTime"    column="approve_time"    />
        <result property="createBy"    column="create_by"    />
        <result property="updateBy"    column="update_by"    />
        <result property="createTime"    column="create_time"    />
        <result property="updateTime"    column="update_time"    />
        <result property="isDelete"    column="is_delete"    />
    </resultMap>

    <sql id="selectMaProjectVo">
        select id, project_name, project_describe, project_duration, project_users_num, project_original_price, project_current_price, project_master_image, project_detail_image, project_is_enable, create_user, update_user, create_time, update_time, is_delete from ma_project
    </sql>

    <select id="selectMaProjectList" parameterType="MaProject" resultMap="MaProjectResult">
        <include refid="selectMaProjectVo"/>
        <where>
            is_delete !=1
            <if test="projectName != null  and projectName != ''"> and project_name like concat('%', #{projectName}, '%')</if>
            <if test="projectDescribe != null  and projectDescribe != ''"> and project_describe = #{projectDescribe}</if>
            <if test="projectDuration != null "> and project_duration = #{projectDuration}</if>
            <if test="projectUsersNum != null "> and project_users_num = #{projectUsersNum}</if>
            <if test="projectOriginalPrice != null "> and project_original_price = #{projectOriginalPrice}</if>
            <if test="projectCurrentPrice != null "> and project_current_price = #{projectCurrentPrice}</if>
            <if test="projectMasterImage != null  and projectMasterImage != ''"> and project_master_image = #{projectMasterImage}</if>
            <if test="projectDetailImage != null  and projectDetailImage != ''"> and project_detail_image = #{projectDetailImage}</if>
            <if test="projectIsEnable != null "> and project_is_enable = #{projectIsEnable}</if>
            <if test="createUser != null  and createUser != ''"> and create_user = #{createUser}</if>
            <if test="updateUser != null  and updateUser != ''"> and update_user = #{updateUser}</if>
        </where>
    </select>

    <resultMap type="com.ylx.massage.domain.vo.MaProjectAuditListVO" id="MaProjectAuditListResult">
        <result property="projectAuditId" column="project_audit_id"/>
        <result property="projectId" column="project_id"/>
        <result property="projectName" column="project_name"/>
        <result property="merchantId" column="merchant_id"/>
        <result property="merchantName" column="merchant_name"/>
        <result property="merchantNickName" column="merchant_nick_name"/>
        <result property="merchantSex" column="merchant_sex"/>
        <result property="merchantSexName" column="merchant_sex_name"/>
        <result property="merchantAvatar" column="merchant_avatar"/>
        <result property="merchantPhone" column="merchant_phone"/>
        <result property="techType" column="tech_type"/>
        <result property="techTypeName" column="tech_type_name"/>
        <result property="applyTime" column="apply_time"/>
        <result property="approveTime" column="approve_time"/>
        <result property="registerTime" column="register_time"/>
        <result property="auditStatus" column="audit_status"/>
        <result property="auditStatusName" column="audit_status_name"/>
    </resultMap>

    <!-- 查询技能审核列表 -->
    <select id="selectProjectAuditList" resultMap="MaProjectAuditListResult">
        SELECT
            p.id AS project_audit_id,
            p.project_id,
            p.project_name,
            p.merchant_id,
            t.te_name AS merchant_name,
            t.te_nick_name AS merchant_nick_name,
            t.te_sex AS merchant_sex,
            CASE t.te_sex
                WHEN 0 THEN '女'
                WHEN 1 THEN '男'
                ELSE ''
            END AS merchant_sex_name,
            t.avatar AS merchant_avatar,
            t.te_phone AS merchant_phone,
            t.tech_type,
            CASE t.tech_type
                WHEN 0 THEN '真实用户'
                WHEN 1 THEN '虚拟用户'
                ELSE ''
            END AS tech_type_name,
            COALESCE(p.apply_time, p.create_time) AS apply_time,
            p.approve_time,
            t.create_time AS register_time,
            p.audit_status,
            CASE p.audit_status
                WHEN 0 THEN '待审核'
                WHEN 1 THEN '审核通过'
                WHEN 2 THEN '审核驳回'
                ELSE ''
            END AS audit_status_name
        FROM ma_project p
        INNER JOIN ma_technician t ON t.id = p.merchant_id
        <where>
            IFNULL(p.is_delete, 0) = 0
            AND IFNULL(t.is_delete, 0) = 0
            <if test="dto != null">
                <choose>
                    <when test="dto.auditStatus != null">
                        AND p.audit_status = #{dto.auditStatus}
                    </when>

                    <when test="dto.auditStatusGroup != null and dto.auditStatusGroup == 0">
                        AND p.audit_status = 0
                    </when>
                    <when test="dto.auditStatusGroup != null and dto.auditStatusGroup == 1">
                        AND p.audit_status IN (1, 2)
                    </when>
                </choose>
                <!-- 商户名称 -->
                <if test="dto.merchantName != null and dto.merchantName != ''">
                    AND t.te_name LIKE CONCAT('%', #{dto.merchantName}, '%')
                </if>
                <!-- 商户昵称 -->
                <if test="dto.merchantNickName != null and dto.merchantNickName != ''">
                    AND t.te_nick_name LIKE CONCAT('%', #{dto.merchantNickName}, '%')
                </if>
                <!-- 商户类型 -->
                <if test="dto.techType != null">
                    AND t.tech_type = #{dto.techType}
                </if>
                <!-- 商户电话 -->
                <if test="dto.merchantPhone != null and dto.merchantPhone != ''">
                    AND t.te_phone LIKE CONCAT('%', #{dto.merchantPhone}, '%')
                </if>
                <!-- 申请开始时间 -->
                <if test="dto.beginApplyTime != null and dto.beginApplyTime != ''">
                    AND COALESCE(p.apply_time, p.create_time) &gt;= #{dto.beginApplyTime}
                </if>
                <!-- 申请结束时间 -->
                <if test="dto.endApplyTime != null and dto.endApplyTime != ''">
                    AND COALESCE(p.apply_time, p.create_time) &lt;= #{dto.endApplyTime}
                </if>
                <!-- 商户性别 -->
                <if test="dto.merchantSex != null">
                    AND t.te_sex = #{dto.merchantSex}
                </if>
            </if>
        </where>
        ORDER BY COALESCE(p.apply_time, p.create_time) DESC, p.id DESC
    </select>

    <resultMap type="com.ylx.massage.domain.vo.MaProjectOpenServiceVO" id="MaProjectOpenServiceResult">
        <result property="projectAuditId" column="project_audit_id"/>
        <result property="projectId" column="project_id"/>
        <result property="projectName" column="project_name"/>
        <result property="applyReason" column="apply_reason"/>
        <result property="applyTime" column="apply_time"/>
        <result property="auditStatus" column="audit_status"/>
        <result property="auditStatusName" column="audit_status_name"/>
        <result property="remark" column="remark"/>
    </resultMap>

    <!-- 查询商户申请开通的项目列表 -->
    <select id="selectMerchantOpenProjectList" resultMap="MaProjectOpenServiceResult">
        SELECT
            p.id AS project_audit_id,
            p.project_id,
            COALESCE(NULLIF(p.project_name, ''), base_project.title, '') AS project_name,
            p.apply_reason,
            COALESCE(p.apply_time, p.create_time) AS apply_time,
            p.audit_status,
            CASE p.audit_status
                WHEN 0 THEN '待审核'
                WHEN 1 THEN '审核通过'
                WHEN 2 THEN '审核驳回'
                ELSE ''
            END AS audit_status_name,
            p.reason AS remark
        FROM ma_project p
        LEFT JOIN project base_project ON base_project.id = p.project_id
        WHERE p.merchant_id = #{merchantId}
          AND IFNULL(p.is_delete, 0) = 0
        ORDER BY COALESCE(p.apply_time, p.create_time) DESC, p.id DESC
    </select>

    <!-- 查询技能审核记录 -->
    <select id="selectProjectAuditById" resultMap="MaProjectResult">
        SELECT
            id,
            project_id,
            project_name,
            merchant_id,
            audit_status,
            project_is_enable,
            reason,
            approve_time,
            is_delete,
            create_time,
            update_time
        FROM ma_project
        WHERE id = #{projectAuditId}
          AND is_delete = 0
    </select>

    <!-- 提交技能开通审核 -->
    <update id="submitProjectAudit">
        UPDATE ma_project
        SET
            audit_status = #{maProject.auditStatus},
            reason = #{maProject.reason},
            approve_time = #{maProject.approveTime},
            project_is_enable = #{maProject.projectIsEnable},
            update_by = #{maProject.updateBy},
            update_time = #{maProject.updateTime}
        WHERE id = #{maProject.id}
          AND IFNULL(is_delete, 0) = 0
          AND audit_status = 0
    </update>

    <select id="selectMaProjectById" parameterType="Long" resultMap="MaProjectResult">
        <include refid="selectMaProjectVo"/>
        where is_delete !=1 and id = #{id}
    </select>

    <insert id="insertMaProject" parameterType="MaProject" useGeneratedKeys="true" keyProperty="id">
        insert into ma_project
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">id,</if>
            <if test="projectName != null and projectName != ''">project_name,</if>
            <if test="projectDescribe != null and projectDescribe != ''">project_describe,</if>
            <if test="projectDuration != null">project_duration,</if>
            <if test="projectUsersNum != null">project_users_num,</if>
            <if test="projectOriginalPrice != null">project_original_price,</if>
            <if test="projectCurrentPrice != null">project_current_price,</if>
            <if test="projectMasterImage != null and projectMasterImage != ''">project_master_image,</if>
            <if test="projectDetailImage != null and projectDetailImage != ''">project_detail_image,</if>
            <if test="projectIsEnable != null">project_is_enable,</if>
            <if test="createUser != null and createUser != ''">create_user,</if>
            <if test="updateUser != null and updateUser != ''">update_user,</if>
            <if test="createTime != null">create_time,</if>
            <if test="updateTime != null">update_time,</if>
            <if test="isDelete != null">is_delete,</if>
         </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">#{id},</if>
            <if test="projectName != null and projectName != ''">#{projectName},</if>
            <if test="projectDescribe != null and projectDescribe != ''">#{projectDescribe},</if>
            <if test="projectDuration != null">#{projectDuration},</if>
            <if test="projectUsersNum != null">#{projectUsersNum},</if>
            <if test="projectOriginalPrice != null">#{projectOriginalPrice},</if>
            <if test="projectCurrentPrice != null">#{projectCurrentPrice},</if>
            <if test="projectMasterImage != null and projectMasterImage != ''">#{projectMasterImage},</if>
            <if test="projectDetailImage != null and projectDetailImage != ''">#{projectDetailImage},</if>
            <if test="projectIsEnable != null">#{projectIsEnable},</if>
            <if test="createUser != null and createUser != ''">#{createUser},</if>
            <if test="updateUser != null and updateUser != ''">#{updateUser},</if>
            <if test="createTime != null">#{createTime},</if>
            <if test="updateTime != null">#{updateTime},</if>
            <if test="isDelete != null">#{isDelete},</if>
         </trim>
    </insert>

    <update id="updateMaProject" parameterType="MaProject">
        update ma_project
        <trim prefix="SET" suffixOverrides=",">
            <if test="projectName != null and projectName != ''">project_name = #{projectName},</if>
            <if test="projectDescribe != null and projectDescribe != ''">project_describe = #{projectDescribe},</if>
            <if test="projectDuration != null">project_duration = #{projectDuration},</if>
            <if test="projectUsersNum != null">project_users_num = #{projectUsersNum},</if>
            <if test="projectOriginalPrice != null">project_original_price = #{projectOriginalPrice},</if>
            <if test="projectCurrentPrice != null">project_current_price = #{projectCurrentPrice},</if>
            <if test="projectMasterImage != null and projectMasterImage != ''">project_master_image = #{projectMasterImage},</if>
            <if test="projectDetailImage != null and projectDetailImage != ''">project_detail_image = #{projectDetailImage},</if>
            <if test="projectIsEnable != null">project_is_enable = #{projectIsEnable},</if>
            <if test="createUser != null and createUser != ''">create_user = #{createUser},</if>
            <if test="updateUser != null and updateUser != ''">update_user = #{updateUser},</if>
            <if test="createTime != null">create_time = #{createTime},</if>
            <if test="updateTime != null">update_time = #{updateTime},</if>
            <if test="isDelete != null">is_delete = #{isDelete},</if>
        </trim>
        where id = #{id}
    </update>

    <update id="deleteMaProjectById" parameterType="Long">
        update ma_project set is_delete = 1 where id = #{id}
    </update>

    <delete id="deleteMaProjectByIds" parameterType="String">
        delete from ma_project where id in
        <foreach item="id" collection="array" open="(" separator="," close=")">
            #{id}
        </foreach>
    </delete>
    <!-- 首页按摩推荐项目-->
    <select id="getMassageProjectRecommend" resultType="com.ylx.massage.domain.vo.MassageProjectRecommendVo">
        SELECT
            pro.id                     AS projectId,
            pro.title                  AS projectName,
            pro.standard_duration      AS projectDuration,
            COALESCE(ord.sales, 0)     AS sales,           -- 无订单时为 0
            mp_avg.avgCurrentPrice,
            pro.highlight              AS highlight
        FROM project pro
                 INNER JOIN (
            -- 1. 符合条件的商家项目：按项目聚合，计算平均价格
            SELECT
                CAST(mp.project_id AS UNSIGNED) AS project_id,
                AVG(mp.project_current_price)   AS avgCurrentPrice
            FROM ma_project mp
                     INNER JOIN ma_technician tech
                                ON tech.id = CAST(mp.merchant_id AS UNSIGNED)
                                    AND tech.te_area_code = #{cityCode}
                                    AND tech.is_delete = 0
                                    AND tech.audit_status = 2
                                    AND tech.service_state = 1
            WHERE mp.service_tag = 1
              AND mp.is_delete = 0
              AND mp.project_is_enable = 1
            GROUP BY CAST(mp.project_id AS UNSIGNED)
        ) mp_avg ON mp_avg.project_id = pro.id
                 LEFT JOIN (
            -- 2. 订单统计：每个项目的真实订单数
            SELECT
                project_id,
                COUNT(id) AS sales
            FROM t_order
            WHERE project_type = 1
              AND status = 6
              AND is_delete = 0
            GROUP BY project_id
        ) ord ON ord.project_id = pro.id
        WHERE pro.is_delete = 0
        ORDER BY sales DESC, pro.id ASC
    </select>
    <!-- 首页按摩推荐商户点击全部查询按摩所有商户-->
    <select id="getMassageAllMerchants" resultType="com.ylx.massage.domain.vo.MassageAllMerchantsVo">
        SELECT
        project_id AS projectId,
        project_name AS projectName,
        te_name AS merchantName,
        id AS merchantId,
        order_count AS nNum,   -- 子查询中已经 COALESCE 过了
        CASE
        WHEN #{dto.longitude} IS NOT NULL AND #{dto.latitude} IS NOT NULL THEN
        CONCAT(
        CASE WHEN distance_meters >= 1000 THEN ROUND(distance_meters / 1000.0, 1) ELSE distance_meters END,
        CASE WHEN distance_meters >= 1000 THEN 'km' ELSE 'm' END
        )
        ELSE NULL
        END AS distanceShow,
        te_avatar AS teAvatar
        FROM (
        SELECT
        p.project_id,
        p.project_name,
        t.te_name,
        t.id,
        t.te_avatar,
        COALESCE(stat.order_count, 0) AS order_count,
        ROUND(ST_Distance_Sphere(POINT(addr.longitude, addr.latitude), POINT(#{dto.longitude}, #{dto.latitude})), 0) AS distance_meters
        FROM ma_technician t
        INNER JOIN ma_project p
        ON p.merchant_id = CAST(t.id AS CHAR)
        AND p.audit_status = 1
        AND p.is_delete = 0
        AND p.service_tag = 1
        AND p.project_is_enable = 0
        <if test="dto.projectId != null and dto.projectId != ''">
            AND p.project_id = #{dto.projectId}
        </if>
        LEFT JOIN (
        SELECT merchant_id, longitude, latitude
        FROM t_address
        WHERE user_type = 2 AND type = 1 AND is_delete = 0
        ) addr ON t.id = addr.merchant_id
        LEFT JOIN (
        SELECT
        merchant_id,
        project_id,
        COUNT(*) AS order_count
        FROM t_order
        WHERE status = 6
        AND project_type = 1
        AND is_delete = 0
        GROUP BY merchant_id, project_id
        ) stat ON stat.merchant_id = t.id AND stat.project_id = p.project_id
        WHERE t.audit_status = 2
        AND t.is_delete = 0
        AND t.service_state = 1
        AND t.te_area_code = #{dto.cityCode}
        ) AS sub
        ORDER BY nNum DESC  -- 或者 nNum DESC
    </select>

    <select id="selectMerchantList" resultType="com.ylx.project.domain.bookMerchant.vo.BookMerchantVO">
        SELECT
        p.id,
        t.id AS merchantId,
        t.te_nick_name AS merchantNickName,
        t.te_avatar AS merchantAvatar,
        t.n_star AS merchantStar,
        t.n_num AS servedCount,
        p.project_id AS projectId,
        p.project_current_price AS currentPrice,
        CASE
        WHEN calc.distanceMeter = 999999999 THEN '未知'
        WHEN calc.distanceMeter &lt; 1000 THEN CONCAT( ROUND( calc.distanceMeter, 0 ), 'm' )
        ELSE CONCAT( ROUND( calc.distanceMeter / 1000, 2 ), 'km' )
        END AS distanceText
        FROM
        ma_technician t
        INNER JOIN ma_project p ON t.id = p.merchant_id
        LEFT JOIN t_address addr ON t.id = addr.merchant_id AND addr.type = 1 AND addr.is_delete = 0
        LEFT JOIN (
        SELECT
        addr_sub.id AS addrId,
        <if test="dto.latitude != null and dto.longitude != null and dto.latitude != 0 and dto.longitude != 0">
            IF(
            addr_sub.latitude IS NULL OR addr_sub.longitude IS NULL OR addr_sub.latitude=0 OR addr_sub.longitude=0,
            999999999,
            ROUND(
            6371 * ACOS(
            COS(RADIANS(#{dto.latitude})) * COS(RADIANS(addr_sub.latitude))
            * COS(RADIANS(addr_sub.longitude) - RADIANS(#{dto.longitude}))
            + SIN(RADIANS(#{dto.latitude})) * SIN(RADIANS(addr_sub.latitude))
            ) * 1000
            )
            ) AS distanceMeter
        </if>
        <if test="dto.latitude == null or dto.longitude == null or dto.latitude == 0 or dto.longitude == 0">
            999999999 AS distanceMeter
        </if>
        FROM t_address addr_sub
        ) calc ON addr.id = calc.addrId

        WHERE
        p.project_id = #{dto.projectId}
        AND p.audit_status = 1
        AND p.is_delete = 0

        <trim prefix="ORDER BY">
            <choose>
                <when test="dto.latitude != null and dto.longitude != null and dto.latitude != 0 and dto.longitude != 0">
                    calc.distanceMeter ASC, t.n_num DESC
                </when>
                <otherwise>
                    t.n_num DESC
                </otherwise>
            </choose>
        </trim>
    </select>
    <!-- 首页陪玩推荐项目-->
    <select id="getHotCompainonProjectList" resultType="com.ylx.companion.domain.vo.HotCompanionProjectVO">
        SELECT
            pro.id                     AS projectId,
            pro.title                  AS projectName,
            pro.standard_duration      AS projectDuration,
            COALESCE(ord.sales, 0)     AS sales,           -- 无订单时为 0
            mp_avg.avgCurrentPrice,
            pro.highlight              AS highlight
        FROM project pro
                 INNER JOIN (
            -- 1. 符合条件的商家项目：按项目聚合，计算平均价格
            SELECT
                CAST(mp.project_id AS UNSIGNED) AS project_id,
                AVG(mp.project_current_price)   AS avgCurrentPrice
            FROM ma_project mp
                     INNER JOIN ma_technician tech
                                ON tech.id = CAST(mp.merchant_id AS UNSIGNED)
                                    AND tech.te_area_code = #{cityCode}
                                    AND tech.is_delete = 0
                                    AND tech.audit_status = 2
                                    AND tech.service_state = 1
            WHERE mp.service_tag = 2
              AND mp.is_delete = 0
              AND mp.project_is_enable = 1
            GROUP BY CAST(mp.project_id AS UNSIGNED)
        ) mp_avg ON mp_avg.project_id = pro.id
                 LEFT JOIN (
            -- 2. 订单统计：每个项目的真实订单数
            SELECT
                project_id,
                COUNT(id) AS sales
            FROM t_order
            WHERE project_type = 2
              AND status = 6
              AND is_delete = 0
            GROUP BY project_id
        ) ord ON ord.project_id = pro.id
        WHERE pro.is_delete = 0
        <if test="categoryId != null">
            AND pro.category_id = #{categoryId}
        </if>
        ORDER BY sales DESC, pro.id ASC
    </select>

    <!-- 首页陪玩推荐商户点击全部查询陪玩所有商户-->
    <select id="getCompanionAllMerchants" resultType="com.ylx.companion.domain.vo.CompanionAllMerchantsVo">
        SELECT
        project_id AS projectId,
        project_name AS projectName,
        te_name AS merchantName,
        id AS merchantId,
        order_count AS nNum,   -- 子查询中已经 COALESCE 过了
        CASE
        WHEN #{dto.longitude} IS NOT NULL AND #{dto.latitude} IS NOT NULL THEN
        CONCAT(
        CASE WHEN distance_meters >= 1000 THEN ROUND(distance_meters / 1000.0, 1) ELSE distance_meters END,
        CASE WHEN distance_meters >= 1000 THEN 'km' ELSE 'm' END
        )
        ELSE NULL
        END AS distanceShow,
        te_avatar AS teAvatar
        FROM (
        SELECT
        p.project_id,
        p.project_name,
        t.te_name,
        t.id,
        t.te_avatar,
        COALESCE(stat.order_count, 0) AS order_count,
        ROUND(ST_Distance_Sphere(POINT(addr.longitude, addr.latitude), POINT(#{dto.longitude}, #{dto.latitude})), 0) AS distance_meters
        FROM ma_technician t
        INNER JOIN ma_project p
        ON p.merchant_id = CAST(t.id AS CHAR)
        AND p.audit_status = 1
        AND p.is_delete = 0
        AND p.service_tag = 2
        AND p.project_is_enable = 0
        <if test="dto.projectId != null and dto.projectId != ''">
            AND p.project_id = #{dto.projectId}
        </if>
        LEFT JOIN (
        SELECT merchant_id, longitude, latitude
        FROM t_address
        WHERE user_type = 2 AND type = 1 AND is_delete = 0
        ) addr ON t.id = addr.merchant_id
        LEFT JOIN (
        SELECT
        merchant_id,
        project_id,
        COUNT(*) AS order_count
        FROM t_order
        WHERE status = 6
        AND project_type = 2
        AND is_delete = 0
        GROUP BY merchant_id, project_id
        ) stat ON stat.merchant_id = t.id AND stat.project_id = p.project_id
        WHERE t.audit_status = 2
        AND t.is_delete = 0
        AND t.service_state = 1
        AND t.te_area_code = #{dto.cityCode}
        ) AS sub
        ORDER BY nNum DESC  -- 或者 nNum DESC
    </select>

</mapper>
