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.ProdOrderNote;
import com.aucma.production.domain.ProdTaskPool;
import com.aucma.production.mapper.ProdOrderNoteMapper;
import com.aucma.production.mapper.ProdTaskPoolMapper;
import com.aucma.production.service.IProdOrderNoteService;

@Service
public class ProdOrderNoteServiceImpl implements IProdOrderNoteService {
    @Autowired
    private ProdOrderNoteMapper prodOrderNoteMapper;

    @Autowired
    private ProdTaskPoolMapper prodTaskPoolMapper;

    @Override
    public ProdOrderNote selectProdOrderNoteByObjId(Long objId) {
        return prodOrderNoteMapper.selectProdOrderNoteByObjId(objId);
    }

    @Override
    public List<ProdOrderNote> selectProdOrderNoteList(ProdOrderNote prodOrderNote) {
        return prodOrderNoteMapper.selectProdOrderNoteList(prodOrderNote);
    }

    @Override
    public int insertProdOrderNote(ProdOrderNote prodOrderNote) {
        validateNote(prodOrderNote);
        prodOrderNote.setCreatedTime(DateUtils.getNowDate());
        return prodOrderNoteMapper.insertProdOrderNote(prodOrderNote);
    }

    @Override
    public int updateProdOrderNote(ProdOrderNote prodOrderNote) {
        validateNote(prodOrderNote);
        prodOrderNote.setUpdatedTime(DateUtils.getNowDate());
        return prodOrderNoteMapper.updateProdOrderNote(prodOrderNote);
    }

    @Override
    public int deleteProdOrderNoteByObjIds(Long[] objIds) {
        return prodOrderNoteMapper.deleteProdOrderNoteByObjIds(objIds);
    }

    private void validateNote(ProdOrderNote prodOrderNote) {
        if (prodOrderNote == null) {
            throw new ServiceException("工单记录不能为空");
        }
        if (StringUtils.isBlank(prodOrderNote.getOrderCode())) {
            throw new ServiceException("工单编号不能为空");
        }
        if (StringUtils.isBlank(prodOrderNote.getNoteType())) {
            throw new ServiceException("记录类型不能为空");
        }
        if (StringUtils.isBlank(prodOrderNote.getNoteContent())) {
            throw new ServiceException("记录内容不能为空");
        }
        // 为什么新增备注前先校验工单存在：备注和异常记录属于工单执行过程资产，不能允许孤儿记录进入系统。
        ProdTaskPool orderSnapshot = prodTaskPoolMapper.selectProdTaskPoolByOrderCode(prodOrderNote.getOrderCode());
        if (orderSnapshot == null) {
            throw new ServiceException("工单不存在，无法登记备注或异常");
        }
        if (StringUtils.isBlank(prodOrderNote.getStatus())) {
            prodOrderNote.setStatus("0");
        }
    }
}
