package cn.iocoder.lyzsys.module.tjt.service.office;

import cn.iocoder.lyzsys.framework.common.pojo.PageResult;
import cn.iocoder.lyzsys.framework.common.util.object.BeanUtils;
import cn.iocoder.lyzsys.module.tjt.controller.admin.office.vo.OfficePageReqVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.office.vo.OfficeRespVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.office.vo.OfficeSaveReqVO;
import cn.iocoder.lyzsys.module.tjt.controller.admin.office.vo.OfficeSimpleRespVO;
import cn.iocoder.lyzsys.module.tjt.dal.dataobject.office.OfficeDO;
import cn.iocoder.lyzsys.module.tjt.dal.mysql.employee.EmployeeMapper;
import cn.iocoder.lyzsys.module.tjt.dal.mysql.office.OfficeMapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

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

import static cn.iocoder.lyzsys.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.lyzsys.module.tjt.enums.ErrorCodeConstants.OFFICE_IN_USE;
import static cn.iocoder.lyzsys.module.tjt.enums.ErrorCodeConstants.OFFICE_NOT_EXISTS;

@Service
@Validated
public class OfficeServiceImpl implements OfficeService {

    @Resource
    private OfficeMapper officeMapper;
    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public Long createOffice(OfficeSaveReqVO createReqVO) {
        OfficeDO office = BeanUtils.toBean(createReqVO, OfficeDO.class);
        if (office.getEnabledFlag() == null) {
            office.setEnabledFlag(Boolean.TRUE);
        }
        officeMapper.insert(office);
        return office.getId();
    }

    @Override
    public void updateOffice(OfficeSaveReqVO updateReqVO) {
        validateOfficeExists(updateReqVO.getId());
        officeMapper.updateById(BeanUtils.toBean(updateReqVO, OfficeDO.class));
    }

    @Override
    public void deleteOffice(Long id) {
        validateOfficeExists(id);
        if (employeeMapper.selectCountByOfficeId(id) > 0) {
            throw exception(OFFICE_IN_USE);
        }
        officeMapper.deleteById(id);
    }

    @Override
    public OfficeRespVO getOffice(Long id) {
        return BeanUtils.toBean(validateOfficeExists(id), OfficeRespVO.class);
    }

    @Override
    public OfficeDO validateOfficeExists(Long id) {
        OfficeDO office = officeMapper.selectById(id);
        if (office == null) {
            throw exception(OFFICE_NOT_EXISTS);
        }
        return office;
    }

    @Override
    public PageResult<OfficeRespVO> getOfficePage(OfficePageReqVO pageReqVO) {
        return BeanUtils.toBean(officeMapper.selectPage(pageReqVO), OfficeRespVO.class);
    }

    @Override
    public List<OfficeSimpleRespVO> getOfficeSimpleList() {
        return BeanUtils.toBean(officeMapper.selectSimpleList(), OfficeSimpleRespVO.class);
    }

}
