package com.aucma.production.service.impl;

import java.util.List;

import com.aucma.common.exception.ServiceException;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.aucma.production.domain.ProdTeamShift;
import com.aucma.production.mapper.ProdTeamShiftMapper;
import com.aucma.production.service.IProdTeamShiftService;

@Service
public class ProdTeamShiftServiceImpl implements IProdTeamShiftService {
    @Autowired
    private ProdTeamShiftMapper prodTeamShiftMapper;

    @Override
    public ProdTeamShift selectProdTeamShiftByObjId(Long objId) {
        return prodTeamShiftMapper.selectProdTeamShiftByObjId(objId);
    }

    @Override
    public List<ProdTeamShift> selectProdTeamShiftList(ProdTeamShift prodTeamShift) {
        return prodTeamShiftMapper.selectProdTeamShiftList(prodTeamShift);
    }

    @Override
    public int insertProdTeamShift(ProdTeamShift prodTeamShift) {
        validateShift(prodTeamShift);
        ensureShiftUnique(prodTeamShift);
        prodTeamShift.setCreatedTime(DateUtils.getNowDate());
        return prodTeamShiftMapper.insertProdTeamShift(prodTeamShift);
    }

    @Override
    public int updateProdTeamShift(ProdTeamShift prodTeamShift) {
        validateShift(prodTeamShift);
        ensureShiftUnique(prodTeamShift);
        prodTeamShift.setUpdatedTime(DateUtils.getNowDate());
        return prodTeamShiftMapper.updateProdTeamShift(prodTeamShift);
    }

    @Override
    public int deleteProdTeamShiftByObjIds(Long[] objIds) {
        return prodTeamShiftMapper.deleteProdTeamShiftByObjIds(objIds);
    }

    private void validateShift(ProdTeamShift prodTeamShift) {
        if (prodTeamShift == null) {
            throw new ServiceException("排班数据不能为空");
        }
        if (StringUtils.isBlank(prodTeamShift.getTeamCode())) {
            throw new ServiceException("班组不能为空");
        }
        if (prodTeamShift.getShiftDate() == null) {
            throw new ServiceException("排班日期不能为空");
        }
        if (StringUtils.isBlank(prodTeamShift.getShiftCode())) {
            throw new ServiceException("班次不能为空");
        }
        if (StringUtils.isBlank(prodTeamShift.getStatus())) {
            prodTeamShift.setStatus("0");
        }
    }

    private void ensureShiftUnique(ProdTeamShift prodTeamShift) {
        ProdTeamShift existed = prodTeamShiftMapper.selectUniqueShift(prodTeamShift);
        if (existed != null && !existed.getObjId().equals(prodTeamShift.getObjId())) {
            throw new ServiceException("该班组在指定日期与班次下已存在排班记录");
        }
    }
}
