package shop.alien.mapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Param;
import shop.alien.entity.store.LawyerConsultationOrder;
import shop.alien.entity.store.vo.LawyerConsultationOrderVO;
import shop.alien.entity.store.vo.LawyerViolationDetailVO;
import shop.alien.entity.store.dto.LawyerConsultationOrderDto;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 咨询订单 Mapper 接口
 * </p>
 *
 * @author system
 * @since 2025-01-XX
 */
@Mapper
public interface LawyerConsultationOrderMapper extends BaseMapper<LawyerConsultationOrder> {

    /**
     * 分頁查詢訂單列表，聯查律師信息
     *
     * @param page 分頁對象
     * @param orderNumber 訂單編號
     * @param clientUserId 客戶用戶ID
     * @param lawyerUserId 律師用戶ID
     * @param lawyerName 律師姓名
     * @param orderStatus 訂單狀態
     * @param lawyerUserIds 律師用戶ID列表（用於按律師姓名搜索）
     * @return 分頁結果
     */
    IPage<LawyerConsultationOrderVO> getConsultationOrderListWithLawyer(
            IPage<LawyerConsultationOrderVO> page,
            @Param("orderNumber") String orderNumber,
            @Param("clientUserId") Integer clientUserId,
            @Param("lawyerUserId") Integer lawyerUserId,
            @Param("lawyerName") String lawyerName,
            @Param("orderStatus") Integer orderStatus,
            @Param("lawyerUserIds") List<Integer> lawyerUserIds
    );

    /**
     * 根据用户ID查询订单列表
     *
     * @param page 分页
     * @param userId 用户ID
     * @param orderStatus 订单状态
     * @param lawyerUserIds 律师ID列表
     * @return 列表结果
     */
    IPage<LawyerConsultationOrderVO> getConsultationOrderListById(
            IPage<LawyerConsultationOrderVO> page,
            @Param("userId") String userId,
            @Param("orderStatus") String orderStatus,
            @Param("lawyerUserIds") List<Integer> lawyerUserIds
    );


