package com.kingdee.eas.custom.flow.osf;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.bos.workflow.ActivityInstInfo;
import com.kingdee.bos.workflow.AssignmentInfo;
import com.kingdee.bos.workflow.define.ManpowerActivityDef;
import com.kingdee.bos.workflow.define.extended.ApproveActivityDef;
import com.kingdee.bos.workflow.metas.WfAssignmentState;
import com.kingdee.bos.workflow.service.ormrpc.EnactmentServiceFactory;
import com.kingdee.bos.workflow.service.ormrpc.IEnactmentService;
import com.kingdee.eas.base.message.AssignReadFactory;
import com.kingdee.eas.base.message.AssignReadInfo;
import com.kingdee.eas.base.message.IAssignRead;
import com.kingdee.eas.base.message.URLInfo;
import com.kingdee.eas.base.message.util.ProcessCenterUtil;
import com.kingdee.eas.base.multiapprove.*;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.hr.service.app.service.BatchApproveService;
import com.kingdee.eas.util.app.ContextUtil;
import com.kingdee.shr.base.syssetting.ml.SHRWebResource;
import com.kingdee.util.StringUtils;
import com.kingdee.util.UuidException;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description 批量审批接口扩展
 * @Date 2024/12/19 10:37
 * @Created by Heyuan
 */
public class BatchApproveServiceEx extends BatchApproveService {
    private static Logger logger = Logger.getLogger(BatchApproveServiceEx.class);

