package com.njcn.rdms.module.project.dal.mysql.product;

import com.njcn.rdms.framework.mybatis.core.mapper.BaseMapperX;
import com.njcn.rdms.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.njcn.rdms.module.project.dal.dataobject.product.ProductDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

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

@Mapper
public interface ProductMapper extends BaseMapperX<ProductDO> {

    default ProductDO selectByCode(String code) {
        return selectOne(ProductDO::getCode, code);
    }

    default ProductDO selectByName(String name) {
        return selectOne(ProductDO::getName, name);
    }

    default List<ProductDO> selectListByCodePrefix(String codePrefix) {
        return selectList(new LambdaQueryWrapperX<ProductDO>()
                .likeRight(ProductDO::getCode, codePrefix)
                .orderByDesc(ProductDO::getCode));
    }

    @Select("""
            SELECT status_code AS statusCode, COUNT(*) AS countValue
            FROM rdms_product
            WHERE deleted = b'0'
            GROUP BY status_code
            """)
    List<Map<String, Object>> selectStatusCountList();

    default int updateStatusByIdAndStatus(Long id, String fromStatus, String toStatus, String lastStatusReason) {
        ProductDO update = new ProductDO();
        update.setStatusCode(toStatus);
        update.setLastStatusReason(lastStatusReason);
        return update(update, new LambdaQueryWrapperX<ProductDO>()
                .eq(ProductDO::getId, id)
                .eq(ProductDO::getStatusCode, fromStatus));
    }

    default int deleteByIdAndStatus(Long id, String statusCode) {
        return delete(new LambdaQueryWrapperX<ProductDO>()
                .eq(ProductDO::getId, id)
                .eq(ProductDO::getStatusCode, statusCode));
    }
}
