package com.trade.client.companyrelated.service.impl;

import java.util.List;

import javax.annotation.Resource;

import cn.hutool.core.util.RandomUtil;
import com.trade.client.companyrelated.service.VendorEntityCService;
import com.trade.service.companyrelated.domain.VendorEntity;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.trade.client.companyrelated.service.VendorEntityCService;
import com.trade.client.security.utils.UserUtils;
import com.trade.common.constant.HttpStatus;
import com.trade.common.exception.ServiceException;
import com.trade.service.companyrelated.domain.VendorEntity;
import com.trade.service.companyrelated.domain.vo.VendorEntitySearch;
import com.trade.service.companyrelated.mapper.VendorEntityMapper;
import com.trade.service.companyrelated.service.IVendorEntityService;

/**
 * <p>
 * 供应商信息 服务实现类
 * </p>
 */
@Service
public class VendorEntityCServiceImp extends ServiceImpl<VendorEntityMapper, VendorEntity> implements VendorEntityCService {

    @Resource
    private IVendorEntityService VendorEntityService;

    @Override
    public void add(VendorEntity addEntity) {
        // 参数校验
        preCheckAndSetParams(addEntity);
        // 保存进口商信息
        this.save(addEntity);
    }

    /**
     * 参数校验
     * 
     * @param vendorEntity 供应商信息
     */
    private void preCheckAndSetParams(VendorEntity vendorEntity) {
        VendorEntity exist = getBaseMapper().getByUserIdAndEntityName(vendorEntity.getUserId(),
                vendorEntity.getEntityName());
        if (exist != null) {
            throw new ServiceException("企业已存在", HttpStatus.BAD_REQUEST);
        }
        vendorEntity.setEntityNo(RandomUtil.randomNumbers(7));
        vendorEntity.setUserId(UserUtils.getCustomerUserId());
    }

    @Override
    public void update(VendorEntity updateEntity) {
        // 提醒前端应该限制不允许修改企业名称
        VendorEntity VendorEntity = this.getById(updateEntity.getId());
        if (VendorEntity == null) {
            throw new ServiceException("供应商信息不存在", HttpStatus.BAD_REQUEST);
        }
        this.updateById(updateEntity);
    }

    @Override
    public PageInfo<VendorEntity> queryListBySearch(VendorEntitySearch search) {
        return VendorEntityService.queryListBySearch(search);
    }

    @Override
    public List<VendorEntity> getListByUserId(Long userId) {
        return VendorEntityService.getListByUserId(userId);
    }

    @Override
    public VendorEntity getByEntityId(Long bizEntityId) {
        return VendorEntityService.getByEntityId(bizEntityId);
    }
}