    //写一个insertOrder的插入方法根据order的入参进行插入
    @Insert("INSERT INTO `lawyer_consultation_order`" +
            " (`id`, " +
            "`order_number`," +
            " `client_user_id`," +
            " `lawyer_user_id`, " +
            "`problem_scenario_id`," +
            " `problem_description`," +
            " `order_amount`, " +
            "`consultation_fee`, " +
            "`start_time`," +
            " `end_time`," +
            " `order_status`," +
            " `payment_status`, " +
            "`order_time`, " +
            "`payment_time`," +
            " `validity_period`," +
            " `rating`, " +
            "`comment`, " +
            "`delete_flag`," +
            " `created_time`," +
            " `created_user_id`," +
            " `updated_time`," +
            " `updated_user_id`, " +
            "`alipay_no`," +
            "`order_str`," +
            "place_id," +
            "lawyer_earnings ," +
            "accept_orders_time ," +
            "reason_order_refusal ," +
            "accept_orders_status ," +
            "pay_type ," +
            "charge_minute ,"+
            "minute_num ,"+
            "charge_time ,"+
            "time_num"+
            ")"+
            "VALUES" +
            " (" +
            " #{id}, " +
            "#{orderNumber}," +
            " #{clientUserId}," +
            " #{lawyerUserId}, " +
            "#{problemScenarioId}," +
            " #{problemDescription}," +
            " #{orderAmount}, " +
            "#{consultationFee}, " +
            "#{startTime}," +
            " #{endTime}," +
            " #{orderStatus}," +
            " #{paymentStatus}, " +
            "#{orderTime}, " +
            "#{paymentTime}," +
            " #{validityPeriod}," +
            " #{rating}, " +
            "#{comment}, " +
            "#{deleteFlag}," +
            " #{createdTime}," +
            " #{createdUserId}," +
            " #{updatedTime}," +
            " #{updatedUserId}," +
            " #{alipayNo}," +
            " #{orderStr}," +
            "#{placeId}," +
            "#{lawyerEarnings} ," +
            "#{acceptOrdersTime} ," +
            "#{reasonOrderRefusal} ," +
            "#{acceptOrdersStatus} ," +
            "#{payType} ," +
            "#{chargeMinute} ," +
            "#{minuteNum} ," +
            "#{chargeTime} ," +
            "#{timeNum} " +
            ")")
            int insertOrder(LawyerConsultationOrderDto order);


//    @Insert("<script>" +
//            "INSERT INTO `alien`.`lawyer_consultation_order`" +
//            "<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">" +
//            "<if test='id != null'>`id`,</if>" +
//            "<if test='orderNumber != null'>`order_number`,</if>" +
//            "<if test='clientUserId != null'>`client_user_id`,</if>" +
//            "<if test='lawyerUserId != null'>`lawyer_user_id`,</if>" +
//            "<if test='problemScenarioId != null'>`problem_scenario_id`,</if>" +
//            "<if test='problemDescription != null'>`problem_description`,</if>" +
//            "<if test='orderAmount != null'>`order_amount`,</if>" +
//            "<if test='consultationFee != null'>`consultation_fee`,</if>" +
//            "<if test='startTime != null'>`start_time`,</if>" +
//            "<if test='endTime != null'>`end_time`,</if>" +
//            "<if test='orderStatus != null'>`order_status`,</if>" +
//            "<if test='paymentStatus != null'>`payment_status`,</if>" +
//            "<if test='orderTime != null'>`order_time`,</if>" +
//            "<if test='paymentTime != null'>`payment_time`,</if>" +
//            "<if test='validityPeriod != null'>`validity_period`,</if>" +
//            "<if test='rating != null'>`rating`,</if>" +
//            "<if test='comment != null'>`comment`,</if>" +
//            "<if test='deleteFlag != null'>`delete_flag`,</if>" +
//            "<if test='createdTime != null'>`created_time`,</if>" +
//            "<if test='createdUserId != null'>`created_user_id`,</if>" +
//            "<if test='updatedTime != null'>`updated_time`,</if>" +
//            "<if test='updatedUserId != null'>`updated_user_id`,</if>" +
//            "<if test='alipayNo != null'>`alipay_no`,</if>" +
//            "<if test='orderStr != null'>`order_str`,</if>" +
//            "<if test='placeId != null'>`place_id`,</if>" +
//            "<if test='lawyerEarnings != null'>`lawyer_earnings`,</if>" +
//            "<if test='acceptOrdersTime != null'>`accept_orders_time`,</if>" +
//            "<if test='reasonOrderRefusal != null'>`reason_order_refusal`,</if>" +
//            "<if test='acceptOrdersStatus != null'>`accept_orders_status`,</if>" +
//            "</trim>" +
//            " VALUES " +
//            "<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">" +
//            "<if test='id != null'>#{id},</if>" +
//            "<if test='orderNumber != null'>#{orderNumber},</if>" +
//            "<if test='clientUserId != null'>#{clientUserId},</if>" +
//            "<if test='lawyerUserId != null'>#{lawyerUserId},</if>" +
//            "<if test='problemScenarioId != null'>#{problemScenarioId},</if>" +
//            "<if test='problemDescription != null'>#{problemDescription},</if>" +
//            "<if test='orderAmount != null'>#{orderAmount},</if>" +
//            "<if test='consultationFee != null'>#{consultationFee},</if>" +
//            "<if test='startTime != null'>#{startTime},</if>" +
//            "<if test='endTime != null'>#{endTime},</if>" +
//            "<if test='orderStatus != null'>#{orderStatus},</if>" +
//            "<if test='paymentStatus != null'>#{paymentStatus},</if>" +
//            "<if test='orderTime != null'>#{orderTime},</if>" +
//            "<if test='paymentTime != null'>#{paymentTime},</if>" +
//            "<if test='validityPeriod != null'>#{validityPeriod},</if>" +
//            "<if test='rating != null'>#{rating},</if>" +
//            "<if test='comment != null'>#{comment},</if>" +
//            "<if test='deleteFlag != null'>#{deleteFlag},</if>" +
//            "<if test='createdTime != null'>#{createdTime},</if>" +
//            "<if test='createdUserId != null'>#{createdUserId},</if>" +
//            "<if test='updatedTime != null'>#{updatedTime},</if>" +
//            "<if test='updatedUserId != null'>#{updatedUserId},</if>" +
//            "<if test='alipayNo != null'>#{alipayNo},</if>" +
//            "<if test='orderStr != null'>#{orderStr},</if>" +
//            "<if test='placeId != null'>#{placeId},</if>" +
//            "<if test='lawyerEarnings != null'>#{lawyerEarnings},</if>" +
//            "<if test='acceptOrdersTime != null'>#{acceptOrdersTime},</if>" +
//            "<if test='reasonOrderRefusal != null'>#{reasonOrderRefusal},</if>" +
//            "<if test='acceptOrdersStatus != null'>#{acceptOrdersStatus},</if>" +
//            "</trim>" +
//            "</script>")
//    int insertOrder(LawyerConsultationOrderDto order);






