package com.dsk.biz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.biz.domain.BusinessOpenTender;
import com.dsk.biz.domain.bo.BusinessOpenTenderDto;
import com.dsk.biz.mapper.BusinessOpenTenderMapper;
import com.dsk.biz.service.IBusinessOpenTenderService;
import com.dsk.common.core.domain.PageQuery;
import com.dsk.common.core.page.TableDataInfo;
import com.dsk.common.exception.ServiceException;
import jodd.bean.BeanException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * @Author lcl
 * @Data 2023/10/23 16:29
 */
@Slf4j
@Service
public class BusinessOpenTenderServiceImpl implements IBusinessOpenTenderService {

    @Resource
    private BusinessOpenTenderMapper baseMapper;


    @Override
    public TableDataInfo<BusinessOpenTender> selectList(BusinessOpenTenderDto dto, PageQuery pageQuery) {
        return TableDataInfo.build(baseMapper.selectPage(pageQuery.build(),
                Wrappers.<BusinessOpenTender>lambdaQuery().eq(BusinessOpenTender::getBusinessId, dto.getBusinessId())));
    }

    @Override
    public int add(BusinessOpenTender bo) {
        verifyBean(bo);
        BusinessOpenTender openTender = baseMapper.selectOne(Wrappers.<BusinessOpenTender>lambdaQuery()
                .eq(BusinessOpenTender::getTenderer, bo.getTenderer())
                .eq(BusinessOpenTender::getBusinessId,bo.getBusinessId()));
        if(!ObjectUtils.isEmpty(openTender)) throw new ServiceException("当前投标人已存在");
        return baseMapper.insert(bo);
    }

    @Override
    public int edit(BusinessOpenTender bo) {
        if(ObjectUtils.isArray(bo.getId())) throw new BeanException("id不能为空！");
        verifyBean(bo);
        BusinessOpenTender openTender = baseMapper.selectOne(Wrappers.<BusinessOpenTender>lambdaQuery()
                .eq(BusinessOpenTender::getTenderer, bo.getTenderer())
                .eq(BusinessOpenTender::getBusinessId,bo.getBusinessId()));
        if(!ObjectUtils.isEmpty(openTender) && !openTender.getId().equals(bo.getId())) throw new ServiceException("当前投标人已存在");
        return baseMapper.updateById(bo);
    }

    @Override
    public int remove(Long[] ids) {
        return baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    private void verifyBean(BusinessOpenTender bo){
        if(ObjectUtils.isArray(bo.getBusinessId())) throw new BeanException("项目id不能为空！");
        if(ObjectUtils.isArray(bo.getTenderer())) throw new BeanException("开标人不能为空！");
        if(ObjectUtils.isArray(bo.getTendererNature())) throw new BeanException("企业性质不能为空！");
        if(ObjectUtils.isArray(bo.getTenderAmount())) throw new BeanException("投标金额不能为空！");
    }
}
