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.ReconciliationBill;
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 ReconciliationBillRepository extends BaseMapper<ReconciliationBill> {

    /**
     * 根据对账单号查询
     */
    @Select("SELECT * FROM reconciliation_bill WHERE bill_no = #{billNo} AND deleted_at IS NULL LIMIT 1")
    ReconciliationBill findByBillNo(@Param("billNo") String billNo);

    /**
     * 根据对账批次号查询
     */
    @Select("SELECT * FROM reconciliation_bill WHERE batch_no = #{batchNo} AND deleted_at IS NULL ORDER BY created_at DESC")
    List<ReconciliationBill> findByBatchNo(@Param("batchNo") String batchNo);

    /**
     * 分页查询对账单
     */
    IPage<ReconciliationBill> selectPageByConditions(
            Page<ReconciliationBill> page,
            @Param("platform") String platform,
            @Param("shopId") Long shopId,
            @Param("status") String status,
            @Param("resultStatus") String resultStatus,
            @Param("periodStart") LocalDateTime periodStart,
            @Param("periodEnd") LocalDateTime periodEnd
    );

    /**
     * 查询待对账账单
     */
    @Select("SELECT * FROM reconciliation_bill WHERE reconciliation_status = 'pending' AND deleted_at IS NULL ORDER BY created_at ASC LIMIT #{limit}")
    List<ReconciliationBill> findPendingBills(@Param("limit") int limit);

    /**
     * 查询最近对账结果为不一致的账单
     */
    @Select("SELECT * FROM reconciliation_bill WHERE result_status = 'inconsistent' AND deleted_at IS NULL ORDER BY created_at DESC LIMIT #{limit}")
    List<ReconciliationBill> findInconsistentBills(@Param("limit") int limit);

    /**
     * 统计各状态账单数量
     */
    @Select("SELECT reconciliation_status, COUNT(*) as count FROM reconciliation_bill WHERE deleted_at IS NULL GROUP BY reconciliation_status")
    List<ReconciliationBill> countByStatus();

    /**
     * 更新对账状态
     */
    @Select("UPDATE reconciliation_bill SET reconciliation_status = #{status}, updated_at = NOW() WHERE id = #{id}")
    int updateStatus(@Param("id") Long id, @Param("status") String status);
}