    @Update("<script>" +
            "UPDATE `lawyer_consultation_order`" +
            "<set>" +
            "<if test='id != null'>`id` = #{id},</if>" +
            "<if test='orderNumber != null'>`order_number` = #{orderNumber},</if>" +
            "<if test='clientUserId != null'>`client_user_id` = #{clientUserId},</if>" +
            "<if test='lawyerUserId != null'>`lawyer_user_id` = #{lawyerUserId},</if>" +
            "<if test='problemScenarioId != null'>`problem_scenario_id` = #{problemScenarioId},</if>" +
            "<if test='problemDescription != null'>`problem_description` = #{problemDescription},</if>" +
            "<if test='orderAmount != null'>`order_amount` = #{orderAmount},</if>" +
            "<if test='consultationFee != null'>`consultation_fee` = #{consultationFee},</if>" +
            "<if test='startTime != null'>`start_time`= #{startTime},</if>" +
            "<if test='endTime != null'>`end_time`= #{endTime},</if>" +
            "<if test='orderStatus != null'>`order_status` = #{orderStatus},</if>" +
            "<if test='paymentStatus != null'>`payment_status` = #{paymentStatus},</if>" +
            "<if test='orderTime != null'>`order_time` = #{orderTime},</if>" +
            "<if test='paymentTime != null'>`payment_time` = #{paymentTime},</if>" +
            "<if test='validityPeriod != null'>`validity_period` = #{validityPeriod},</if>" +
            "<if test='rating != null'>`rating`= #{rating},</if>" +
            "<if test='comment != null'>`comment`= #{comment},</if>" +
            "<if test='deleteFlag != null'>`delete_flag` = #{deleteFlag},</if>" +
            "<if test='createdTime != null'>`created_time` = #{createdTime},</if>" +
            "<if test='createdUserId != null'>`created_user_id` = #{createdUserId},</if>" +
            "<if test='updatedTime != null'>`updated_time` = #{updatedTime},</if>" +
            "<if test='updatedUserId != null'>`updated_user_id` = #{updatedUserId},</if>" +
            "<if test='alipayNo != null'>`alipay_no` = #{alipayNo},</if>" +
            "<if test='orderStr != null'>`order_str` = #{orderStr},</if>" +
            "<if test='placeId != null'>`place_id` = #{placeId},</if>" +
            "<if test='lawyerEarnings != null'>`lawyer_earnings` = #{lawyerEarnings},</if>" +
            "<if test='acceptOrdersTime != null'>`accept_orders_time` = #{acceptOrdersTime},</if>" +
            "<if test='payType != null'>`pay_type` = #{payType},</if>" +
            "<if test='reasonOrderRefusal != null'>`reason_order_refusal` = #{reasonOrderRefusal},</if>" +
            "</set>" +
            "WHERE `order_number` = #{orderNumber}" +
            "</script>")
    int updateOrder(LawyerConsultationOrderDto order);







//    @Update("<script>" +
//            "UPDATE `lawyer_consultation_order`" +
//            "<set>" +
//            "<if test='id != null'>`id` = #{id},</if>" +
//            "<if test='orderNumber != null'>`order_number` = #{orderNumber},</if>" +
//            "<if test='clientUserId != null'>`client_user_id` = #{clientUserId},</if>" +
//            "<if test='lawyerUserId != null'>`lawyer_user_id` = #{lawyerUserId},</if>" +
//            "<if test='problemScenarioId != null'>`problem_scenario_id` = #{problemScenarioId},</if>" +
//            "<if test='problemDescription != null'>`problem_description` = #{problemDescription},</if>" +
//            "<if test='orderAmount != null'>`order_amount` = #{orderAmount},</if>" +
//            "<if test='consultationFee != null'>`consultation_fee` = #{consultationFee},</if>" +
//            "<if test='startTime != null'>`start_time`= #{startTime},</if>" +
//            "<if test='endTime != null'>`end_time`= #{endTime},</if>" +
//            "<if test='orderStatus != null'>`order_status` = #{orderStatus},</if>" +
//            "<if test='paymentStatus != null'>`payment_status` = #{paymentStatus},</if>" +
//            "<if test='orderTime != null'>`order_time` = #{orderTime},</if>" +
//            "<if test='paymentTime != null'>`payment_time` = #{paymentTime},</if>" +
//            "<if test='validityPeriod != null'>`validity_period` = #{validityPeriod},</if>" +
//            "<if test='rating != null'>`rating`= #{rating},</if>" +
//            "<if test='comment != null'>`comment`= #{comment},</if>" +
//            "<if test='deleteFlag != null'>`delete_flag` = #{deleteFlag},</if>" +
//            "<if test='createdTime != null'>`created_time` = #{createdTime},</if>" +
//            "<if test='createdUserId != null'>`created_user_id` = #{createdUserId},</if>" +
//            "<if test='updatedTime != null'>`updated_time` = #{updatedTime},</if>" +
//            "<if test='updatedUserId != null'>`updated_user_id` = #{updatedUserId},</if>" +
//            "<if test='alipayNo != null'>`alipay_no` = #{alipayNo},</if>" +
//            "</set>" +
//            "WHERE `order_number` = #{orderNumber}" +
//            "</script>")
//    int updateOrder(LawyerConsultationOrderDto order);

