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

import com.hys.app.converter.erp.PostConverter;
import com.hys.app.framework.database.WebPage;
import com.hys.app.framework.exception.ServiceException;
import com.hys.app.framework.database.mybatisplus.base.BaseServiceImpl;
import com.hys.app.mapper.erp.PostMapper;
import com.hys.app.model.erp.dos.PostDO;
import com.hys.app.model.erp.dto.PostDTO;
import com.hys.app.model.erp.dto.PostQueryParams;
import com.hys.app.model.erp.vo.PostVO;
import com.hys.app.service.erp.PostManager;
import com.hys.app.service.system.AdminUserManager;
import com.hys.app.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 岗位业务层实现
 *
 * @author 张崧
 * 2023-11-29 17:15:22
 */
@Service
public class PostManagerImpl extends BaseServiceImpl<PostMapper, PostDO> implements PostManager {

    @Autowired
    private PostConverter converter;

    @Autowired
    private AdminUserManager adminUserManager;

    @Override
    public WebPage<PostVO> list(PostQueryParams queryParams) {
        WebPage<PostDO> webPage = baseMapper.selectPage(queryParams);
        return converter.convert(webPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(PostDTO postDTO) {
        check(postDTO);
        save(converter.convert(postDTO));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(PostDTO postDTO) {
        check(postDTO);
        updateById(converter.convert(postDTO));
    }

    @Override
    public PostVO getDetail(Long id) {
        return converter.convert(getById(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List<PostDO> list = listByIds(ids);

        for (PostDO postDO : list) {
            long count = adminUserManager.countByPostId(postDO.getId());
            if(count > 0){
                throw new ServiceException("岗位：" + postDO.getName() + " 存在关联的人员，不能删除");
            }
        }

        removeByIds(ids);
    }

    @Override
    public List<PostVO> listAll() {
        return converter.convert(baseMapper.listAll());
    }

    private void check(PostDTO postDTO) {
        if (ValidateUtil.checkRepeat(baseMapper, PostDO::getSn, postDTO.getSn(), PostDO::getId, postDTO.getId())) {
            throw new ServiceException("岗位编号已存在");
        }
    }

}

