package com.aucma.base.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.base.mapper.StandardDocumentMapper;
import com.aucma.base.domain.StandardDocument;
import com.aucma.base.service.IStandardDocumentService;

@Service
public class StandardDocumentServiceImpl implements IStandardDocumentService {
    @Autowired
    private StandardDocumentMapper standardDocumentMapper;

    @Override
    public StandardDocument selectStandardDocumentByObjId(Long objId) {
        return standardDocumentMapper.selectStandardDocumentByObjId(objId);
    }

    @Override
    public List<StandardDocument> selectStandardDocumentList(StandardDocument standardDocument) {
        return standardDocumentMapper.selectStandardDocumentList(standardDocument);
    }

    @Override
    public int insertStandardDocument(StandardDocument standardDocument) {
        Date now = DateUtils.getNowDate();
        standardDocument.setCreatedTime(now);
        refreshUploadInfo(standardDocument, now);
        return standardDocumentMapper.insertStandardDocument(standardDocument);
    }

    @Override
    public int updateStandardDocument(StandardDocument standardDocument) {
        Date now = DateUtils.getNowDate();
        standardDocument.setUpdatedTime(now);
        if (Boolean.TRUE.equals(standardDocument.getFileChanged())) {
            // 只有前端明确声明附件变更时，才刷新或清空上传元数据，避免普通字段编辑误伤附件信息。
            refreshUploadInfo(standardDocument, now);
        }
        return standardDocumentMapper.updateStandardDocument(standardDocument);
    }

    @Override
    public int deleteStandardDocumentByObjIds(Long[] objIds) {
        return standardDocumentMapper.deleteStandardDocumentByObjIds(objIds);
    }

    @Override
    public int deleteStandardDocumentByObjId(Long objId) {
        return standardDocumentMapper.deleteStandardDocumentByObjId(objId);
    }

    private void refreshUploadInfo(StandardDocument standardDocument, Date operateTime) {
        if (StringUtils.isNotBlank(standardDocument.getDocumentPath())) {
            // 上传人与上传时间必须和当前实际附件保持一致，后续版本追溯才有意义。
            standardDocument.setUploader(SecurityUtils.getUsername());
            standardDocument.setUploadTime(operateTime);
            return;
        }
        standardDocument.setUploader(null);
        standardDocument.setUploadTime(null);
        standardDocument.setDocumentSize(null);
    }
}
