package nckd.jimin.jyyy.fi.plugin.form;

import com.alibaba.fastjson.JSON;
import com.kingdee.util.StringUtils;
import kd.bos.algo.DataSet;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.ext.fi.ai.DapBuildVoucherCommonUtil;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.image.pojo.ImageSysInfo;
import kd.bos.image.pojo.ViewImageVo;
import kd.bos.imageplatform.util.SSCImageUtils;
import kd.bos.list.ListShowParameter;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.image.ImageServiceNewHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;
import kd.bos.servicehelper.permission.PermissionServiceHelper;
import kd.bos.url.UrlService;
import kd.bos.util.CollectionUtils;
import kd.fi.cas.util.EmptyUtil;
import nckd.jimin.jyyy.fi.common.constant.BillTypeConstants;
import nckd.jimin.jyyy.fi.common.constant.ErPrintUserConstant;
import nckd.jimin.jyyy.fi.common.constant.ErReimBurseBillConstant;
import nckd.jimin.jyyy.fi.common.constant.HandInReceiveTicketConstant;
import nckd.jimin.jyyy.fi.common.entity.MergePrintEntity;
import nckd.jimin.jyyy.fi.common.util.ErFindRelationBillUtils;
import nckd.jimin.jyyy.fi.common.util.ReceiveTicketUtils;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

public class HandInReceiveTicketPlugin extends AbstractFormPlugin implements RowClickEventListener {

    private static Log log = LogFactory.getLog(HandInReceiveTicketPlugin.class);

