package com.erp.reconciliation.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.reconciliation.entity.OrderReconciliationRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单对账记录 Mapper
 * 
 * @author ERP Migration
 */
@Mapper
public interface OrderReconciliationRecordRepository extends BaseMapper<OrderReconciliationRecord> {

    /**
     * 根据对账单ID查询
     */
    @Select("SELECT * FROM order_reconciliation_record WHERE bill_id = #{billId} AND deleted_at IS NULL ORDER BY created_at DESC")
    List<OrderReconciliationRecord> findByBillId(@Param("billId") Long billId);

    /**
     * 根据对账单号查询
     */
    @Select("SELECT * FROM order_reconciliation_record WHERE bill_no = #{billNo} AND deleted_at IS NULL ORDER BY created_at DESC")
    List<OrderReconciliationRecord> findByBillNo(@Param("billNo") String billNo);

    /**
     * 根据内部订单ID查询
     */
    @Select("SELECT * FROM order_reconciliation_record WHERE order_id = #{orderId} AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1")
    OrderReconciliationRecord findByOrderId(@Param("orderId") Long orderId);

    /**
     * 根据平台订单号查询
     */
    @Select("SELECT * FROM order_reconciliation_record WHERE platform_order_sn = #{platformOrderSn} AND deleted_at IS NULL ORDER BY created_at DESC LIMIT 1")
    OrderReconciliationRecord findByPlatformOrderSn(@Param("platformOrderSn") String platformOrderSn);

    /**
     * 分页查询订单对账记录
     */
    IPage<OrderReconciliationRecord> selectPageByConditions(
            Page<OrderReconciliationRecord> page,
            @Param("billId") Long billId,
            @Param("billNo") String billNo,
            @Param("checkStatus") String checkStatus,
            @Param("platform") String platform,
            @Param("shopId") Long shopId,
            @Param("startDate") LocalDateTime startDate,
            @Param("endDate") LocalDateTime endDate
    );

    /**
     * 查询有差异的订单
     */
    @Select("SELECT * FROM order_reconciliation_record WHERE bill_id = #{billId} AND check_status = 'difference' AND deleted_at IS NULL ORDER BY ABS(difference_amount) DESC")
    List<OrderReconciliationRecord> findDifferencesByBillId(@Param("billId") Long billId);

    /**
     * 统计各核对状态的数量
     */
    @Select("SELECT check_status, COUNT(*) as count FROM order_reconciliation_record WHERE bill_id = #{billId} AND deleted_at IS NULL GROUP BY check_status")
    List<OrderReconciliationRecord> countByCheckStatus(@Param("billId") Long billId);

    /**
     * 删除指定对账单的记录
     */
    @Select("DELETE FROM order_reconciliation_record WHERE bill_id = #{billId}")
    int deleteByBillId(@Param("billId") Long billId);
}
