package com.bcxin.tenant.open.domains.utils;

import com.bcxin.tenant.open.document.domains.documents.RdProjectDocument;
import com.bcxin.tenant.open.document.domains.repositories.RdProjectDocumentRepository;
import com.bcxin.tenant.open.domains.entities.RdProjectEntity;
import com.bcxin.tenant.open.infrastructures.exceptions.DocumentIndexNoFoundException;
import com.bcxin.tenant.open.infrastructures.utils.ExceptionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Optional;

public class RdProjectEntityUtils {
    private static final Logger logger = LoggerFactory.getLogger(RdProjectEntityUtils.class);
    public static RdProjectDocument toDocument(RdProjectEntity ii,
                                               RdProjectDocumentRepository projectDocumentRepository) {
        try {
            RdProjectDocument document = null;
            Optional<RdProjectDocument> projectDocumentOptional =
                    projectDocumentRepository.findById(ii.getId());
            if (projectDocumentOptional.isPresent()) {
                document = projectDocumentOptional.get();
            }

            if (document == null) {
                document = new RdProjectDocument();

                document.setId(ii.getId());
            }
            document.rest();
            document.setName(ii.getName());
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if(ii.getBeginDate()!=null) {
                document.setBeginDate(dateFormat.format(ii.getBeginDate()));
            }else{
                document.setBeginDate(null);
            }

            document.setEndDate(null);
            if(ii.getBeginDate()!=null) {
                document.setEndDate(dateFormat.format(ii.getEndDate()));
            }
            document.setOrganizationId(ii.getOrganizationId());
            document.setPrincipalId(ii.getPrincipalId());
            document.setState(ii.getState());
            document.updateWord(ii.getName(), ii.getAddress());

            return document;
        } catch (Exception ex) {
            if(ExceptionUtil.getStackMessage(ex).contains("no such index")) {
                throw new DocumentIndexNoFoundException("索引异常", ex);
            }
            logger.error("项目制度-解析数据发生异常:id={};name={};", ii.getId(), ii.getName(), ex);

            return null;
        }
    }
}