    private static final String CLOSECALLBACK_MAIL = "closecallback_mail";

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        EntryGrid entryGrid = this.getControl(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
        entryGrid.addRowClickListener(this);

        Toolbar toolbar = this.getControl(HandInReceiveTicketConstant.METEDATAFLAG.NCKD_ENTRY_TOOLBARAP);
        toolbar.addItemClickListener(this);
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        // 显示当前扫描点
        DynamicObjectCollection scanTypeCol = getScanType();
        getModel().setValue(HandInReceiveTicketConstant.KEY_NCKD_SCANTYPE,scanTypeCol.get(0).getString(ErPrintUserConstant.KEY_NCKD_SCANTYPE));
    }

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);
        DynamicObjectCollection scanTypeCol = getScanType();

        if(CollectionUtils.isEmpty(scanTypeCol)){
            e.setCancel(true);
            e.setCancelMessage("请先配置用户登记后再操作。");
            return;
        }

        if(scanTypeCol.size() > 1){
            e.setCancel(true);
            e.setCancelMessage("用户登记存在多条有效数据，请处理后再操作。");
            return;
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IDataEntityProperty property = e.getProperty();
        String name = property.getName();
        switch (name){
            case HandInReceiveTicketConstant.KEY_NCKD_SCANNUMBER:
                propertyChangedScanNumber(e);
                break;
        }

    }

    protected void propertyChangedScanNumber(PropertyChangedArgs e){
        // 查询单据
        String scanNumber = (String)this.getModel().getValue(HandInReceiveTicketConstant.KEY_NCKD_SCANNUMBER);
        if(StringUtils.isEmpty(scanNumber)){
            return;
        }
        // 判断编码是否存在
        DynamicObjectCollection entryEntity = getModel().getEntryEntity(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
        Optional<DynamicObject> findNumberOp = entryEntity.stream()
                .filter(r -> scanNumber.equals(r.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_NUMBER))).findFirst();
        if(findNumberOp.isPresent()){
            return;
        }

        String[] findBillArray = new String[]{BillTypeConstants.ER_PUBLICREIMBURSEBILL,BillTypeConstants.ER_DAILYREIMBURSEBILL,
                BillTypeConstants.ER_TRIPREIMBURSEBILL,BillTypeConstants.ER_CHECKINGPAYBILL,BillTypeConstants.ER_PREPAYBILL,
                BillTypeConstants.ER_DAILYLOANBILL,BillTypeConstants.ER_REPAYMENTBILL};
        for(String billType : findBillArray){
            Boolean isFind = loadBillInfo(billType, scanNumber);
            if(isFind){
                break;
            }
        }
        // 查询完之后清空数据
        this.getModel().setValue(HandInReceiveTicketConstant.KEY_NCKD_SCANNUMBER,null);
    }

    protected Boolean loadBillInfo(String billlType , String billNo){
        String companyField = "costcompany";
        if(BillTypeConstants.ER_CHECKINGPAYBILL.equals(billlType)){
            companyField = "company";
        }
        String selector = String.join(",",ErReimBurseBillConstant.ID,ErReimBurseBillConstant.KEY_BILLNO,companyField,
                ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON,ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON);
        DataEntityPropertyCollection properties = EntityMetadataCache.getDataEntityType(billlType).getProperties();
        if(properties.containsKey(ErReimBurseBillConstant.KEY_NCKD_PAGEID)){
            selector = String.join(",",selector,ErReimBurseBillConstant.KEY_NCKD_PAGEID);
        }

        DynamicObject tripReimBurseBill = BusinessDataServiceHelper.loadSingle(billlType,selector,
                new QFilter(ErReimBurseBillConstant.KEY_BILLNO, QCP.equals, billNo).toArray());
        if(tripReimBurseBill != null){
            String pageId = billlType;
            if(properties.containsKey(ErReimBurseBillConstant.KEY_NCKD_PAGEID) && !StringUtils.isEmpty(tripReimBurseBill.getString(ErReimBurseBillConstant.KEY_NCKD_PAGEID))){
                pageId = tripReimBurseBill.getString(ErReimBurseBillConstant.KEY_NCKD_PAGEID);
            }

            addScanBillEntry(tripReimBurseBill.getString(ErReimBurseBillConstant.KEY_BILLNO),getReceiptStatus(tripReimBurseBill),
                    tripReimBurseBill.get(ErReimBurseBillConstant.ID), billlType,
                    tripReimBurseBill.getDynamicObject(companyField).getPkValue(),
                    pageId);
            return true;
        }
        return false;
    }


    protected String getReceiptStatus(DynamicObject billInfo){
        // 未交票
        if(billInfo.getDynamicObject(ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON) == null){
            return "handin_incomplete";
        }
        //未收票
        if(billInfo.getDynamicObject(ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON) != null
                && billInfo.getDynamicObject(ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON) == null){
            return "receipt_incomplete";
        }
        //已收票
        if(billInfo.getDynamicObject(ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON) != null
                && billInfo.getDynamicObject(ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON) != null){
            return "receipt_complete";
        }
        return "";
    }


    protected void addScanBillEntry(String number, String status, Object billId, String formId, Object companyId,String pageId){
        int newEntryRow = this.getModel().createNewEntryRow(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
        getModel().setValue(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_NUMBER,number,newEntryRow);
        getModel().setValue(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_STATUS,status,newEntryRow);
        getModel().setValue(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID,billId,newEntryRow);
        getModel().setValue(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID,formId,newEntryRow);
        getModel().setValue(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_PAGEID,pageId,newEntryRow);
        getModel().setItemValueByID(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_COMPANY,companyId,newEntryRow);
        getView().updateView(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
    }

    protected DynamicObjectCollection getScanType(){
        long currUserId = RequestContext.get().getCurrUserId();
        // 查询用户登记
        return QueryServiceHelper.query(ErPrintUserConstant.ENTITYID, ErPrintUserConstant.KEY_NCKD_SCANTYPE, new QFilter[]{
                new QFilter(ErPrintUserConstant.KEY_NCKD_BOS_USER, QCP.equals, currUserId),
                new QFilter(ErPrintUserConstant.KEY_STATUS, QCP.equals, "C"),
                new QFilter(ErPrintUserConstant.KEY_ENABLE, QCP.equals, Boolean.TRUE),
        });
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        String itemKey = evt.getItemKey();

        if(HandInReceiveTicketConstant.OPERATE.NCKD_MAIL.equals(itemKey) || HandInReceiveTicketConstant.OPERATE.NCKD_CANCELMAIN.equals(itemKey)
            || HandInReceiveTicketConstant.OPERATE.NCKD_VIEW_VOUCHER.equals(itemKey) || HandInReceiveTicketConstant.OPERATE.NCKD_VIEW_ELECRECEIPT.equals(itemKey)
            || HandInReceiveTicketConstant.OPERATE.NCKD_IMAGEPREVIEW.equals(itemKey)){
            String checkMsg = checkSelectSingle();
            if(!StringUtils.isEmpty(checkMsg)) {
                getView().showTipNotification(checkMsg);
                evt.setCancel(true);
                return;
            }
        }

        switch (itemKey){
            case HandInReceiveTicketConstant.OPERATE.NCKD_MAIL:
                beforeMail(evt);
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_CANCELMAIN:
                beforeCancleMail(evt);
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_IMAGEPREVIEW:
                //beforeImagePreview(evt);
                break;
        }
    }

    protected void beforeMail(BeforeItemClickEvent evt){

        DynamicObject selectRow = getSelectRows().get(0);
        // 快递编号为空
        DynamicObject billInfo = BusinessDataServiceHelper.loadSingle(selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID),
                selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID), ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER);

        if(!StringUtils.isEmpty(billInfo.getString(ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER))){
            getView().showTipNotification("不允许重复邮寄。");
            evt.setCancel(true);
            return;
        }
    }
    protected void beforeCancleMail(BeforeItemClickEvent evt){
        // 快递编号为空
        DynamicObject billInfo = getSelectBillInfo(ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER);

        if(StringUtils.isEmpty(billInfo.getString(ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER))){
            getView().showTipNotification("单据没有进行邮寄操作。");
            evt.setCancel(true);
            return;
        }

    }

    protected void beforeImagePreview(BeforeItemClickEvent evt){
        Long currUserId = RequestContext.get().getCurrUserId();
        DynamicObject billInfo = getSelectBillInfo(ErReimBurseBillConstant.KEY_COMPANY);
        Long orgId = billInfo.getDynamicObject(ErReimBurseBillConstant.KEY_COMPANY).getLong(ErReimBurseBillConstant.ID);
        DynamicObject permitem = QueryServiceHelper.queryOne("perm_permitem", "id,number", new QFilter("number", QCP.equals, "QXX0097").toArray());
        // 进行权限校验
        int checkPermission = PermissionServiceHelper.checkPermission(currUserId, orgId, OrgViewType.Admin, "er", billInfo.getDataEntityType().getName(), permitem.getString("id"));
        if(checkPermission == 0){
            getView().showTipNotification("没有查看影像的权限。");
            evt.setCancel(true);
            return;
        }
    }


    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);

        String itemKey = evt.getItemKey();

        switch (itemKey){
            case HandInReceiveTicketConstant.OPERATE.NCKD_MAIL:
                doMail();
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_CANCELMAIN:
                doCancleMail();
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_VIEW_VOUCHER:
                doViewVouhcer();
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_VIEW_ELECRECEIPT:
                doViewElecReceipt();
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_REFRESH:
                doRefresh();
                break;
            case HandInReceiveTicketConstant.OPERATE.NCKD_IMAGEPREVIEW:
                doImagePreview();
                break;
        }
    }

    protected void doImagePreview(){
        String userID = String.valueOf(RequestContext.get().getUserId());
        String userName = String.valueOf(RequestContext.get().getUserName());

        ImageSysInfo enableImageSysInfo = null;
        DynamicObject selectBillInfo = getSelectBillInfo(String.join(",",ErReimBurseBillConstant.ID,ErReimBurseBillConstant.KEY_NUMBER));
        String billType = selectBillInfo.getDataEntityType().getName();
        try {
            enableImageSysInfo = SSCImageUtils.getEnableImageSysInfo();
        } catch (Exception e) {
            log.error("获取影像系统异常：" + e.getMessage());
        }
        String imageSys;
        if (enableImageSysInfo == null) {
            imageSys = ResManager.loadKDString("无启用的影像系统配置，请联系系统管理员。", "ImageReview_0", "bos-image-formplugin", new Object[0]);
            getView().showTipNotification(imageSys);
            return;
        }

        imageSys = enableImageSysInfo.getNumber();
        log.info("获取到的imagesys:{}" , imageSys);
        ViewImageVo viewImageVo = new ViewImageVo();
        viewImageVo.setBillId(selectBillInfo.getString(ErReimBurseBillConstant.ID));
        viewImageVo.setUserId(userID);
        viewImageVo.setUserName(userName);
        viewImageVo.setMobile(false);
        viewImageVo.setBilltype(billType);
        viewImageVo.setImageSys(imageSys);
        viewImageVo = ImageServiceNewHelper.viewPhoto(viewImageVo);
        if (viewImageVo.getUrl() == null) {
            getView().showTipNotification(viewImageVo.getMessage());
            return;
        }
        String url = viewImageVo.getUrl();
        String message = viewImageVo.getMessage();
        if (kd.bos.util.StringUtils.isNotEmpty(message)) {
            getView().showMessage(message);
            return;
        }
        getView().openUrl(url);
    }

    protected void doViewVouhcer(){
        DynamicObject selectRow = getSelectRows().get(0);
        Map<String, Set<Object>> relationBelowBillMap = ErFindRelationBillUtils.getRelationBelowBillMap(selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID),
                selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID));
        if(relationBelowBillMap.containsKey(BillTypeConstants.GL_VOUCHER)){
            Set<Object> voucherIdSet = relationBelowBillMap.get(BillTypeConstants.GL_VOUCHER);
            if(CollectionUtils.isNotEmpty(voucherIdSet)){
                if(voucherIdSet.size() == 1){
                    Object voucherId = voucherIdSet.iterator().next();
                    BillShowParameter showParameter = new BillShowParameter();
                    showParameter.setPkId(voucherId);
                    showParameter.setFormId(BillTypeConstants.GL_VOUCHER);
                    showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                    DataSet ds = QueryServiceHelper.queryDataSet("TraceVoucher_queryvoucher", BillTypeConstants.GL_VOUCHER, "org", new QFilter[]{new QFilter("id", "=", voucherId)}, null);
                    long orgId = ds.iterator().next().getLong("org");
                    long userId = Long.parseLong(RequestContext.get().getUserId());
                    int checkPermission = PermissionServiceHelper.checkPermission(userId, "DIM_ORG", orgId, "83bfebc8000017ac", BillTypeConstants.GL_VOUCHER, "4715a0df000000ac");
                    Boolean isbizvoucher = DapBuildVoucherCommonUtil.getEnableBizVoucherSystemParam(orgId);
                    if (checkPermission != 1 || isbizvoucher) {
                        showParameter.setStatus(OperationStatus.VIEW);
                    } else {
                        showParameter.setStatus(OperationStatus.EDIT);
                    }
                    showParameter.setHasRight(true);
                    this.getView().showForm(showParameter);
                }else{
                    ListShowParameter showParameter = new ListShowParameter();
                    showParameter.setBillFormId(BillTypeConstants.GL_VOUCHER);
                    showParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                    showParameter.setShowFilter(false);
                    showParameter.setShowQuickFilter(false);
                    for(Object voucherId : voucherIdSet){
                        showParameter.addLinkQueryPkId(voucherId);
                    }
                    showParameter.getCustomParams().put("org", "");
                    showParameter.getCustomParams().put("booktype", "");
                    this.getView().showForm(showParameter);
                }
            }else{
                this.getView().showTipNotification(ResManager.loadKDString("单据没有关联的凭证。", "TraceVoucher_2", "bos-ext-fi"));
            }
        }else{
            this.getView().showTipNotification(ResManager.loadKDString("单据没有关联的凭证。", "TraceVoucher_2", "bos-ext-fi"));
        }
    }

    protected void doViewElecReceipt(){
        DynamicObject selectRow = getSelectRows().get(0);
        String pdfUrl = null;
        try {
            pdfUrl = FeiBillFileViewMultHelper.getElecreceiptByFile(selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID));
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        if (kd.bos.util.StringUtils.isNotEmpty(pdfUrl)) {
            FeiBillFileViewMultHelper.openForm(this.getView(), pdfUrl);
        } else {
            this.getView().showSuccessNotification("没有相应的电子回单！");
        }

    }


    public Map<String,Object> getElecreceiptByFile(String payBillId){
        Long billId = Long.parseLong(payBillId);
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject billDyn = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qf});
        String transdetailId = billDyn.getString("detailseqid");
        if(kd.bos.util.StringUtils.isEmpty(transdetailId)) return null;
        QFilter qf1 = new QFilter("billno", QCP.equals, transdetailId);
        DynamicObject transdetailDyn = BusinessDataServiceHelper.loadSingle("bei_transdetail", new QFilter[]{qf1});
        if(EmptyUtil.isEmpty(transdetailDyn)) return null;
        String elecreceiptNo = transdetailDyn.getString("receiptno");
        QFilter qf2 = new QFilter("receiptno", QCP.equals, elecreceiptNo);
        DynamicObject elecreceiptDyn = BusinessDataServiceHelper.loadSingle("bei_elecreceipt", new QFilter[]{qf2});

        if(EmptyUtil.isEmpty(elecreceiptDyn)) return null;
        Map<String, Object> attachmentMap = getAttachmentFile(elecreceiptDyn.getLong("id"));

        if(attachmentMap == null) return null;
        String filepath = elecreceiptDyn.getString("filepath");
        /**
         * 获取持久化附件的预览url
         * @param path 持久化附件的downloadUrl相对路径
         * @return 持久化附件的预览url
         *  入参示例： /tenant_devcore_dev/1402323749146986496/202305/1683569603244172288/5b3c272f9d5a42fdbecddf2d84bcdd56/Wo rd文档.docx
         */
        String previewUrl = UrlService.getAttachmentPreviewUrl(filepath);
        String downloadUrl = UrlService.getAttachmentDownloadUrl(filepath);
        //previewUrl = previewUrl.replace("http://127.0.0.1:8881","https://d-kd.jeyoupharma.com:8022");
        //downloadUrl = downloadUrl.replace("http://127.0.0.1:8881","https://d-kd.jeyoupharma.com:8022");

        Map<String,Object> attMap = new HashMap<>();
        attMap.put("previewurl",previewUrl);
        attMap.put("url",downloadUrl);
        attMap.put("uid",attachmentMap.get("uid"));
        attMap.put("type", attachmentMap.get("type"));
        attMap.put("name",attachmentMap.get("name"));
        attMap.put("size", attachmentMap.get("size"));
        attMap.put("status","success");
        attMap.put("visible","1000");

        return attMap;
    }

    public static Map<String, Object>  getAttachmentFile(Long billId) {

        //创建一条基础资料数据-附件字段
        //获取单据信息，并查询单据中的附件字段
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject file =BusinessDataServiceHelper.loadSingle("bei_elecreceipt", "attachmentpanel",new QFilter[]{qf});
        //获取单据中附件面板信息
        List<Map<String, Object>> atts = AttachmentServiceHelper.getAttachments("bei_elecreceipt", file.getPkValue().toString(), "attachmentpanel");
        //遍历文件   电子回单只有一条
        for (Map<String, Object>  att: atts) {
            return att;
        }
        return null;
    }


    protected void doRefresh(){

        int entryRowCount = getModel().getEntryRowCount(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
        int[] allRow = new int[entryRowCount];
        for(int i = 0 ; i< entryRowCount ; i++){
            allRow[i] = i ;
        }
        reloadEntryRow(allRow);

        getView().showSuccessNotification("刷新成功。");
    }

    protected void doMail(){

        FormShowParameter parameter = new FormShowParameter();
        parameter.setFormId(HandInReceiveTicketConstant.ENTITY_NCKD_TICKET_MAIL);
        CloseCallBack callBack = new CloseCallBack(this,CLOSECALLBACK_MAIL);
        parameter.setCloseCallBack(callBack);
        parameter.getOpenStyle().setShowType(ShowType.Modal);
        getView().showForm(parameter);
    }

    protected void doCancleMail(){
        DynamicObject billInfo = getSelectBillInfo(String.join(",",ErReimBurseBillConstant.KEY_BILLNO,ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER));
        billInfo.set(ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER,null);
        SaveServiceHelper.save(new DynamicObject[]{ billInfo });
        getView().showSuccessNotification("退邮成功。");
    }



    protected DynamicObject getSelectBillInfo(String selector){
        DynamicObject selectRow = getSelectRows().get(0);
        // 快递编号为空
       return BusinessDataServiceHelper.loadSingle(selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID),
                selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID), selector);
    }



    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate operate = (FormOperate)args.getSource();
        String operateKey = operate.getOperateKey();
        String checkMsg = checkSelectSingle();
        switch (operateKey){
            case HandInReceiveTicketConstant.OPERATE.MERGEPRINT:
//                if(!StringUtils.isEmpty(checkMsg)){
//                    getView().showTipNotification(checkMsg);
//                    args.setCancel(true);
//                    return;
//                }
                beforeDoPrint(args);
                break;
        }
    }

    protected void beforeDoPrint(BeforeDoOperationEventArgs args){
        List<DynamicObject> selectRows = getSelectRows();
        List<String> status = Arrays.asList("E", "F", "G" , "I");

        for(DynamicObject selectRow : selectRows){
            DynamicObject billInfo = BusinessDataServiceHelper.loadSingle(selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID),
                    selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID), String.join(",",ErReimBurseBillConstant.KEY_BILLSTATUS,ErReimBurseBillConstant.KEY_BILLNO));
            if(!status.contains(billInfo.getString(ErReimBurseBillConstant.KEY_BILLSTATUS))){
                getView().showTipNotification(String.format("单据%s打印失败：只有审核通过、等待付款、已付款状态的单据允许打印。",billInfo.getString(ErReimBurseBillConstant.KEY_BILLNO)));
                args.setCancel(true);
                return;
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        OperationResult operationResult = args.getOperationResult();

        if( operationResult != null
                && (!operationResult.isSuccess() || operationResult.getSuccessPkIds().size() == 0)){
            return;
        }
        switch (operateKey) {
            case HandInReceiveTicketConstant.OPERATE.HANDIN_TICKET:
                executeOperateBill(operateKey, "交票");
                break;
            case HandInReceiveTicketConstant.OPERATE.RECEIVE_TICKET:
                executeOperateBill(operateKey, "收票");
                break;
            // 打印
            case HandInReceiveTicketConstant.OPERATE.MERGEPRINT:
                doMergetPrint();
                break;
        }
    }

    @Override
    public void entryRowDoubleClick(RowClickEvent evt) {
        RowClickEventListener.super.entryRowDoubleClick(evt);
        EntryGrid entryGrid = (EntryGrid)evt.getSource();
        String entryKey = entryGrid.getEntryKey();
        int row = evt.getRow();

        if(StringUtils.equals(entryKey,HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID)){
            // 获取单据信息
            DynamicObject billEntry = getModel().getEntryRowEntity(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID, row);
            String formId = billEntry.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID);
            String billId = billEntry.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID);
            MainEntityType entityType = EntityMetadataCache.getDataEntityType(formId);
            String targetFormId = formId;
            // 单据存在样式字段，则从单据上取，不存在则直接打开
            if(entityType.getProperties().containsKey(ErReimBurseBillConstant.KEY_NCKD_PAGEID)){
                DynamicObject queryBill = QueryServiceHelper.queryOne(formId, ErReimBurseBillConstant.KEY_NCKD_PAGEID,
                        new QFilter(ErReimBurseBillConstant.ID, QCP.equals, Long.valueOf(billId)).toArray());
                if(!StringUtils.isEmpty(queryBill.getString(ErReimBurseBillConstant.KEY_NCKD_PAGEID))){
                    targetFormId = queryBill.getString(ErReimBurseBillConstant.KEY_NCKD_PAGEID);
                }
            }

            BillShowParameter parameter = new BillShowParameter();
            parameter.setFormId(targetFormId);
            parameter.setStatus(OperationStatus.VIEW);
            parameter.getOpenStyle().setShowType(ShowType.InContainer);
            parameter.getOpenStyle().setTargetKey(HandInReceiveTicketConstant.METEDATAFLAG.NCKD_FLEX_TARGETBILL);
            parameter.setPkId(billId);
            getView().showForm(parameter);
        }
    }

    @Override
    public void entryRowClick(RowClickEvent evt) {
        RowClickEventListener.super.entryRowClick(evt);
    }

    protected String checkSelectSingle(){
        List<DynamicObject> selectRows = getSelectRows();
        if(selectRows.size() == 0){
            return "请选择要执行的数据。";
        }
        if(selectRows.size() > 1){
            return "仅允许选择一条数据进行操作。";
        }
        return "";
    }

    protected void doMergetPrint() {

        List<DynamicObject> selectRows = getSelectRows();

        List<MergePrintEntity> allPrintEntity = new ArrayList<>();

        for(DynamicObject selectRow : selectRows){
            Object companyId = selectRow.getDynamicObject(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_COMPANY).getPkValue();
            String formId = selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID);
            String billId = selectRow.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID);
            // 通过打印配置获取单据打印信息
            List<MergePrintEntity> printPdfConfig = ReceiveTicketUtils.getPrintPdfConfig(formId,Long.valueOf(billId),companyId);
            printPdfConfig.sort(comparing(MergePrintEntity::getIndex));
            allPrintEntity.addAll(printPdfConfig);
        }
        log.info(String.format("获取的打印信息为：%s", JSON.toJSONString(allPrintEntity)));
        String printFileName = String.format("报销信息打印");
        String previewUrl = ReceiveTicketUtils.mergePrintPdf(getView(), allPrintEntity, printFileName);
        getView().openUrl(previewUrl);
        getView().showSuccessNotification("打印成功。");
    }

    protected void reloadEntryRow(int[] indexArray){
        for(int index : indexArray){
            DynamicObject entryRowEntity = getModel().getEntryRowEntity(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID, index);
            DynamicObject billInfo = BusinessDataServiceHelper.loadSingle(entryRowEntity.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID),
                    entryRowEntity.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID),
                    String.join(",", ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON, ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON));
            entryRowEntity.set(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_STATUS,getReceiptStatus(billInfo));
        }
        getView().updateView(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent event) {
        super.closedCallBack(event);
        String actionId = event.getActionId();
        Object returnData = event.getReturnData();
        if(CLOSECALLBACK_MAIL.equals(actionId)){
            if(returnData == null || StringUtils.isEmpty(returnData.toString())){
                return;
            }
            DynamicObject billInfo = getSelectBillInfo(ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER);
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_TRACKING_NUMBER,returnData);
            SaveServiceHelper.save(new DynamicObject[]{ billInfo });
        }
    }

    protected void executeOperateBill(String operate, String operateName){
        List<DynamicObject> selectRowList = getSelectRows();
        EntryGrid entryGrid = this.getControl(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);

        if(selectRowList.size() <= 0){
            return;
        }
        // 按照单据类型分组来执行
        Map<String, List<DynamicObject>> formIdMap = selectRowList.stream().collect(Collectors.groupingBy(r -> r.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_FORMID)));

        OperationResult opResult =new OperationResult();

        for(Map.Entry<String, List<DynamicObject>> row : formIdMap.entrySet()){
            String billFormId = row.getKey();
            List<DynamicObject> billList = row.getValue();
            List<Object> selectRowIdList = billList.stream().map(r -> Long.valueOf(r.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID))).collect(Collectors.toList());
            // 调用操作
            OperationResult operationResult = OperationServiceHelper.executeOperate(operate, billFormId, selectRowIdList.toArray(), OperateOption.create());

            opResult.mergeOperateResult(operationResult);

        }

        // 全部成功弹出消息提示，否则弹出操作提示框
        if(opResult.isSuccess()){
            getView().showSuccessNotification(String.format("执行【%1$s】操作成功！",operateName));
        }else{
            getView().showOperationResult(opResult);
        }

        List<Object> successPkIds = opResult.getSuccessPkIds();
        // 移除操作成功的数据
        DynamicObjectCollection entryCol = getModel().getEntryEntity(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
        entryCol.removeIf(r -> successPkIds.contains(Long.valueOf(r.getString(HandInReceiveTicketConstant.SCANBILLENTRY.KEY_NCKD_BILLID))));
        getView().updateView(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);

        //刷新分录
        //reloadEntryRow(entryGrid.getSelectRows());
    }

    protected List<DynamicObject> getSelectRows(){
        List<DynamicObject> selectRowList = new ArrayList<>();
        EntryGrid entryGrid = this.getControl(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID);
        int[] selectRows = entryGrid.getSelectRows();
        for(int rowIndex : selectRows){
            selectRowList.add(getModel().getEntryRowEntity(HandInReceiveTicketConstant.SCANBILLENTRY.ENTITYID,rowIndex));
        }
        return selectRowList;
    }
}
