package com.kingdee.eas.custom.perfwebinterview.handler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.EntityViewInfo;
import com.kingdee.bos.metadata.entity.FilterInfo;
import com.kingdee.bos.metadata.entity.FilterItemInfo;
import com.kingdee.bos.metadata.entity.SelectorItemCollection;
import com.kingdee.eas.custom.perfwebinterview.IInterviewRecord;
import com.kingdee.eas.custom.perfwebinterview.InterviewRecordCollection;
import com.kingdee.eas.custom.perfwebinterview.InterviewRecordFactory;
import com.kingdee.eas.custom.perfwebinterview.InterviewRecordInfo;
import com.kingdee.eas.framework.CoreBaseInfo;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.base.syssetting.web.handler.EditHandler;
import com.kingdee.shr.base.syssetting.web.support.fieldrule.FieldRuleHelper;
import com.kingdee.shr.perfweb.app.base.evalplan.EvaResultSummaryFactory;
import com.kingdee.shr.perfweb.app.base.evalplan.EvaResultSummaryInfo;
import com.kingdee.shr.perfweb.app.base.evalplan.IEvaResultSummary;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @Description 面谈记录表单Handler
 * @Date 2025/4/11 16:24
 * @Created by Heyuan
 */
public class InterviewRecordEditHandler extends EditHandler {
    private static Logger logger = Logger.getLogger(InterviewRecordEditHandler.class);
    private Context ctx = SHRContext.getInstance().getContext();

    protected CoreBaseInfo initModel(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap) throws SHRWebException {
        this.shrFieldPerm = this.fieldPermInit(request);
        FieldRuleHelper.initFieldRule(this.getContext(), this.getUIViewInfo(request).getUipk());
        CoreBaseInfo model = null;
        if (request.getAttribute("InitDataObject") != null) {
            model = (CoreBaseInfo) request.getAttribute("InitDataObject");
        } else {
            //考核结果id
            String evaResultId = request.getParameter("evaResultId");
            if (StringUtils.isEmpty(evaResultId)) {
                logger.error("evaResultId is empty");
                throw new ShrWebBizException("evaResultId can not be empty");
            }
            //通过考核结果id查找面谈记录
            try {
                IInterviewRecord interviewRecord = InterviewRecordFactory.getLocalInstance(ctx);
                SelectorItemCollection sic = getSelectors(request);
                FilterInfo filterInfo = new FilterInfo();
                filterInfo.getFilterItems().add(new FilterItemInfo("evaResult", evaResultId));
                EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, sic, null);
                InterviewRecordCollection infoCollection = interviewRecord.getInterviewRecordCollection(viewInfo);
                if (infoCollection.size() > 0) {
                    model = infoCollection.get(0);
                } else {
                    model = this.createNewModel(request, response, modelMap);
                }
            } catch (BOSException e) {
                logger.error("BOSException", e);
                throw new ShrWebBizException(e);
            }
        }
        this.afterInitModel(request, response, model);
        modelMap.addAttribute("model", model);
        if (model != null) {
            if (model.getId() != null) {
                modelMap.addAttribute("billId", URLEncoder.encode(model.getId().toString()));
            }

            try {
                SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
                model.put("attachmentID", "attachment_" + random.nextInt(1000) + System.currentTimeMillis());
            } catch (NoSuchAlgorithmException e) {
                logger.error("NoSuchAlgorithmException", e);
                throw new SHRWebException(e.getMessage(), e);
            }
        }
        return model;
    }

    /**
     * 创建新单据
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    protected CoreBaseInfo createNewModel(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap
    ) throws SHRWebException {
        InterviewRecordInfo info = (InterviewRecordInfo) super.createNewModel(request, response, modelMap);
        if (info != null) {
            String evaResultId = request.getParameter("evaResultId");
            if (StringUtils.isEmpty(evaResultId)) {
                logger.error("evaResultId is empty");
                throw new ShrWebBizException("evaResultId can not be empty");
            }
            try {
                //绑定考核结果数据
                IEvaResultSummary iEvaResultSummary = EvaResultSummaryFactory.getLocalInstance(ctx);
                EvaResultSummaryInfo evaResultSummaryInfo = iEvaResultSummary.getEvaResultSummaryInfo(new ObjectUuidPK(evaResultId));
                info.setGradeLevel(evaResultSummaryInfo.getLastGradeLevel());
                info.setEvaResult(evaResultSummaryInfo);
            } catch (Exception e) {
                logger.error("createNewModel failure: ", e);
                throw new ShrWebBizException("evaResult not exist, please check");
            }
        }
        return info;
    }

    /**
     * 保存后置方法
     * 保存后，更新考核结果表上“是否维护面谈记录”为是
     *
     * @param request
     * @param response
     * @param model
     * @throws SHRWebException
     */
    protected void afterSave(
            HttpServletRequest request,
            HttpServletResponse response,
            CoreBaseInfo model
    ) throws SHRWebException {
        try {
            InterviewRecordInfo info = (InterviewRecordInfo) model;
            EvaResultSummaryInfo evaResultSummaryInfo = info.getEvaResult();
            evaResultSummaryInfo.put("interviewed", true);
            IEvaResultSummary iEvaResultSummary = EvaResultSummaryFactory.getLocalInstance(ctx);
            SelectorItemCollection sic = new SelectorItemCollection();
            sic.add("interviewed");
            iEvaResultSummary.updatePartial(evaResultSummaryInfo, sic);
        } catch (Exception e) {
            logger.error("afterSave failure: ", e);
            throw new ShrWebBizException(e);
        }
    }
}
