package cn.iocoder.yudao.module.asset.dal.mysql.contract;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.asset.controller.admin.contract.vo.ContractPageReqVO;
import cn.iocoder.yudao.module.asset.dal.dataobject.contract.ContractDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;

/**
 * 车辆租赁合同 Mapper
 *
 * @author 芋道源码
 */
@Mapper
public interface ContractMapper extends BaseMapperX<ContractDO> {

    default PageResult<ContractDO> selectPage(ContractPageReqVO reqVO) {
        return selectPage(reqVO, new LambdaQueryWrapperX<ContractDO>()
                .likeIfPresent(ContractDO::getContractCode, reqVO.getContractCode())
                .eqIfPresent(ContractDO::getContractType, reqVO.getContractType())
                .likeIfPresent(ContractDO::getProjectName, reqVO.getProjectName())
                .eqIfPresent(ContractDO::getCustomerId, reqVO.getCustomerId())
                .likeIfPresent(ContractDO::getCustomerName, reqVO.getCustomerName())
                .eqIfPresent(ContractDO::getApprovalStatus, reqVO.getApprovalStatus())
                .eqIfPresent(ContractDO::getContractStatus, reqVO.getContractStatus())
                .betweenIfPresent(ContractDO::getStartDate, reqVO.getStartDate())
                .betweenIfPresent(ContractDO::getEndDate, reqVO.getEndDate())
                .eqIfPresent(ContractDO::getBusinessDeptId, reqVO.getBusinessDeptId())
                .eqIfPresent(ContractDO::getSigningCompany, reqVO.getSigningCompany())
                .eqIfPresent(ContractDO::getBusinessManagerId, reqVO.getBusinessManagerId())
                .likeIfPresent(ContractDO::getCreator, reqVO.getCreator())
                .orderByDesc(ContractDO::getId));
    }

    @Select("SELECT contract_code FROM asset_contract WHERE contract_code LIKE CONCAT(#{prefix}, '%') AND deleted = 0 ORDER BY contract_code DESC LIMIT 1")
    String selectMaxContractCodeByPrefix(@Param("prefix") String prefix);

    /**
     * 检查车辆在指定时间段内是否有有效合同
     */
    @Select("SELECT COUNT(*) FROM asset_contract c " +
            "INNER JOIN asset_contract_vehicle cv ON c.id = cv.contract_id " +
            "WHERE cv.vehicle_id = #{vehicleId} " +
            "AND c.contract_status IN (1, 2) " +
            "AND c.deleted = 0 AND cv.deleted = 0 " +
            "AND NOT (c.end_date < #{startDate} OR c.start_date > #{endDate})")
    int countActiveContractsByVehicleAndDateRange(@Param("vehicleId") Long vehicleId,
                                                   @Param("startDate") LocalDate startDate,
                                                   @Param("endDate") LocalDate endDate);

}
