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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.util.BOSUuid;
import com.kingdee.eas.base.attachment.*;
import com.kingdee.eas.base.attachment.common.AttachmentHelper;
import com.kingdee.eas.basedata.person.PersonInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewFactory;
import com.kingdee.eas.custom.esign.ESignGlobalStatusOverviewInfo;
import com.kingdee.eas.custom.esign.IESignGlobalStatusOverview;
import com.kingdee.eas.custom.esign.bizEnum.EsignStatusEnum;
import com.kingdee.eas.custom.esign.tsign.hz.comm.EsignHttpResponse;
import com.kingdee.eas.custom.esign.tsign.hz.exception.EsignException;
import com.kingdee.eas.custom.esign.util.DownloaderUtil;
import com.kingdee.eas.custom.esign.util.EsignHttpUtil;
import com.kingdee.eas.custom.esign.util.SyncSignedFilesUtil;
import com.kingdee.eas.hr.base.app.util.SHRBizBillAttachmentReverseUtils;
import com.kingdee.shr.attachment.*;
import com.kingdee.shr.attachment.AttachmentTypeEnum;
import com.kingdee.shr.base.syssetting.api.bean.BatchMessageTipsBody;
import com.kingdee.shr.base.syssetting.api.bean.BatchMessageTipsHeader;
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.ml.SHRWebResource;
import com.kingdee.shr.base.syssetting.web.handler.ListHandler;
import com.kingdee.shr.ml.util.MutilanUtils;
import com.kingdee.util.LocaleUtils;
import com.kingdee.util.STConverter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/**
 * description: ESignGlobalStatusOverviewHandler <br>
 * date: 21/11/2025 下午 4:19 <br>
 * author: lhbj <br>
 * version: 1.0 <br>
 */
public class ESignGlobalStatusOverviewListHandler extends ListHandler {
    public Context getCtx() {
        return SHRContext.getInstance().getContext();
    }