    /**
     * 查询咨询订单（律师端）
     *
     * @param page 分页
     * @param queryWrapper 查询对象
     * @return 列表结果
     */
    @Select("        SELECT\n" +
            "        lco.id,\n" +
            "        lco.order_number,\n" +
            "        lco.client_user_id,\n" +
            "        lco.lawyer_user_id,\n" +
            "        lco.problem_scenario_id,\n" +
            "        lco.problem_description,\n" +
            "        lco.order_amount,\n" +
            "        lco.consultation_fee,\n" +
            "        lco.start_time,\n" +
            "        lco.end_time,\n" +
            "        lco.order_status,\n" +
            "        lco.payment_status,\n" +
            "        lco.order_time,\n" +
            "        lco.payment_time,\n" +
            "        lco.validity_period,\n" +
            "        lco.rating,\n" +
            "        lco.comment,\n" +
            "        lco.created_time,\n" +
            "        lco.alipay_no,\n" +
            "        lco.order_str,\n" +
            "        lco.apply_refund_status,\n" +
            "        lco.reject_refund_reason,\n" +
            "        lco.apply_refund_reason,\n" +
            "        lco.apply_refund_process_time,\n" +
            "        lco.apply_refund_time,\n" +
            "        lco.charge_minute,\n" +
            "        lco.minute_num,\n" +
            "        lco.charge_time,\n" +
            "        lco.time_num,\n" +
            "        CASE\n" +
            "        WHEN EXISTS (SELECT 1 FROM lawyer_order_review lor WHERE lor.order_id = lco.id) THEN '1'\n" +
            "        ELSE '2'\n" +
            "        END AS isHasCommon,\n" +
            "        lu.name AS lawyer_name,\n" +
            "        lu.phone AS lawyer_phone,\n" +
            "        lu.email AS lawyer_email,\n" +
            "        lu.lawyer_certificate_no,\n" +
            "        lu.law_firm,\n" +
            "        lu.practice_years,\n" +
            "        lu.specialty_fields,\n" +
            "        lu.certification_status,\n" +
            "        lu.service_score,\n" +
            "        lu.service_count,\n" +
            "        lu.consultation_fee AS lawyer_consultation_fee,\n" +
            "        lu.province,\n" +
            "        lu.city,\n" +
            "        lu.district,\n" +
            "        lu.address,\n" +
            "        lu.head_img,\n" +
            "        lu.nick_name,\n" +
            "        lu.account_blurb,\n" +
            "        lu.personal_introduction,\n" +
            "        lf.platform_commission_ratio as commission_rate,\n" +
            "        lf.firm_name,\n" +
            "        CASE \n" +
            "        WHEN lf.platform_commission_ratio = 0 THEN '0%' \n" +
            "        ELSE CONCAT( \n" +
            "        TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM CAST(lf.platform_commission_ratio AS CHAR))), '%') \n" +
            "        END AS commissionRateStr, \n" +
            "        lea.expertise_area_info,\n" +
            "        lur.user_name client_user_name,\n" +
            "        lur.user_phone client_user_phone,\n" +
            "        lco.order_amount - lco.consultation_fee as lawyerEarnings,\n" +
            "        luv.processing_status,\n" +
            "        luv.processing_time,\n" +
            "        lur.user_image,\n" +
            "        cas.status as commentStatus,\n" +
            "        luv.report_result ,\n" +
            "        lco.pay_type\n" +
            "        FROM lawyer_consultation_order lco\n" +
            "        LEFT JOIN lawyer_user lu ON lco.lawyer_user_id = lu.id AND lu.delete_flag = 0\n" +
            "        LEFT JOIN law_firm lf on lf.id = lu.firm_id\n" +
            "        left join lawyer_expertise_area lea on lea.id = lu.lawyer_expertise_area_id and lea.delete_flag = 0 " +
            "        left join life_user lur on lur.id = lco.client_user_id " +
            "        left join lawyer_order_review lor on lor.order_id = lco.id " +
            "        left join comment_appeals cas on cas.comment_id = lor.id and cas.delete_flag = 0  " +
            "        left join lawyer_user_violation luv on luv.order_number = lco.order_number and luv.delete_flag = 0 " +
            " ${ew.customSqlSegment}")
    IPage<LawyerConsultationOrderVO> getLawyerConsultationOrderInfo(
            IPage<LawyerConsultationOrderVO> page, @Param(Constants.WRAPPER) QueryWrapper<LawyerConsultationOrderVO> queryWrapper
    );


