package com.hys.app.service.erp.impl;

import com.hys.app.framework.database.mybatisplus.base.BaseServiceImpl;
import com.hys.app.framework.database.WebPage;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.mapper.erp.EnterpriseMapper;
import com.hys.app.model.erp.dos.EnterpriseDO;
import com.hys.app.model.erp.vo.EnterpriseVO;
import com.hys.app.model.erp.dto.EnterpriseDTO;
import com.hys.app.converter.erp.EnterpriseConverter;
import com.hys.app.service.erp.EnterpriseManager;
import com.hys.app.model.erp.dto.EnterpriseQueryParams;
import com.hys.app.util.ValidateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;

/**
 * 企业业务层实现
 *
 * @author 张崧
 * 2024-03-25 15:44:10
 */
@Service
public class EnterpriseManagerImpl extends BaseServiceImpl<EnterpriseMapper, EnterpriseDO> implements EnterpriseManager {
    
    @Autowired
    private EnterpriseConverter converter;
    
    @Override
    public WebPage<EnterpriseVO> list(EnterpriseQueryParams queryParams) {
        WebPage<EnterpriseDO> page = baseMapper.selectPage(queryParams);
        return converter.convertPage(page);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(EnterpriseDTO enterpriseDTO) {
        // 校验参数
        checkParams(enterpriseDTO);
        
        // 保存
        EnterpriseDO enterpriseDO = converter.convert(enterpriseDTO);
        save(enterpriseDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(EnterpriseDTO enterpriseDTO) {
        // 校验参数
        checkParams(enterpriseDTO);
        
        // 更新
        EnterpriseDO enterpriseDO = converter.convert(enterpriseDTO);
        updateById(enterpriseDO);
    }

    @Override
    public EnterpriseVO getDetail(Long id) {
        EnterpriseDO enterpriseDO = getById(id);
        return converter.convert(enterpriseDO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        removeBatchByIds(ids);
    }
    
    private void checkParams(EnterpriseDTO enterpriseDTO) {
        if(ValidateUtil.checkRepeat(baseMapper, EnterpriseDO::getName, enterpriseDTO.getName(), EnterpriseDO::getId, enterpriseDTO.getId())){
            throw new ServiceException("企业名称已存在");
        }
        if(ValidateUtil.checkRepeat(baseMapper, EnterpriseDO::getSn, enterpriseDTO.getSn(), EnterpriseDO::getId, enterpriseDTO.getId())){
            throw new ServiceException("企业编号已存在");
        }

    }
}

