package org.springblade.modules.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wn.common.datamodel.ModelConvertUtil;
import com.wn.common.validator.Validator;
import org.springblade.modules.app.common.dto.SlaughterBuyerRelationLogDTO;
import org.springblade.modules.app.common.enums.RelationTypeEnum;
import org.springblade.modules.app.common.query.RelationQuery;
import org.springblade.modules.app.constant.DbField;
import org.springblade.modules.app.constant.ErrorCode;
import org.springblade.modules.app.entity.SlaughterBuyerRelationLogDO;
import org.springblade.modules.app.mapper.SlaughterBuyerRelationLogMapper;
import org.springblade.modules.app.service.ISlaughterBuyerRelationLogService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 代宰户与屠宰场绑定记录表 服务实现类
 * </p>
 *
 * @author zhangK
 * @since 2022-01-13
 */
@Service
public class SlaughterBuyerRelationLogServiceImpl extends ServiceImpl<SlaughterBuyerRelationLogMapper, SlaughterBuyerRelationLogDO> implements ISlaughterBuyerRelationLogService {

    @Override
    public Long insert(SlaughterBuyerRelationLogDTO dto) {
        SlaughterBuyerRelationLogDO slaughterBuyerRelationLogDO = dto.copyTo(SlaughterBuyerRelationLogDO.class);
        Validator.isTrue(save(slaughterBuyerRelationLogDO), ErrorCode.SAVE_DATA_INTO_DB_ERROR);
        return slaughterBuyerRelationLogDO.getId();
    }

    @Override
    public List<SlaughterBuyerRelationLogDTO> queryUnbindList(RelationQuery query) {
        QueryWrapper<SlaughterBuyerRelationLogDO> wrapper = new QueryWrapper<>();
        wrapper.eq(query.getBuyerUserId() != null, DbField.BUYER_USER_ID, query.getBuyerUserId());
        wrapper.eq(query.getSlaughterHouseId() != null, DbField.SLAUGHTER_HOUSE_ID, query.getSlaughterHouseId());
        wrapper.eq(DbField.TYPE , RelationTypeEnum.UNBIND.getCode());
        wrapper.orderByDesc(DbField.CREATED_TIME);
        List<SlaughterBuyerRelationLogDO> list = list(wrapper);
        return CollectionUtils.isNotEmpty(list) ? ModelConvertUtil.copyListTo(list, SlaughterBuyerRelationLogDTO.class) : null;
    }
}