    /**
     * 查询咨询订单（用户端）
     *
     * @param page 分页
     * @param queryWrapper 查询对象
     * @return 列表结果
     */
    @Select("        SELECT\n" +
            "        lco.id,\n" +
            "        lco.order_number,\n" +
            "        lco.client_user_id,\n" +
            "        lco.lawyer_user_id,\n" +
            "        lco.problem_scenario_id,\n" +
            "        lco.problem_description,\n" +
            "        lco.order_amount,\n" +
            "        lco.consultation_fee,\n" +
            "        lco.start_time,\n" +
            "        lco.end_time,\n" +
            "        lco.order_status,\n" +
            "        lco.payment_status,\n" +
            "        lco.order_time,\n" +
            "        lco.payment_time,\n" +
            "        lco.validity_period,\n" +
            "        lco.rating,\n" +
            "        lco.comment,\n" +
            "        lco.created_time,\n" +
            "        lco.alipay_no,\n" +
            "        lco.order_str,\n" +
            "        lco.apply_refund_status,\n" +
            "        lco.reject_refund_reason,\n" +
            "        lco.pay_type,\n" +
            "        CASE\n" +
            "        WHEN EXISTS (SELECT 1 FROM lawyer_order_review lor WHERE lor.order_id = lco.id) THEN '1'\n" +
            "        ELSE '2'\n" +
            "        END AS isHasCommon,\n" +
            "        lu.name AS lawyer_name,\n" +
            "        lu.phone AS lawyer_phone,\n" +
            "        lu.email AS lawyer_email,\n" +
            "        lu.lawyer_certificate_no,\n" +
            "        lu.law_firm,\n" +
            "        lu.practice_years,\n" +
            "        lu.practice_start_date,\n" +
            "        lu.specialty_fields,\n" +
            "        lu.certification_status,\n" +
            "        lu.service_score,\n" +
            "        lu.service_count,\n" +
            "        lu.consultation_fee AS lawyer_consultation_fee,\n" +
            "        lu.province,\n" +
            "        lu.city,\n" +
            "        lu.order_receiving_status,\n" +
            "        lu.district,\n" +
            "        lu.address,\n" +
            "        lu.head_img,\n" +
            "        lu.nick_name,\n" +
            "        lu.account_blurb,\n" +
            "        lu.personal_introduction,\n" +
            "        lf.platform_commission_ratio as commission_rate,\n" +
            "        luv.processing_status,\n" +
            "        CASE\n" +
            "        WHEN luv.processing_status IS NOT NULL THEN 1\n" +
            "        ELSE 2\n" +
            "        END AS isViolation,\n" +
            "        lf.firm_name,\n" +
            "        CASE \n" +
            "        WHEN lf.platform_commission_ratio = 0 THEN '0%' \n" +
            "        ELSE CONCAT( \n" +
            "        TRIM(TRAILING '.' FROM TRIM(TRAILING '0' FROM CAST(lf.platform_commission_ratio AS CHAR))), '%') \n" +
            "        END AS commissionRateStr, \n" +
            "        lea.expertise_area_info,\n" +
            "        lur.user_name client_user_name,\n" +
            "        lur.user_phone client_user_phone,\n" +
            "        lco.order_amount - lco.consultation_fee as lawyerEarnings,\n" +
            "        lco.charge_minute,\n" +
            "        lco.minute_num,\n" +
            "        lco.charge_time,\n" +
            "        lco.time_num\n" +
            "        FROM lawyer_consultation_order lco\n" +
            "        LEFT JOIN (\n" +
            "            SELECT luv1.*\n" +
            "            FROM lawyer_user_violation luv1\n" +
            "            INNER JOIN (\n" +
            "                SELECT order_number, MAX(id) as max_id\n" +
            "                FROM lawyer_user_violation\n" +
            "                WHERE delete_flag = 0\n" +
            "                GROUP BY order_number\n" +
            "            ) luv2 ON luv1.order_number = luv2.order_number AND luv1.id = luv2.max_id\n" +
            "            WHERE luv1.delete_flag = 0\n" +
            "        ) luv ON luv.order_number = lco.order_number\n" +
            "        LEFT JOIN lawyer_user lu ON lco.lawyer_user_id = lu.id AND lu.delete_flag = 0\n" +
            "        LEFT JOIN law_firm lf on lf.id = lu.firm_id\n" +
            "        left join lawyer_expertise_area lea on lea.id = lu.lawyer_expertise_area_id and lea.delete_flag = 0 " +
            "        left join life_user lur on lur.id = lco.client_user_id " +
            " ${ew.customSqlSegment}")
    IPage<LawyerConsultationOrderVO> getLawyerConsultationOrderList(
            IPage<LawyerConsultationOrderVO> page, @Param(Constants.WRAPPER) QueryWrapper<LawyerConsultationOrderVO> queryWrapper
    );

