package com.kingdee.eas.custom.perfweb.service;

import com.kingdee.bos.Context;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.BaseRowInfo;
import com.kingdee.shr.base.syssetting.app.io.fileImport.ImportException;
import com.kingdee.shr.perfweb.app.base.evalrule.IsNeedEnum;
import com.kingdee.shr.perfweb.app.base.evalrule.WFNodeDefInfo;
import com.kingdee.shr.perfweb.app.exception.SHRPerfWebBizException;
import com.kingdee.shr.perfweb.app.workflow.GradeTaskNodeInstFactory;
import com.kingdee.shr.perfweb.app.workflow.GradeTaskNodeInstInfo;
import com.kingdee.shr.perfweb.app.workflow.IGradeTaskNodeInst;
import com.kingdee.shr.perfweb.app.workflow.IWholeComment;
import com.kingdee.shr.perfweb.app.workflow.WholeCommentCollection;
import com.kingdee.shr.perfweb.app.workflow.WholeCommentFactory;
import com.kingdee.shr.perfweb.app.workflow.WholeCommentInfo;
import com.kingdee.shr.perfweb.service.GradeTaskNodeInstFileService;
import com.kingdee.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 评分任务节点实例 Excel 导入：仅更新整体评价（wholeComment）。
 * <p>
 * 导出逻辑继承 {@link GradeTaskNodeInstFileService}；导入时不走 saveNodeSumScoreAndGrade，
 * 避免改写节点分数、等级。
 * <p>
 * 导入模板配置中将「业务实现类」指向本类即可。
 */
public class GradeTaskNodeInstWholeCommentFileService extends GradeTaskNodeInstFileService {

    private static final Logger logger = LoggerFactory.getLogger(GradeTaskNodeInstWholeCommentFileService.class);

    @Override
    protected void verifyRowBiz(CoreBaseInfo info) throws ImportException {
        try {
            String id = info.getString("ID");
            checkStatus(id);
            validateWholeComment(info.getString("wholeComment"), id);
        } catch (ImportException e) {
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
        }
    }

    /**
     * 按节点配置校验整体评价：强制必填时 comment 不能为空。
     */
    private void validateWholeComment(String comment, String gradeTaskNodeInstId) throws ImportException {
        try {
            Context ctx = getContext();
            IGradeTaskNodeInst gradeTaskNodeInst = GradeTaskNodeInstFactory.getLocalInstance(ctx);
            GradeTaskNodeInstInfo nodeInstInfo = gradeTaskNodeInst.getGradeTaskNodeInstInfo(
                    " select wfNode.* where id='" + gradeTaskNodeInstId + "'");
            if (nodeInstInfo == null || nodeInstInfo.getWfNode() == null) {
                logger.error("GradeTaskNodeInstWholeCommentFileService#validateWholeComment: wfNode is NULL, id={}", gradeTaskNodeInstId);
                throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
            }
            WFNodeDefInfo wfNode = nodeInstInfo.getWfNode();
            IsNeedEnum wholeCommentNeed = wfNode.getWholeComment();
            if (wholeCommentNeed == IsNeedEnum.NEEDMUST && StringUtils.isEmpty(comment)) {
                throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
            }
        } catch (ImportException e) {
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
        }
    }

    @Override
    protected void importUpdateOnly(BaseRowInfo row) throws ImportException {
        CoreBaseInfo info = transRowToObejct(row);
        String gradeTaskNodeInstId = info.getString("ID");
        String comment = info.getString("wholeComment");
        try {
            Context ctx = getContext();
            IWholeComment iWholeComment = WholeCommentFactory.getLocalInstance(ctx);
            WholeCommentCollection coll = iWholeComment.getWholeCommentCollection(
                    " where gradeTaskNodeInst='" + gradeTaskNodeInstId + "'");
            WholeCommentInfo wholeCommentInfo;
            if (coll == null || coll.isEmpty()) {
                wholeCommentInfo = createWholeComment(ctx, gradeTaskNodeInstId);
            } else {
                wholeCommentInfo = coll.get(0);
            }
            wholeCommentInfo.setComment(comment == null ? "" : comment);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("comment");
            iWholeComment.updatePartial(wholeCommentInfo, sic);
        } catch (ImportException e) {
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
        }
    }

    private WholeCommentInfo createWholeComment(Context ctx, String gradeTaskNodeInstId) throws ImportException {
        try {
            IGradeTaskNodeInst gradeTaskNodeInst = GradeTaskNodeInstFactory.getLocalInstance(ctx);
            GradeTaskNodeInstInfo nodeInstInfo = gradeTaskNodeInst.getGradeTaskNodeInstInfo(
                    " select evaObj.id, wfNode.nodeWeight where id='" + gradeTaskNodeInstId + "'");
            if (nodeInstInfo == null || nodeInstInfo.getEvaObj() == null) {
                throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
            }
            IWholeComment iWholeComment = WholeCommentFactory.getLocalInstance(ctx);
            WholeCommentInfo wholeCommentInfo = new WholeCommentInfo();
            if (nodeInstInfo.getWfNode() != null) {
                wholeCommentInfo.setWeight(nodeInstInfo.getWfNode().getNodeWeight());
            }
            wholeCommentInfo.put("evaObj", nodeInstInfo.getEvaObj().getId().toString());
            wholeCommentInfo.put("gradeTaskNodeInst", gradeTaskNodeInstId);
            iWholeComment.addnew(wholeCommentInfo);
            WholeCommentCollection coll = iWholeComment.getWholeCommentCollection(
                    " where gradeTaskNodeInst='" + gradeTaskNodeInstId + "'");
            if (coll == null || coll.isEmpty()) {
                throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
            }
            return coll.get(0);
        } catch (ImportException e) {
            throw e;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ImportException(new SHRPerfWebBizException(SHRPerfWebBizException.IMPORTEXCELERR));
        }
    }
}
