<?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="shop.alien.mapper.LawFirmMapper">

    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="shop.alien.entity.store.LawFirm">
        <id column="id" property="id" />
        <result column="firm_name" property="firmName" />
        <result column="credit_code" property="creditCode" />
        <result column="short_name" property="shortName" />
        <result column="english_name" property="englishName" />
        <result column="establishment_date" property="establishmentDate" />
        <result column="firm_type" property="firmType" />
        <result column="firm_scale" property="firmScale" />
        <result column="phone" property="phone" />
        <result column="fax" property="fax" />
        <result column="email" property="email" />
        <result column="website" property="website" />
        <result column="introduction" property="introduction" />
        <result column="logo" property="logo" />
        <result column="business_license_image" property="businessLicenseImage" />
        <result column="practice_license_no" property="practiceLicenseNo" />
        <result column="practice_license_image" property="practiceLicenseImage" />
        <result column="director_name" property="directorName" />
        <result column="director_phone" property="directorPhone" />
        <result column="director_email" property="directorEmail" />
        <result column="lawyer_count" property="lawyerCount" />
        <result column="partner_count" property="partnerCount" />
        <result column="status" property="status" />
        <result column="certification_status" property="certificationStatus" />
        <result column="certification_fail_reason" property="certificationFailReason" />
        <result column="certification_time" property="certificationTime" />
        <result column="certification_reviewer_id" property="certificationReviewerId" />
        <result column="is_recommended" property="isRecommended" />
        <result column="recommend_sort" property="recommendSort" />
        <result column="delete_flag" property="deleteFlag" />
        <result column="created_time" property="createdTime" />
        <result column="created_user_id" property="createdUserId" />
        <result column="updated_time" property="updatedTime" />
        <result column="updated_user_id" property="updatedUserId" />
        <result column="remark" property="remark" />
    </resultMap>

    <!-- 通用查询结果列 -->
    <sql id="Base_Column_List">
        id, firm_name, credit_code, short_name, english_name, establishment_date, firm_type, firm_scale,
        phone, fax, email, website, introduction, logo,
        business_license_image, practice_license_no, practice_license_image, director_name, director_phone,
        director_email, lawyer_count, partner_count, status, certification_status, certification_fail_reason,
        certification_time, certification_reviewer_id, is_recommended, recommend_sort, delete_flag,
        created_time, created_user_id, updated_time, updated_user_id, remark, platform_commission_ratio
    </sql>

    <!-- 订单查询公共条件 -->
    <sql id="Order_Common_Where">
        lco.delete_flag = 0
        AND lco.order_status = 3
        <if test="startDate != null">
            AND lco.order_time &gt;= CONCAT(#{startDate}, ' 00:00:00')
        </if>
        <if test="endDate != null">
            AND lco.order_time &lt;= CONCAT(#{endDate}, ' 23:59:59')
        </if>
    </sql>

    <!-- 查询律所对账统计信息 -->
    <select id="getLawFirmReconciliationStatistics" resultType="java.util.HashMap">
        <choose>
            <when test="firmId != null">
                <!-- 指定律所ID时，从律所表开始，确保即使没有订单也返回 -->
                SELECT
                    COUNT(DISTINCT lco.id) as order_count,
                    COALESCE(SUM(lco.lawyer_earnings), 0) as total_amount,
                    COALESCE(SUM(lco.consultation_fee), 0) as total_platform_service_fee
                FROM law_firm lf
                LEFT JOIN lawyer_consultation_order lco ON lco.place_id = lf.id
                    AND lco.delete_flag = 0
                    AND lco.order_status = 3
                    <if test="startDate != null">
                        AND lco.order_time &gt;= CONCAT(#{startDate}, ' 00:00:00')
                    </if>
                    <if test="endDate != null">
                        AND lco.order_time &lt;= CONCAT(#{endDate}, ' 23:59:59')
                    </if>
                WHERE lf.delete_flag = 0
                    AND lf.id = #{firmId}
            </when>
            <otherwise>
                <!-- 未指定律所ID时，从订单表开始 -->
                SELECT
                    COUNT(DISTINCT lco.id) as order_count,
                    COALESCE(SUM(lco.lawyer_earnings), 0) as total_amount,
                    COALESCE(SUM(lco.consultation_fee), 0) as total_platform_service_fee
                FROM lawyer_consultation_order lco
                LEFT JOIN law_firm lf ON lco.place_id = lf.id
                    AND lf.delete_flag = 0
                WHERE
                <include refid="Order_Common_Where"/>
                <if test="firmName != null and firmName != ''">
                    AND lf.firm_name LIKE CONCAT('%', #{firmName}, '%')
                </if>
            </otherwise>
        </choose>
    </select>

    <!-- 查询所有律所的对账统计信息（按律所分组） -->
    <resultMap id="LawFirmReconciliationStatisticsResultMap" type="shop.alien.entity.store.vo.LawFirmListVO">
        <result column="firm_id" property="firmId" />
        <result column="firm_name" property="firmName" />
        <result column="order_count" property="totalOrderCount" />
        <result column="total_amount_yuan" property="totalOrderAmountYuan" jdbcType="VARCHAR" />
        <result column="commission_fee_yuan" property="platformServiceFeeYuan" jdbcType="VARCHAR" />
    </resultMap>

    <!-- 查询律所下所有律师的对账统计信息（按律师分组） -->
    <resultMap id="LawyerReconciliationStatisticsResultMap" type="shop.alien.entity.store.vo.LawyerListVO">
        <result column="lawyer_id" property="lawyerId" />
        <result column="lawyer_name" property="lawyerName" />
        <result column="head_img" property="headImg" />
        <result column="lawyer_certificate_no" property="lawyerCertificateNo" />
        <result column="firm_id" property="firmId" />
        <result column="firm_name" property="firmName" />
        <result column="order_count" property="totalOrderCount" />
        <result column="total_amount_yuan" property="totalOrderAmountYuan" jdbcType="VARCHAR" />
        <result column="commission_fee_yuan" property="platformServiceFeeYuan" jdbcType="VARCHAR" />
    </resultMap>

    <select id="getAllLawFirmReconciliationStatistics" resultMap="LawFirmReconciliationStatisticsResultMap">
        SELECT
            lf.id as firm_id,
            lf.firm_name,
            COUNT(DISTINCT lco.id) as order_count,
            CAST(ROUND(COALESCE(SUM(lco.lawyer_earnings), 0) / 100.0, 2) AS CHAR) as total_amount_yuan,
            CAST(ROUND(COALESCE(SUM(lco.consultation_fee), 0) / 100.0, 2) AS CHAR) as commission_fee_yuan
        FROM law_firm lf
        LEFT JOIN lawyer_consultation_order lco ON lco.place_id = lf.id
            AND lco.delete_flag = 0
            AND lco.order_status = 3
            <if test="startDate != null">
                AND lco.order_time &gt;= CONCAT(#{startDate}, ' 00:00:00')
            </if>
            <if test="endDate != null">
                AND lco.order_time &lt;= CONCAT(#{endDate}, ' 23:59:59')
            </if>
        WHERE lf.delete_flag = 0
        <if test="firmName != null and firmName != ''">
            AND lf.firm_name LIKE CONCAT('%', #{firmName}, '%')
        </if>
        GROUP BY lf.id, lf.firm_name
        ORDER BY COALESCE(SUM(lco.lawyer_earnings), 0) DESC
    </select>

    <!-- 查询律所下所有律师的对账统计信息（按律师分组） -->
    <select id="getLawyerReconciliationStatistics" resultMap="LawyerReconciliationStatisticsResultMap">
        SELECT
            lu.id as lawyer_id,
            lu.name as lawyer_name,
            lu.head_img,
            lu.lawyer_certificate_no,
            lf.id as firm_id,
            lf.firm_name,
            COUNT(DISTINCT lco.id) as order_count,
            CAST(ROUND(COALESCE(SUM(lco.lawyer_earnings), 0) / 100.0, 2) AS CHAR) as total_amount_yuan,
            CAST(ROUND(COALESCE(SUM(lco.consultation_fee), 0) / 100.0, 2) AS CHAR) as commission_fee_yuan
        FROM lawyer_user lu
        INNER JOIN law_firm lf ON lu.firm_id = lf.id
            AND lf.delete_flag = 0
            AND lf.id = #{firmId}
        LEFT JOIN lawyer_consultation_order lco ON lco.lawyer_user_id = lu.id
            AND lco.place_id = #{firmId}
            AND lco.delete_flag = 0
            AND lco.order_status = 3
            <if test="startDate != null">
                AND lco.order_time &gt;= CONCAT(#{startDate}, ' 00:00:00')
            </if>
            <if test="endDate != null">
                AND lco.order_time &lt;= CONCAT(#{endDate}, ' 23:59:59')
            </if>
        WHERE lu.delete_flag = 0
        GROUP BY lu.id, lu.name, lu.head_img, lu.lawyer_certificate_no, lf.id, lf.firm_name
        ORDER BY COALESCE(SUM(lco.lawyer_earnings), 0) DESC
    </select>

    <!-- 查询律所下所有律师的对账统计信息（按律师分组，支持律师名称模糊查询） -->
    <select id="getLawyerReconciliationStatisticsWithName" resultMap="LawyerReconciliationStatisticsResultMap">
        SELECT
            lu.id as lawyer_id,
            lu.name as lawyer_name,
            lu.head_img,
            lu.lawyer_certificate_no,
            lf.id as firm_id,
            lf.firm_name,
            COUNT(DISTINCT lco.id) as order_count,
            CAST(ROUND(COALESCE(SUM(lco.lawyer_earnings), 0) / 100.0, 2) AS CHAR) as total_amount_yuan,
            CAST(ROUND(COALESCE(SUM(lco.consultation_fee), 0) / 100.0, 2) AS CHAR) as commission_fee_yuan
        FROM lawyer_user lu
        INNER JOIN law_firm lf ON lu.firm_id = lf.id
            AND lf.delete_flag = 0
            AND lf.id = #{firmId}
        LEFT JOIN lawyer_consultation_order lco ON lco.lawyer_user_id = lu.id
            AND lco.place_id = #{firmId}
            AND lco.delete_flag = 0
            AND lco.order_status = 3
            <if test="startDate != null">
                AND lco.order_time &gt;= CONCAT(#{startDate}, ' 00:00:00')
            </if>
            <if test="endDate != null">
                AND lco.order_time &lt;= CONCAT(#{endDate}, ' 23:59:59')
            </if>
        WHERE lu.delete_flag = 0
        <if test="lawyerName != null and lawyerName != ''">
            AND lu.name LIKE CONCAT('%', #{lawyerName}, '%')
        </if>
        GROUP BY lu.id, lu.name, lu.head_img, lu.lawyer_certificate_no, lf.id, lf.firm_name
        ORDER BY COALESCE(SUM(lco.lawyer_earnings), 0) DESC
    </select>

    <!-- 查询律师的已完成订单列表（分页） -->
    <resultMap id="LawyerOrderListResultMap" type="shop.alien.entity.store.vo.LawFirmReconciliationVO">
        <result column="lawyer_name" property="lawyerName" />
        <result column="order_number" property="orderNumber" />
        <result column="order_amount" property="orderAmount" />
        <result column="order_time" property="orderTime" />
        <result column="client_user_id" property="clientUserId" />
        <result column="client_user_name" property="clientUserName" />
    </resultMap>

    <select id="getLawyerOrderList" resultMap="LawyerOrderListResultMap">
        SELECT
            lu.name as lawyer_name,
            lco.order_number,
            lco.order_amount,
            lco.order_time,
            lco.client_user_id,
            life_user.user_name as client_user_name
        FROM lawyer_consultation_order lco
        INNER JOIN lawyer_user lu ON lco.lawyer_user_id = lu.id
            AND lu.delete_flag = 0
        LEFT JOIN life_user ON lco.client_user_id = life_user.id
            AND life_user.delete_flag = 0
        WHERE lco.lawyer_user_id = #{lawyerId}
            AND lco.delete_flag = 0
            AND lco.order_status = 3
        ORDER BY lco.order_time DESC
    </select>

</mapper>