    @Override
    public Object process(Context ctx, Map param)
            throws EASBizException, BOSException {
        List<Map<String, String>> results = new ArrayList();
        String assignmentIds = (String) param.get("assignmentIds");
        String opinion = (String) param.get("opinion");
        StringBuilder errorMsg = new StringBuilder();
        if (StringUtils.isEmpty(assignmentIds)) {
            errorMsg.append("工作流任务id不能为空!").append(System.lineSeparator());
        } else {
            try {
                assignmentIds = URLDecoder.decode(assignmentIds, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                errorMsg.append("工作流任务id数据错误, " + e.getMessage());
            }
        }
        if (StringUtils.isEmpty(opinion)) {
            errorMsg.append("审批意见不能为空!");
        } else {
            logger.error("opinion_>1 " + opinion);
            try {
                opinion = URLDecoder.decode(opinion, "utf-8");
                logger.error("opinion_>2 " + opinion);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                errorMsg.append("审批意见数据错误, " + e.getMessage());
            }
        }
        logger.error("assignmentIds>2 " + assignmentIds);
        if (errorMsg.length() > 0) {
            Map<String, String> result = new HashMap();
            result.put("code", "0");
            result.put("msg", errorMsg.toString());
            results.add(result);
        }
        String[] assignmentIdArray = assignmentIds.split("[,，]");
        for (int i = 0; i < assignmentIdArray.length; ++i) {
            results.add(this.handle(ctx, assignmentIdArray[i], opinion));
        }
        return results;
    }

    private Map<String, String> handle(Context ctx,
                                       String assignmentId,
                                       String opinion) {
        Map<String, String> result = new HashMap();
        result.put("assignmentId", assignmentId);
        try {
            String bosType = BOSUuid.read(assignmentId).getType().toString();
            if ("9623EB51".equals(bosType)) {
                //任务阅读id
                try {
                    IAssignRead assignReadIns = AssignReadFactory.getLocalInstance(ctx);
                    AssignReadInfo assignReadInfo = assignReadIns.getAssignReadInfo(new ObjectUuidPK(assignmentId));
                    if (assignReadInfo != null) {
                        assignmentId = assignReadInfo.getAssignID().toString();
                    } else {
                        throw new BOSException("任务阅读数据不存在: " + assignmentId);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new BOSException("获取任务阅读数据报错: " + assignmentId);
                }
            }
            //校验流程状态
            String errorMessage = this.verifyData(ctx, assignmentId);
            if (!StringUtils.isEmpty(errorMessage)) {
                throw new BOSException(errorMessage);
            } else {
                this.doApprove(ctx, assignmentId, opinion);
                result.put("code", "1");
                result.put("msg", "成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0");
            String error = e.getMessage();
            if (e instanceof IllegalArgumentException) {
                result.put("msg", "流程id无效 " + assignmentId);
            } else {
                result.put("msg", error);
            }
        }
        return result;
    }

    /**
     * 校验数据
     *
     * @param ctx
     * @param assignmentId
     * @return
     * @throws BOSException
     */
    private String verifyData(Context ctx,
                              String assignmentId)
            throws BOSException {
        IEnactmentService service = EnactmentServiceFactory.createEnactService(ctx);
        Map map = service.getActivityDefAndActivityInstInfo(assignmentId);
        Object act = map.get("ACTIVITYDEF");
        if (!(act instanceof ApproveActivityDef) && act instanceof ManpowerActivityDef) {
            return SHRWebResource.getString("com.kingdee.shr.base.syssetting.CommonserviceResource", "labor_node_not_supported");
        } else {
            AssignmentInfo assignmentInfo = service.getAssignmentById(assignmentId);
            ActivityInstInfo actInstInfo = null;
            if (null != assignmentInfo) {
                actInstInfo = service.getActivityInstByActInstId(assignmentInfo.getActInstId());
            }

            if (actInstInfo != null && (actInstInfo.getState().equalsIgnoreCase("open.not_running.suspended") || actInstInfo.getState().equalsIgnoreCase("open.not_running.blocked"))) {
                return (new MultiApproveException(MultiApproveException.FLOW_NOT_RUNNING)).getMessage();
            } else if (assignmentInfo == null) {
                return (new MultiApproveException(MultiApproveException.ASSIGNMENTINFO_NULL)).getMessage();
            } else if (assignmentInfo.getState().equals(WfAssignmentState.CANCELED)) {
                return (new MultiApproveException(MultiApproveException.ASSIGNMENTSTATE_CANCELED)).getMessage();
            } else if (assignmentInfo.getState().equals(WfAssignmentState.COMPLETED)) {
                return (new MultiApproveException(MultiApproveException.ASSIGNMENTSTATE_COMPLETED)).getMessage();
            } else if (assignmentInfo.getState().equals(WfAssignmentState.REJECTED)) {
                return (new MultiApproveException(MultiApproveException.ASSIGNMENTSTATE_REJECTED)).getMessage();
            } else {
                return assignmentInfo.getState().equals(WfAssignmentState.PROCESSING) ? (new MultiApproveException(MultiApproveException.ASSIGNMENTSTATE_COMPLETED)).getMessage() : null;
            }
        }
    }

    /**
     * 审批
     *
     * @param ctx
     * @param assignmentId
     * @param opinion
     * @return
     * @throws BOSException
     * @throws EASBizException
     */
    private IObjectPK doApprove(Context ctx, String assignmentId, String opinion)
            throws BOSException, EASBizException {
        IMultiApprove multiApprove = MultiApproveFactory.getLocalInstance(ctx);
        MultiApproveInfo mInfo = new MultiApproveInfo();
        mInfo.setAssignment(assignmentId);
        URLInfo info = ProcessCenterUtil.getUrlInfos(assignmentId, ctx);
        String billID = info.getBillID();
        mInfo.setBillId(BOSUuid.read(billID));
        mInfo.setIsPass(ApproveResult.PASS);
        mInfo.setHandlerOpinion(0);
        mInfo.setOpinion(opinion);
        mInfo.setCreator(ContextUtil.getCurrentUserInfo(ctx));
        mInfo.setHandlerContent("同意");
        mInfo.setExtendedProperty("isAddNew", "isAddNew");
        mInfo.setExtendedProperty("assignmentID", assignmentId);
        mInfo.setExtendedProperty("businuessObjectId", billID);
        IObjectPK pk = multiApprove.submit(mInfo);
        return pk;
    }


}
