package com.yc.ship.module.product.dal.mysql.voyagestockdetail;

import com.yc.ship.framework.mybatis.core.mapper.BaseMapperX;
import com.yc.ship.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.yc.ship.framework.tenant.core.aop.TenantIgnore;
import com.yc.ship.module.product.dal.dataobject.voyagestockdetail.VoyageStockDetailDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal;
import java.util.List;

/**
 * 航次库存 Mapper
 *
 * @author 管理员
 */
@Mapper
public interface VoyageStockDetailMapper extends BaseMapperX<VoyageStockDetailDO> {


    @TenantIgnore
    default List<VoyageStockDetailDO> selectListByVoyageId(Long voyageId) {
        return selectList(new LambdaQueryWrapperX<VoyageStockDetailDO>()
                .eq(VoyageStockDetailDO::getVoyageId, voyageId)
                .orderByAsc(VoyageStockDetailDO::getRoomModelId)
                .orderByAsc(VoyageStockDetailDO::getFloor));
    }

    @TenantIgnore
    default void deleteByVoyageId(Long voyageId) {
        delete(new LambdaQueryWrapperX<VoyageStockDetailDO>()
                .eq(VoyageStockDetailDO::getVoyageId, voyageId));
    }

    @TenantIgnore
    default void deleteByVoyageIds(List<Long> voyageIds) {
        delete(new LambdaQueryWrapperX<VoyageStockDetailDO>()
                .in(VoyageStockDetailDO::getVoyageId, voyageIds));
    }

    /**
     * 从 system_dist_data 表查询实际房间数据
     *
     * @param voyageId 航次ID
     * @return 实际房间数
     */
    @Select("SELECT IFNULL(value, 0) FROM system_dict_data WHERE dict_type= 'inside_cabin_count' and status = 0 and deleted = 0 LIMIT 1")
    @TenantIgnore
    BigDecimal selectRealTotalNumFromDistData(@Param("voyageId") Long voyageId);

    /**
     * 根据航次ID查询已分配房间数
     * 已分配房间数 = (领队数 leader_total_num + 陪同数 with_total_num) / 2
     *
     * @param voyageId 航次ID
     * @return 已分配房间数
     */
    @Select("SELECT IFNULL(SUM(t.leader_total_num + t.with_total_num) / 2.0, 0) " +
            "FROM trade_order_total t " +
            "INNER JOIN trade_order o ON t.old_order_id = o.id  " +
            "WHERE o.voyage_id = #{voyageId} AND o.deleted = 0 AND t.deleted = 0")
    @TenantIgnore
    Double selectAllocatedRoomCountByVoyageId(@Param("voyageId") Long voyageId);


}