    @Select("select\n" +
            "lco.order_status,\n" +
            "count(*) as order_count\n" +
            "FROM\n" +
            "\tlawyer_consultation_order lco\n" +
            "LEFT JOIN lawyer_user lu ON\n" +
            "\tlco.lawyer_user_id = lu.id\n" +
            "\tAND lu.delete_flag = 0\n" +
            "left join lawyer_expertise_area lea on\n" +
            "\tlea.id = lu.lawyer_expertise_area_id\n" +
            "\tand lea.delete_flag = 0\n" +
            "left join life_user lur on\n" +
            "\tlur.id = lco.client_user_id ${ew.customSqlSegment}")
    List<Map<String, Object>> getLawyerStatisticsInfo(@Param(Constants.WRAPPER) QueryWrapper<LawyerConsultationOrderVO> queryWrapper);


    //查询咨询订单
    @Select("<script>" +
            "SELECT " +
            "id, " +
            "order_number, " +
            "client_user_id, " +
            "lawyer_user_id, " +
            "problem_scenario_id, " +
            "problem_description, " +
            "order_amount, " +
            "consultation_fee, " +
            "start_time, " +
            "end_time, " +
            "order_status, " +
            "payment_status, " +
            "order_time, " +
            "payment_time, " +
            "validity_period, " +
            "rating, " +
            "comment, " +
            "delete_flag, " +
            "created_time, " +
            "created_user_id, " +
            "updated_time, " +
            "updated_user_id, " +
            "alipay_no, " +
            "order_str, " +
            "place_id, " +
            "lawyer_earnings ,"+
            "accept_orders_time ,"+
            "reason_order_refusal ,"+
            "accept_orders_status "+
            "FROM " +
            "lawyer_consultation_order " +
            "WHERE order_status in (0,1,2) " +
            " and delete_flag = 0 " +
            "<if test='clientUserId != null'>" +
            "AND client_user_id = #{clientUserId} " +
            "</if>" +
            "<if test='lawyerUserId != null'>" +
            "AND lawyer_user_id = #{lawyerUserId} " +
            "</if>" +
            "</script>")
    List<LawyerConsultationOrder> selectOrder(
            @Param("clientUserId") Integer clientUserId,
            @Param("lawyerUserId") Integer lawyerUserId);