    /**
     * 基于文件发起签署
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String create_by_fileAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String billId = this.getBillId(request);
        int failure = 0;
        int success = 0;
        try {
            if (billId.indexOf(",") >= 0) {
                throw new EsignException("请选择一行记录发起签署");
            }
            IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(this.getCtx());
            SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
            selectorItemCollection.add(new SelectorItemInfo("*"));
            selectorItemCollection.add(new SelectorItemInfo("person.id"));
            selectorItemCollection.add(new SelectorItemInfo("operator.id"));
            ESignGlobalStatusOverviewInfo info = globalStatusOverview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(billId));
            PersonInfo person = info.getPerson();
            PersonInfo operator = info.getOperator();
            String personId = null;
            if (null != person && null != person.getId()) {
                personId = person.getId().toString();
            }
            String operatorId = null;
            if (null != operator && null != operator.getId()) {
                operatorId = operator.getId().toString();
            }
            if (StringUtils.isNotBlank(info.getSignFlowId())) {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                body.setMuitTipsState(Boolean.FALSE);
                body.setMuitTipsMessage("已经发起签署了，不能重复发起");
                body.setId(billId);
                batchMessageTipsHeader.addResult(body);
            } else {
                EsignHttpResponse httpRes = EsignHttpUtil.create_by_file(this.getCtx(), personId, info.getFileName(), operatorId, info.getEfileId(),
                        EsignStatusEnum.SIGNING, info.getRequestParams());
                if (httpRes.getStatus() >= 200 && httpRes.getStatus() < 300) {
                    JSONObject object = JSON.parseObject(httpRes.getBody());
                    if ("0".equals(String.valueOf(object.get("code")))) {
                        BatchMessageTipsBody body = new BatchMessageTipsBody();
                        body.setMuitTipsState(Boolean.TRUE);
                        body.setMuitTipsMessage(httpRes.getBody());
                        body.setId(billId);
                        batchMessageTipsHeader.addResult(body);
                        success++;
                    } else {
                        BatchMessageTipsBody body = new BatchMessageTipsBody();
                        body.setMuitTipsState(Boolean.FALSE);
                        body.setMuitTipsMessage(httpRes.getBody());
                        body.setId(billId);
                        batchMessageTipsHeader.addResult(body);
                    }
                } else {
                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage(httpRes.getBody());
                    body.setId(billId);
                    batchMessageTipsHeader.addResult(body);
                }
            }


        } catch (EsignException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
        batchMessageTipsHeader.setBillId(billId);
        batchMessageTipsHeader.setFailureCount((success <= 0 ? 1 : 0));
        batchMessageTipsHeader.setSuccessCount(success);
        this.writeSuccessData(batchMessageTipsHeader);
        return null;
    }

    /**
     * 撤销签署流程
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String revoke_by_fileAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String billId = this.getBillId(request);
        String revokeReason = request.getParameter("revokeReason");
        int failure = 0;
        int success = 0;
        try {
            if (billId.indexOf(",") >= 0) {
                throw new EsignException("请选择一行记录发起签署");
            }

            IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(this.getCtx());
            SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
            selectorItemCollection.add(new SelectorItemInfo("*"));
            selectorItemCollection.add(new SelectorItemInfo("person.id"));
            selectorItemCollection.add(new SelectorItemInfo("operator.id"));
            ESignGlobalStatusOverviewInfo info = globalStatusOverview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(billId));
            PersonInfo person = info.getPerson();
            PersonInfo operator = info.getOperator();
            String personId = null;
            if (null != person && null != person.getId()) {
                personId = person.getId().toString();
            }
            String operatorId = null;
            if (null != operator && null != operator.getId()) {
                operatorId = operator.getId().toString();
            }
            if (StringUtils.isBlank(info.getSignFlowId())) {
                throw new EsignException("没有签署流程id");
            }
            EsignHttpResponse httpRes = EsignHttpUtil.revoke_by_file(this.getCtx(), info.getSignFlowId(), revokeReason, info.getEfileId());
            if (httpRes.getStatus() >= 200 && httpRes.getStatus() < 300) {
                JSONObject object = JSON.parseObject(httpRes.getBody());
                if ("0".equals(String.valueOf(object.get("code")))) {

                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    body.setMuitTipsState(Boolean.TRUE);
                    body.setMuitTipsMessage(httpRes.getBody());
                    body.setId(billId);
                    batchMessageTipsHeader.addResult(body);
                    success++;
                } else {
                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage(httpRes.getBody());
                    body.setId(billId);
                    batchMessageTipsHeader.addResult(body);
                }
            } else {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                body.setMuitTipsState(Boolean.FALSE);
                body.setMuitTipsMessage(httpRes.getBody());
                body.setId(billId);
                batchMessageTipsHeader.addResult(body);
            }

        } catch (EsignException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
        batchMessageTipsHeader.setBillId(billId);
        batchMessageTipsHeader.setFailureCount((success <= 0 ? 1 : 0));
        batchMessageTipsHeader.setSuccessCount(success);
        this.writeSuccessData(batchMessageTipsHeader);
        return null;
    }

    /**
     * 催签流程中签署人
     *
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String urge_by_fileAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String billId = this.getBillId(request);
        int failure = 0;
        int success = 0;
        try {
            if (billId.indexOf(",") >= 0) {
                throw new EsignException("请选择一行记录发起签署");
            }
            IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(this.getCtx());
            SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
            selectorItemCollection.add(new SelectorItemInfo("*"));
            selectorItemCollection.add(new SelectorItemInfo("person.id"));
            selectorItemCollection.add(new SelectorItemInfo("operator.id"));
            ESignGlobalStatusOverviewInfo info = globalStatusOverview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(billId));
            PersonInfo person = info.getPerson();
            PersonInfo operator = info.getOperator();
            String personId = null;
            if (null != person && null != person.getId()) {
                personId = person.getId().toString();
            }
            String operatorId = null;
            if (null != operator && null != operator.getId()) {
                operatorId = operator.getId().toString();
            }

            if (StringUtils.isBlank(info.getSignFlowId())) {
                throw new EsignException("没有签署流程id");
            }
            String json = info.getRequestParams();
            JSONObject params = JSON.parseObject(json);
            Map<String, Object> jsonMap = Maps.newHashMap();
            Set<String> noticeSet = Sets.newHashSet();
            JSONArray jsonArray = params.getJSONArray("signers");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject param = jsonArray.getJSONObject(i);
                JSONObject noticeConfig = param.getJSONObject("noticeConfig");
                if (null != noticeConfig) {
                    String noticeTypeStr = noticeConfig.getString("noticeTypes");
                    if (StringUtils.isNotBlank(noticeTypeStr)) {
                        String[] noticeTypes = noticeTypeStr.split(",");
                        for (String nts : noticeTypes) {
                            noticeSet.add(nts);
                        }
                    }
                }
            }
            jsonMap.put("noticeTypes", StringUtils.join(noticeSet.toArray(), ","));
            EsignHttpResponse httpRes = EsignHttpUtil.urge_by_file(this.getCtx(), info.getSignFlowId(), JSON.toJSONString(jsonMap), info.getEfileId());
            if (httpRes.getStatus() >= 200 && httpRes.getStatus() < 300) {
                JSONObject object = JSON.parseObject(httpRes.getBody());
                if ("0".equals(String.valueOf(object.get("code")))) {

                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    body.setMuitTipsState(Boolean.TRUE);
                    body.setMuitTipsMessage(httpRes.getBody());
                    body.setId(billId);
                    batchMessageTipsHeader.addResult(body);
                    success++;
                } else {
                    BatchMessageTipsBody body = new BatchMessageTipsBody();
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage(httpRes.getBody());
                    body.setId(billId);
                    batchMessageTipsHeader.addResult(body);
                }
            } else {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                body.setMuitTipsState(Boolean.FALSE);
                body.setMuitTipsMessage(httpRes.getBody());
                body.setId(billId);
                batchMessageTipsHeader.addResult(body);
            }
        } catch (EsignException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
        batchMessageTipsHeader.setBillId(billId);
        batchMessageTipsHeader.setFailureCount((success <= 0 ? 1 : 0));
        batchMessageTipsHeader.setSuccessCount(success);
        this.writeSuccessData(batchMessageTipsHeader);
        return null;
    }

    /**
     * 预览附件
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String previewAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {

        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String billId = this.getBillId(request);
        String update = request.getParameter("upd");
        int failure = 0;
        int success = 0;
        try {
            if (billId.indexOf(",") >= 0) {
                throw new EsignException("请选择一行记录发起签署");
            }
            ISHRAttachmentExt SHRAttchExt = SHRAttachmentExtFactory.getLocalInstance(this.getCtx());
            IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(this.getCtx());
            SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
            selectorItemCollection.add(new SelectorItemInfo("*"));
            selectorItemCollection.add(new SelectorItemInfo("person.id"));
            selectorItemCollection.add(new SelectorItemInfo("operator.id"));
            ESignGlobalStatusOverviewInfo info = globalStatusOverview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(billId));
            if (StringUtils.isBlank(info.getSignFlowId())) {
                throw new EsignException("没有签署流程id");
            }
            boolean canLive = false;
            //更新附件
            if ("update".equals(update)) {
                this.delAttachment(this.getCtx(), info);
                canLive = true;
            } else if (EsignStatusEnum.COMPLETED.equals(info.getEsignStatus())) {
                //成功签署的附件
                FilterInfo filterInfo = new FilterInfo();
                filterInfo.getFilterItems().add(new FilterItemInfo("propertyName", "files"));
                String bunding = MessageFormat.format("{0}#{1}", EsignStatusEnum.COMPLETED_VALUE, info.getSignFlowId());
                filterInfo.getFilterItems().add(new FilterItemInfo("bunding", bunding));
                filterInfo.getFilterItems().add(new FilterItemInfo("boID", info.getId().toString()));
                boolean canCompleted = SHRAttchExt.exists(filterInfo);
                //没有成功签署的附件时，更新附件
                if (!canCompleted) {
                    this.delAttachment(this.getCtx(), info);
                    canLive = true;
                }
            } else {
                //预览中文件会更新所以需要删除重新下载
                this.delAttachment(this.getCtx(), info);
                canLive = true;
            }
            if (canLive) {
                EsignHttpResponse response1 = null;
                if (EsignStatusEnum.COMPLETED.equals(info.getEsignStatus())) {
                    response1 = EsignHttpUtil.getFile_download_url(this.getCtx(), info.getSignFlowId(), 3600, info.getEfileId());
                    JSONObject jsonObject = JSON.parseObject(response1.getBody());
                    Integer code = (Integer) jsonObject.get("code");
                    if (code == 0) {
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        JSONArray files = jsonData.getJSONArray("files");
                        if(null!=files) {
                            for (int i = 0; i < files.size(); i++) {
                                JSONObject fileMap = files.getJSONObject(i);
                                this.saveAttachment(this.getCtx(), info, fileMap, "com.kingdee.eas.custom.esign.app.ESignGlobalStatusOverview.list", "files");
                            }
                        }
                        JSONArray attachments = jsonData.getJSONArray("attachments");
                        if(null!=attachments) {
                            for (int i = 0; i < attachments.size(); i++) {
                                JSONObject fileMap = attachments.getJSONObject(i);
                                this.saveAttachment(this.getCtx(), info, fileMap, "com.kingdee.eas.custom.esign.app.ESignGlobalStatusOverview.list", "attachments");
                            }
                        }
                    }
                } else {
                    String json = info.getRequestParams();
                    JSONObject params = JSON.parseObject(json);
                    JSONArray docs = params.getJSONArray("docs");
                    for (int i = 0; i < docs.size(); i++) {
                        JSONObject doc = docs.getJSONObject(i);
                        String fileId = doc.getString("fileId");
                        response1 = EsignHttpUtil.getPreview_file_download_url(this.getCtx(), info.getSignFlowId(),fileId, info.getEfileId());
                        JSONObject jsonObject = JSON.parseObject(response1.getBody());
                        Integer code = (Integer) jsonObject.get("code");
                        if (code == 0) {
                            JSONObject fileMap = jsonObject.getJSONObject("data");
                            this.saveAttachment(this.getCtx(), info, fileMap, "com.kingdee.eas.custom.esign.app.ESignGlobalStatusOverview.list", "files");
                        }
                    }
                }
            }
            BatchMessageTipsBody body = new BatchMessageTipsBody();
            body.setMuitTipsState(Boolean.TRUE);
            body.setMuitTipsMessage("成功");
            body.setId(billId);
            batchMessageTipsHeader.addResult(body);
            success++;
        } catch (EsignException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
        batchMessageTipsHeader.setBillId(billId);
        batchMessageTipsHeader.setFailureCount((success <= 0 ? 1 : 0));
        batchMessageTipsHeader.setSuccessCount(success);
        this.writeSuccessData(batchMessageTipsHeader);
        return null;
    }
    /**
     *  同步签署状态信息
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String detail_sign_fieldsAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String billId = this.getBillId(request);
        int failure = 0;
        int success = 0;
        try {
            if (billId.indexOf(",") >= 0) {
                throw new EsignException("请选择一行记录发起签署");
            }
            IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(this.getCtx());
            SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
            selectorItemCollection.add(new SelectorItemInfo("*"));
            selectorItemCollection.add(new SelectorItemInfo("person.id"));
            selectorItemCollection.add(new SelectorItemInfo("operator.id"));
            ESignGlobalStatusOverviewInfo info = globalStatusOverview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(billId));
            if (null!=info&&StringUtils.isBlank(info.getSignFlowId())) {
                throw new EsignException("没有签署流程id");
            }

            EsignHttpResponse res = EsignHttpUtil.getSign_fields(this.getCtx(),info.getSignFlowId(),info.getEfileId());
            if (res.getStatus() >= 200 && res.getStatus() < 300) {
                JSONObject jsonObject = JSON.parseObject(res.getBody());
                Integer code = (Integer) jsonObject.get("code");
                if (code == 0) {
                    JSONObject jsonData = jsonObject.getJSONObject("data");
                    String signFlowStatus = jsonData.getString("signFlowStatus");
                    String signFlowId = jsonData.getString("signFlowId");
                    String statusDescription = jsonData.getString("statusDescription");
                    info.setEsignStatus(EsignStatusEnum.getEnum(Integer.parseInt(signFlowStatus)));
                    info.setDescription(statusDescription);
                    SelectorItemCollection selectorUpdatePartial = new SelectorItemCollection();
                    selectorUpdatePartial.add(new SelectorItemInfo("esignStatus"));
                    selectorUpdatePartial.add(new SelectorItemInfo("description"));
                    globalStatusOverview.updatePartial(info,selectorUpdatePartial);
                }
            }
            BatchMessageTipsBody body = new BatchMessageTipsBody();
            body.setMuitTipsState(Boolean.TRUE);
            body.setMuitTipsMessage("同步状态成功");
            body.setId(billId);
            batchMessageTipsHeader.addResult(body);
            success++;
        } catch (EsignException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
        batchMessageTipsHeader.setBillId(billId);
        batchMessageTipsHeader.setFailureCount((success <= 0 ? 1 : 0));
        batchMessageTipsHeader.setSuccessCount(success);
        this.writeSuccessData(batchMessageTipsHeader);
        return null;
    }
    /**
     *  同步签署完成附件
     * @param request
     * @param response
     * @param modelMap
     * @return
     * @throws SHRWebException
     */
    public String syncAttachmentsAction(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) throws SHRWebException {
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();
        String billId = this.getBillId(request);
        int failure = 0;
        int success = 0;
        try {
            if (billId.indexOf(",") >= 0) {
                throw new EsignException("请选择一行记录发起签署");
            }
            IESignGlobalStatusOverview globalStatusOverview = ESignGlobalStatusOverviewFactory.getLocalInstance(this.getCtx());
            SelectorItemCollection selectorItemCollection = new SelectorItemCollection();
            selectorItemCollection.add(new SelectorItemInfo("*"));
            selectorItemCollection.add(new SelectorItemInfo("person.id"));
            selectorItemCollection.add(new SelectorItemInfo("operator.id"));
            ESignGlobalStatusOverviewInfo info = globalStatusOverview.getESignGlobalStatusOverviewInfo(new ObjectUuidPK(billId));
            if (StringUtils.isBlank(info.getSignFlowId())) {
                throw new EsignException("没有签署流程id");
            }
//            if (!info.isFivouchered()) {
//                throw new EsignException("电子签全域状态总览表 [{0}]，签署文件已经同步,请勿重复同步");
//            }
            SyncSignedFilesUtil.syncAttachmentsForEmpPage(this.getCtx(),billId);
            BatchMessageTipsBody body = new BatchMessageTipsBody();
            body.setMuitTipsState(Boolean.TRUE);
            body.setMuitTipsMessage("触发同步成功");
            body.setId(billId);
            batchMessageTipsHeader.addResult(body);
            success++;
        } catch (EsignException e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
        batchMessageTipsHeader.setBillId(billId);
        batchMessageTipsHeader.setFailureCount((success <= 0 ? 1 : 0));
        batchMessageTipsHeader.setSuccessCount(success);
        this.writeSuccessData(batchMessageTipsHeader);
        return null;
    }



    private void delAttachment(Context ctx, ESignGlobalStatusOverviewInfo info) throws BOSException, EASBizException {
        ISHRAttachmentExt SHRAttchExt = SHRAttachmentExtFactory.getLocalInstance(ctx);
        IAttachment attachment = AttachmentFactory.getLocalInstance(ctx);
        IBoAttchAsso attchAsso = BoAttchAssoFactory.getLocalInstance(ctx);
        EntityViewInfo entityViewInfo = new EntityViewInfo();
        FilterInfo filterInfo2 = new FilterInfo();
        filterInfo2.getFilterItems().add(new FilterItemInfo("boID", info.getId().toString()));
        entityViewInfo.setFilter(filterInfo2);
        SHRAttachmentExtCollection collection = SHRAttchExt.getSHRAttachmentExtCollection(entityViewInfo);
        for (int i = 0; i < collection.size(); i++) {
            String attId = collection.get(i).getAttachment().getId().toString();
            attchAsso.delete(MessageFormat.format(" where attachment = ''{0}''", attId));
            attachment.delete(new ObjectUuidPK(attId));
        }
        SHRAttchExt.delete(filterInfo2);
    }

    /**
     * 保存附件
     *
     * @param ctx
     * @param info
     * @param fileMap
     * @param uipk
     * @param propertyName
     * @throws IOException
     * @throws ShrWebBizException
     * @throws BOSException
     * @throws EASBizException
     */
    private void saveAttachment(Context ctx, ESignGlobalStatusOverviewInfo info, JSONObject fileMap, String uipk, String propertyName) throws IOException, ShrWebBizException, BOSException, EASBizException {
        String fileId = fileMap.getString("fileId");
        String fileName = fileMap.getString("fileName");
        System.out.println("saveAttachment:fileMap"+fileMap);
        if(StringUtils.isBlank(fileName)) {
            fileName = info.getFileName()+".pdf";
        }
        String downloadUrl = fileMap.getString("downloadUrl");
        if(StringUtils.isBlank(downloadUrl)) {
            downloadUrl = fileMap.getString("fileDownloadUrl");
        }
        IAttachment attachment = AttachmentFactory.getLocalInstance(ctx);
        IBoAttchAsso attchAsso = BoAttchAssoFactory.getLocalInstance(ctx);
        ISHRAttachmentExt SHRAttchExt = SHRAttachmentExtFactory.getLocalInstance(ctx);
        byte[] content = DownloaderUtil.downloadFileToByteArray(downloadUrl);
        fileName = this.checkScriptAttack(fileName);
        if( fileName.lastIndexOf(46)<=0) {
            fileName +=".pdf";
        }
        String mainname = fileName.substring(0, fileName.lastIndexOf(46));
        String extname = fileName.substring(fileName.lastIndexOf(46) + 1, fileName.length());
        extname = extname.toLowerCase();
        SHRAttachmentExtInfo attchExt = new SHRAttachmentExtInfo();
        AttachmentInfo ai = new AttachmentInfo();
        this.setAttMulNameAndDesc(ctx, ai, mainname, fileId);
        ai.setSimpleName(extname);
        ai.setFile(content);
        ai.setIsShared(false);
        ai.setNumber(propertyName);
        ai.setSharedDesc(SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "false"));
        int size = content.length;
        if (size < 1024) {
            ai.setSize(size + SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "byte"));
        } else {
            ai.setSize(size / 1024 + "KB");
        }
        ai.setSizeInByte(size);
        ai.setAttachID("" + System.currentTimeMillis());
        ai.setType(this.getFileType(fileName));
        ai.setBeizhu(uipk);
        attchExt.setAttachment(ai);
        this.setAttExtMulNameAndDesc(ctx, attchExt, fileName, fileId);
        attchExt.setPropertyName(propertyName);
        attchExt.setType(AttachmentTypeEnum.PROPERTY);
        attchExt.setState(AttachmentState.UNSAVE);
        String bunding = MessageFormat.format("{0}#{1}", info.getEsignStatus().getValue(), info.getSignFlowId());
        attchExt.setBunding(bunding);
        attchExt.setBoID(info.getId().toString());
        try {
            attachment.addnew(ai);
        } catch (Exception var20) {
            throw new ShrWebBizException(SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "upload_error"), var20);
        }
        attchExt.setState(AttachmentState.SAVE);
        BoAttchAssoInfo boAttchAssoInfo = new BoAttchAssoInfo();
        boAttchAssoInfo.setBoID(info.getId().toString());
        boAttchAssoInfo.setAssoBusObjType(String.valueOf(info.getBOSType()));
        boAttchAssoInfo.setAssoType("Added Accessories", LocaleUtils.locale_l1);
        boAttchAssoInfo.setAssoType("Added Accessories", LocaleUtils.locale_l2);
        boAttchAssoInfo.setAssoType("Added Accessories", LocaleUtils.locale_l3);
        boAttchAssoInfo.setAttachment(ai);
        attchAsso.addnew(boAttchAssoInfo);
        SHRAttchExt.addnew(attchExt);
    }

    private String getFileType(String fullname) {
        String extname = fullname.substring(fullname.lastIndexOf(46) + 1, fullname.length());
        if (!"doc".equalsIgnoreCase(extname) && !"docx".equalsIgnoreCase(extname)) {
            if (!"xls".equalsIgnoreCase(extname) && !"xlsx".equalsIgnoreCase(extname) && !"xlsm".equalsIgnoreCase(extname) && !"xlsb".equalsIgnoreCase(extname)) {
                if (!"ppt".equalsIgnoreCase(extname) && !"pptx".equalsIgnoreCase(extname) && !"pptm".equalsIgnoreCase(extname)) {
                    return "txt".equalsIgnoreCase(extname) ? SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "text") : MessageFormat.format(SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "unknow_type"), extname);
                } else {
                    return SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "microsoft_ppt");
                }
            } else {
                return SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "microsoft_excel");
            }
        } else {
            return SHRWebResource.getString("com.kingdee.shr.base.syssetting.SHRSyssettingResource", "microsoft_word");
        }
    }

    private String checkScriptAttack(String str) {
        if (!StringUtils.isEmpty(str)) {
            if (str.contains("<")) {
                str.replaceAll("<", "&lt;");
            }

            if (str.contains(">")) {
                str.replaceAll(">", "&gt;");
            }
        }

        return str;
    }

    private void setAttMulNameAndDesc(Context ctx, AttachmentInfo att, String name, String desc) {
        if (att != null && !StringUtils.isEmpty(name)) {
            MutilanUtils.setMultiFieldValueToBean(ctx, "name", att, name);
            MutilanUtils.setMultiFieldValueToBean(ctx, "description", att, desc);
        }
    }

    private void setAttExtMulNameAndDesc(Context ctx, SHRAttachmentExtInfo info, String name, String desc) {
        if (info != null && !StringUtils.isEmpty(name)) {
            Locale locale = ctx.getLocale();
            info.setName(name, LocaleUtils.locale_l1);
            info.setDescription(desc, LocaleUtils.locale_l1);
            if (LocaleUtils.locale_l1.getDisplayName().equals(LocaleUtils.getLocaleString(locale))) {
                info.setName(name, LocaleUtils.locale_l2);
                info.setName(name, LocaleUtils.locale_l3);
                info.setDescription(desc, LocaleUtils.locale_l2);
                info.setDescription(desc, LocaleUtils.locale_l3);
            } else if (LocaleUtils.locale_l2.getDisplayName().equals(LocaleUtils.getLocaleString(locale))) {
                info.setName(name, LocaleUtils.locale_l2);
                info.setName(STConverter.sc2tc(name), LocaleUtils.locale_l3);
                if (!StringUtils.isEmpty(desc)) {
                    info.setDescription(desc, LocaleUtils.locale_l2);
                    info.setDescription(STConverter.sc2tc(desc), LocaleUtils.locale_l3);
                }
            } else {
                info.setName(STConverter.tc2sc(name), LocaleUtils.locale_l2);
                info.setName(name, LocaleUtils.locale_l3);
                if (!StringUtils.isEmpty(desc)) {
                    info.setDescription(STConverter.tc2sc(desc), LocaleUtils.locale_l2);
                    info.setDescription(desc, LocaleUtils.locale_l3);
                }
            }

        }
    }
}