    /**
     * 统计本月订单量和本月收益
     *
     * @param lawyerUserId 律师用户ID
     * @param startTime    本月开始时间
     * @param endTime      本月结束时间
     * @return 统计数据Map，包含monthOrderCount和monthRevenue（单位：分）
     */
    @Select("SELECT " +
            "COUNT(*) as monthOrderCount, " +
            "COALESCE(SUM(order_amount), 0) as monthRevenue " +
            "FROM lawyer_consultation_order " +
            "WHERE lawyer_user_id = #{lawyerUserId} " +
            "AND delete_flag = 0 " +
            "AND order_status = 3 " +
            "AND created_time >= #{startTime} " +
            "AND created_time < #{endTime}")
    Map<String, Object> getMonthStatistics(
            @Param("lawyerUserId") Integer lawyerUserId,
            @Param("startTime") String startTime,
            @Param("endTime") String endTime);

    /**
     * 统计总订单量和总收益
     *
     * @param lawyerUserId 律师用户ID
     * @return 统计数据Map，包含totalOrderCount和totalRevenue（单位：分）
     */
    @Select("SELECT " +
            "COUNT(*) as totalOrderCount, " +
            "COALESCE(SUM(order_amount), 0) as totalRevenue " +
            "FROM lawyer_consultation_order " +
            "WHERE lawyer_user_id = #{lawyerUserId} " +
            "AND order_status = 3 " +
            "AND delete_flag = 0")
    Map<String, Object> getTotalStatistics(@Param("lawyerUserId") Integer lawyerUserId);

    /**
     * 统计进行中订单（订单状态=2）
     *
     * @param lawyerUserId 律师用户ID
     * @return 统计数据Map，包含orderCount和totalAmount（单位：分）
     */
    @Select("SELECT " +
            "COUNT(*) as orderCount, " +
            "COALESCE(SUM(order_amount), 0) as totalAmount " +
            "FROM lawyer_consultation_order " +
            "WHERE lawyer_user_id = #{lawyerUserId} " +
            "AND delete_flag = 0 " +
            "AND order_status = 2")
    Map<String, Object> getInProgressStatistics(@Param("lawyerUserId") Integer lawyerUserId);

    /**
     * 统计待接单订单（订单状态=1）
     *
     * @param lawyerUserId 律师用户ID
     * @return 统计数据Map，包含orderCount和totalAmount（单位：分）
     */
    @Select("SELECT " +
            "COUNT(*) as orderCount, " +
            "COALESCE(SUM(order_amount), 0) as totalAmount " +
            "FROM lawyer_consultation_order " +
            "WHERE lawyer_user_id = #{lawyerUserId} " +
            "AND delete_flag = 0 " +
            "AND order_status = 1")
    Map<String, Object> getPendingAcceptStatistics(@Param("lawyerUserId") Integer lawyerUserId);

    /**
     * 统计已退款订单（申请退款状态=3）
     *
     * @param lawyerUserId 律师用户ID
     * @return 统计数据Map，包含orderCount和totalAmount（单位：分）
     */
    @Select("SELECT " +
            "COUNT(*) as orderCount, " +
            "COALESCE(SUM(order_amount), 0) as totalAmount " +
            "FROM lawyer_consultation_order " +
            "WHERE lawyer_user_id = #{lawyerUserId} " +
            "AND delete_flag = 0 " +
            "AND order_status = 5")
    Map<String, Object> getRefundedStatistics(@Param("lawyerUserId") Integer lawyerUserId);

    /**
     * 根据订单ID查询举报详情（包含举报信息、订单信息、律师信息）
     *
     * @param orderId 订单ID
     * @return 举报详情VO
     */
    @Select("SELECT " +
            "luv.id AS violationId, " +
            "luv.order_number, " +
            "luv.violation_reason, " +
            "luv.other_reason_content, " +
            "luv.report_evidence_img, " +
            "luv.processing_status, " +
            "luv.processing_time, " +
            "luv.report_result, " +
            "luv.created_time AS violationCreatedTime, " +
            "luv.reporting_user_id, " +
            "luv.reported_user_id, " +
            "lco.id AS orderId, " +
            "lco.client_user_id, " +
            "lco.problem_description, " +
            "lco.order_amount, " +
            "lco.consultation_fee, " +
            "lco.start_time, " +
            "lco.end_time, " +
            "lco.order_status, " +
            "lco.payment_status, " +
            "lco.order_time, " +
            "lco.payment_time, " +
            "lco.rating, " +
            "lco.comment, " +
            "lco.lawyer_user_id, " +
            "lco.pay_type, " +
            "lco.charge_minute, " +
            "lco.minute_num, " +
            "lco.charge_time, " +
            "lco.time_num, " +
            "lu.name AS lawyerName, " +
            "lu.phone AS lawyerPhone, " +
            "lu.email AS lawyerEmail, " +
            "lu.lawyer_certificate_no, " +
            "lu.law_firm, " +
            "lu.practice_years, " +
            "lu.specialty_fields, " +
            "lu.certification_status, " +
            "lu.service_score, " +
            "lu.service_count, " +
            "lu.consultation_fee AS lawyerConsultationFee, " +
            "lu.province, " +
            "lu.city, " +
            "lu.district, " +
            "lu.address, " +
            "lu.head_img, " +
            "lu.nick_name, " +
            "lu.personal_introduction, " +
            "luv.reporting_user_type, " +
            "lf.firm_name " +
            "FROM lawyer_consultation_order lco " +
            "LEFT JOIN (" +
            "    SELECT luv1.* " +
            "    FROM lawyer_user_violation luv1 " +
            "    INNER JOIN (" +
            "        SELECT order_number, MAX(id) as max_id " +
            "        FROM lawyer_user_violation " +
            "        WHERE delete_flag = 0 " +
            "        GROUP BY order_number" +
            "    ) luv2 ON luv1.order_number = luv2.order_number AND luv1.id = luv2.max_id " +
            "    WHERE luv1.delete_flag = 0" +
            ") luv ON luv.order_number = lco.order_number " +
            "LEFT JOIN lawyer_user lu ON lco.lawyer_user_id = lu.id AND lu.delete_flag = 0 " +
            "LEFT JOIN law_firm lf ON lf.id = lu.firm_id " +
            "WHERE lco.id = #{orderId} AND lco.delete_flag = 0 " +
            "LIMIT 1")
    LawyerViolationDetailVO getViolationDetailByOrderId(@Param("orderId") Integer orderId);

}

