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

import com.kingdee.bos.util.backport.Collections;
import kd.bos.algo.DataSet;
import kd.bos.algo.Row;
import kd.bos.bill.BillShowParameter;
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.entity.LocaleString;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.botp.runtime.ConvertOperationResult;
import kd.bos.entity.botp.runtime.PushArgs;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.events.TotalEntriesEventArgs;
import kd.bos.entity.filter.FilterBuilder;
import kd.bos.entity.filter.FilterCondition;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.form.ClientProperties;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.events.BeforeClickEvent;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
import kd.bos.form.operate.botp.Push;
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.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.param.ParameterReader;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.botp.ConvertServiceHelper;
import kd.bos.servicehelper.image.ImageServiceNewHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.org.OrgViewType;
import kd.bos.servicehelper.permission.PermissionServiceHelper;
import kd.bos.servicehelper.workflow.WorkflowServiceHelper;
import kd.bos.svc.util.print.PrintFileUtil;
import kd.bos.util.CollectionUtils;
import kd.bos.util.StringUtils;
import nckd.jimin.jyyy.fi.common.ReimDetailTypeEnum;
import nckd.jimin.jyyy.fi.common.util.PrintPdfUtil;
import nckd.jimin.jyyy.fi.common.util.ReceiveTicketUtils;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class ReimWorkBenchesDetailFormPlugin extends AbstractFormPlugin implements HyperLinkClickListener {
    private static Log logger = LogFactory.getLog(ReimWorkBenchesDetailFormPlugin.class);
    private static final String ENTITY_ENTRY = "nckd_entryentity";
    //报销
    private static final String BTN_REIM = "btn_reim";

    //借款
    private static final String BTN_LOAN = "btn_loan";

    //还款
    private static final String BTN_REPAY = "btn_repay";

    // 打印
    private static final String BTN_PRINT = "btn_print";

    // 查看影像
    private static final String BTN_VIEWIMAGE = "btn_viewimage";

    // 查看流程图
    private static final String BTN_VIEWFLOW = "btn_viewflow";

    // 废弃
    private static final String BTN_CANCEL = "btn_cancel";

    // 刷新
    private static final String BTN_REFRESH = "btn_refresh";

    // 删除
    private static final String BTN_DELETE = "btn_delete";

    // 关闭
    private static final String BTN_CLOSE = "btn_close";

    protected ReimWorkBenchesHelper reimHelper ;

    @Override
    public void initialize() {
        super.initialize();
        reimHelper = new ReimWorkBenchesHelper();

        EntryGrid entryGrid = this.getControl(ENTITY_ENTRY);
        entryGrid.setInterveneTotal(true);
    }

    protected ReimWorkBenchesHelper getReimHelper(){
        return Optional.ofNullable(reimHelper).orElse(new ReimWorkBenchesHelper());
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("bar_reim");
        EntryGrid entryGrid = this.getControl(ENTITY_ENTRY);
        entryGrid.addHyperClickListener(this);
    }


    @Override
    public void totalEntriesByCondition(TotalEntriesEventArgs e) {
        super.totalEntriesByCondition(e);
        setEntryTotalAmount();
    }


    protected void setEntryTotalAmount(){
        EntryGrid entryGrid = this.getControl(ENTITY_ENTRY);
        DynamicObject[] entryPageDataArray = entryGrid.getEntryData().getDataEntitys();

        BigDecimal applyAmount = BigDecimal.ZERO;
        BigDecimal approveAmount = BigDecimal.ZERO;
        BigDecimal balanceAmount = BigDecimal.ZERO;
        BigDecimal payAmount = BigDecimal.ZERO;
        BigDecimal notpayAmount = BigDecimal.ZERO;
        for(DynamicObject entry : entryPageDataArray){
            applyAmount = applyAmount.add(entry.getBigDecimal("applyamount"));
            approveAmount = approveAmount.add(entry.getBigDecimal("approveamount"));
            balanceAmount = balanceAmount.add(entry.getBigDecimal("balanceamount"));
            payAmount = payAmount.add(entry.getBigDecimal("payamount"));
            notpayAmount = notpayAmount.add(entry.getBigDecimal("notpayamount"));
        }
        Map<String,String> totalAmountMap = new HashMap<>(5);
        totalAmountMap.put("applyAmount",applyAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        totalAmountMap.put("approveAmount",approveAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        totalAmountMap.put("balanceAmount",balanceAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        totalAmountMap.put("payAmount",payAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        totalAmountMap.put("notpayAmount",notpayAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        entryGrid.setFloatButtomData(totalAmountMap);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        this.getModel().putContextVariable("MODEL_BOSENTRYSERVERFILTERSORT",true);
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        loadBillData();
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);

        updateEntryFiledTitle();

        setEntryTotalAmount();
    }

    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        String itemKey = evt.getItemKey();
        String checkMsg = checkSelectSingle();
        if(!BTN_REFRESH.equals(itemKey)){
            if(!com.kingdee.util.StringUtils.isEmpty(checkMsg)) {
                getView().showTipNotification(checkMsg);
                evt.setCancel(true);
                return;
            }
        }

        switch (itemKey){
            case BTN_PRINT:
                beforePrint(evt);
                break;
            case BTN_VIEWIMAGE:
                //beforeImagePreview(evt);
                break;
        }
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String itemKey = evt.getItemKey();
        List<DynamicObject> selectRowList = getSelectRows();
        switch (itemKey){

            case BTN_REIM:
                doPushNew(evt,"reim");
                break;
            case BTN_LOAN:
                doPushNew(evt,"loan");
                break;
            case BTN_REPAY:
                doPushNew(evt,"repay");
                break;

            case BTN_PRINT:
                doPrint();
                break;
            case BTN_VIEWIMAGE:
                doImagePreview();
                break;
            case BTN_VIEWFLOW:
                if(CollectionUtils.isNotEmpty(selectRowList)){
                    WorkflowServiceHelper.viewFlowchart(getView().getPageId(), selectRowList.get(0).get("billid"));
                }
                break;
            case BTN_CANCEL:
                executeOperateBill("invalid","废弃");
                break;
            case BTN_REFRESH:
                loadBillData();
                getView().showSuccessNotification("刷新成功。");
                break;
            case BTN_DELETE:
                executeOperateBill("delete","删除");
                break;
            case BTN_CLOSE:
                executeOperateBill("closebill","关闭单据");
                break;
        }
    }

    protected void doPushNew(ItemClickEvent evt , String type){
        DynamicObject selectRow = getSelectRows().get(0);
        String sourceBillType = selectRow.getString("billtype");
        String billid = selectRow.getString("billid");
        // 查询配置表

        DynamicObjectCollection pushSettingCol = QueryServiceHelper.query("nckd_reimpushsetting", "nckd_type,nckd_sourcebilltype,nckd_targetbilltype,nckd_ruleid", new QFilter[]{
                new QFilter("nckd_sourcebilltype", QCP.equals, sourceBillType),
                new QFilter("nckd_type", QCP.equals, type)
        });

        if(CollectionUtils.isEmpty(pushSettingCol)){
            getView().showTipNotification("单据未配置报销工作台下推设置。");
            return;
        }
        if(pushSettingCol.size() > 1){
            getView().showTipNotification("单据存在多条报销工作台下推设置。");
            return;
        }
        DynamicObject pushSettingInfo = pushSettingCol.get(0);
        botpCreateBillOpen(billid,pushSettingInfo.getString("nckd_sourcebilltype"),
                pushSettingInfo.getString("nckd_targetbilltype"),pushSettingInfo.getString("nckd_ruleid"));

    }

    protected void doReim(ItemClickEvent evt){
        DynamicObject selectRow = getSelectRows().get(0);
        String billtype = selectRow.getString("billtype");
        String billid = selectRow.getString("billid");

        // 出差申请单
        if("er_tripreqbill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_tripreimbursebill");
            return;
        }

        // 差旅借款单
        if("er_dailyloanbill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_tripreimbursebill");
            return;
        }

        // 外办申请单
        if("er_dailyvehiclebill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_publicreimbursebill");
            return;
        }

        // 费用申请
        if("er_dailyapplybill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_publicreimbursebill");
            return;
        }

        // 预付单
        if("er_prepaybill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_publicreimbursebill");
            return;
        }

        throw new KDBizException("单据无法进行报销操作。");
    }

    protected void doLoan(ItemClickEvent evt){
        DynamicObject selectRow = getSelectRows().get(0);
        String billtype = selectRow.getString("billtype");
        String billid = selectRow.getString("billid");

        // 出差申请单
        if("er_tripreqbill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_dailyloanbill");
            return;
        }

        // 外办申请单
        if("er_dailyvehiclebill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_prepaybill");
            return;
        }

        // 费用申请
        if("er_dailyapplybill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_prepaybill");
            return;
        }

        throw new KDBizException("单据无法进行借款操作。");
    }

    protected void doRepay(ItemClickEvent evt){
        DynamicObject selectRow = getSelectRows().get(0);
        String billtype = selectRow.getString("billtype");
        String billid = selectRow.getString("billid");


        // 差旅借款单
        if("er_dailyloanbill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_repaymentbill");
            return;
        }


        // 预付单
        if("er_prepaybill".equals(billtype)){
            botpCreateBillOpen(billid,billtype, "er_repaymentbill");
            return;
        }
        throw new KDBizException("单据无法进行还款操作。");

    }


    protected void executeOperateBill(String operate, String operateName){
        List<DynamicObject> selectRowList = getSelectRows();
        if(selectRowList.size() <= 0){
            return;
        }
        // 按照单据类型分组来执行
        Map<String, List<DynamicObject>> formIdMap = selectRowList.stream().collect(Collectors.groupingBy(r -> r.getString("billtype")));

        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("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));
            //刷新分录
            loadBillData();
        }else{
            getView().showOperationResult(opResult);
        }
    }


    protected void doPrint(){
        // 判断是否有打印条件
        DynamicObject selectRow = getSelectRows().get(0);
        String billid = selectRow.getString("billid");
        String billtype = selectRow.getString("billtype");
        String billno = selectRow.getString("billno");
        String printTemplateId = ReceiveTicketUtils.getPrintTemplateId(null, billtype, Long.valueOf(billid));
        String tplType = ReceiveTicketUtils.getTplTypeById(printTemplateId);
        int tplParamType = "A".equalsIgnoreCase(tplType)?1:2;
        byte[] printBuff = PrintPdfUtil.getPrintByte(getView().getPageId(),billtype,printTemplateId, Collections.singletonList(billid),"billForm",tplParamType);
        String previewUrl = "tempfile/print.do?" + PrintFileUtil.saveInputStream2TempFile(billno + ".pdf", new ByteArrayInputStream(printBuff), 3600 * 2);
        getView().openUrl(previewUrl);

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

        ImageSysInfo enableImageSysInfo = null;
        DynamicObject selectRow = getSelectRows().get(0);
        String billType = selectRow.getString("billtype");
        try {
            enableImageSysInfo = SSCImageUtils.getEnableImageSysInfo();
        } catch (Exception e) {
            logger.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();
        logger.info("获取到的imagesys:{}" , imageSys);
        ViewImageVo viewImageVo = new ViewImageVo();
        viewImageVo.setBillId(selectRow.getString("billid"));
        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 (StringUtils.isNotEmpty(message)) {
            getView().showMessage(message);
            return;
        }
        getView().openUrl(url);
    }

    @Override
    public void beforeClick(BeforeClickEvent evt) {
        super.beforeClick(evt);
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
    }

    protected void beforePrint(BeforeItemClickEvent evt){
        // 校验有没有打印的权限
        Long currUserId = RequestContext.get().getCurrUserId();
        DynamicObject selectRow = getSelectRows().get(0);
        Long orgId = selectRow.getDynamicObject("company").getLong("id");
        // 判断是否有打印条件
        String billid = getSelectRows().get(0).getString("billid");
        String billtype = selectRow.getString("billtype");
        DynamicObject permitem = QueryServiceHelper.queryOne("perm_permitem", "id,number", new QFilter("number", QCP.equals, "QXX0014").toArray());
        // 进行权限校验
        int checkPermission = PermissionServiceHelper.checkPermission(currUserId, orgId, OrgViewType.Admin, "er", billtype, permitem.getString("id"));
        if(checkPermission == 0){
            getView().showTipNotification("没有打印单据的权限。");
            evt.setCancel(true);
            return;
        }

        DynamicObject params = ParameterReader.getBillParameter(billtype);
        if(params == null){
            return;
        }
        String printcondition = params.getString("printconditionvalue");
        String printconditionname = params.getString("printcondition");
        if(StringUtils.isEmpty(printcondition)){
            return;
        }

        FilterCondition filterCondition = (FilterCondition) SerializationUtils.fromJsonString(printcondition, FilterCondition.class);
        MainEntityType dt = EntityMetadataCache.getDataEntityType(billtype);
        FilterBuilder filterBuilder = new FilterBuilder(dt, filterCondition, true);
        filterBuilder.buildFilter(true);
        QFilter qfFormBillParameter = filterBuilder.getQFilter();
        boolean check = ORM.create().exists(billtype, new QFilter[]{
                qfFormBillParameter,
                new QFilter("id", QCP.equals, Long.valueOf(billid))
        });

        if(!check){
            getView().showTipNotification(String.format("所选数据不符合%s打印条件，不允许打印。",printconditionname));
            evt.setCancel(true);
            return;
        }

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

    protected void updateEntryFiledTitle(){

        String reimtype = (String) getModel().getValue("reimtype");
        ReimDetailTypeEnum reportType = ReimDetailTypeEnum.getValueByKey(reimtype);
        if(reportType == null){
            return;
        }
        EntryGrid entryGrid = this.getControl(ENTITY_ENTRY);
        // 报销中，申请金额改成报销金额
        if(reportType.equals(ReimDetailTypeEnum.REIMING)){
            entryGrid.setColumnProperty("applyamount", ClientProperties.Header,new LocaleString("报销金额"));
        }

        // 已完成，申请金额改成金额
        if(reportType.equals(ReimDetailTypeEnum.COMPLETE)){
            entryGrid.setColumnProperty("applyamount", ClientProperties.Header,new LocaleString("金额"));
        }

        // 还款，申请金额改成还款金额
        if(reportType.equals(ReimDetailTypeEnum.REPAY)){
            entryGrid.setColumnProperty("applyamount", ClientProperties.Header,new LocaleString("还款金额"));
        }

    }

    protected void loadBillData(){
        String reimtype = getView().getFormShowParameter().getCustomParam("reimtype");
        if(StringUtils.isEmpty(reimtype)){
            return;
        }

        ReimDetailTypeEnum reportType = ReimDetailTypeEnum.getValueByKey(reimtype);
        if(reportType == null){
            return;
        }
        this.getModel().setValue("reimtype",reportType.getKey());
        // 取值
        DataSet oriDataSet = queryDataSet(reportType);
        DataSet billDataSet = oriDataSet.orderBy(new String[]{"applydate desc","billno desc"});
        int totalRow = billDataSet.copy().count("billid", false);
        // 更新到单据体
        String[] fieldNames = billDataSet.getRowMeta().getFieldNames();
        DynamicObjectCollection entryEntityCol = getModel().getEntryEntity(ENTITY_ENTRY);
        getModel().deleteEntryData(ENTITY_ENTRY);
        if(totalRow == 0 ){
            return;
        }
        DataEntityPropertyCollection properties = entryEntityCol.getDynamicObjectType().getProperties();
        Iterator<Row> iterator = billDataSet.iterator();
        getModel().batchCreateNewEntryRow(ENTITY_ENTRY, totalRow);
        int index = 0;
        while (iterator.hasNext()){
            //DynamicObject entry = entryEntityCol.addNew();
            Row next = iterator.next();
            for(String filedName : fieldNames){
                if(properties.containsKey(filedName)){
                    if("company".equals(filedName)){
                        getModel().setValue(filedName,BusinessDataServiceHelper.loadSingleFromCache(next.get(filedName),"bos_org"),index);
                        //entry.set(filedName,BusinessDataServiceHelper.loadSingleFromCache(next.get(filedName),"bos_org"));
                        continue;
                    }
                    if("applier".equals(filedName)){
                        //entry.set(filedName,BusinessDataServiceHelper.loadSingleFromCache(next.get(filedName),"bos_user"));
                        getModel().setValue(filedName,BusinessDataServiceHelper.loadSingleFromCache(next.get(filedName),"bos_user"),index);
                        continue;
                    }
                    //entry.set(filedName,next.get(filedName));
                    getModel().setValue(filedName,next.get(filedName),index);
                }
            }
            index++;
        }
        EntryGrid entryGrid = this.getControl(ENTITY_ENTRY);
        entryGrid.setPageIndex(1);
    }

    protected  DataSet queryDataSet(ReimDetailTypeEnum reportType){
        String quickFilter = getQuicklyQueryContent();
        ReimWorkBenchesHelper service = getReimHelper();
        if(reportType.equals(ReimDetailTypeEnum.APPLY)){
            return service.queryDataApply(null,quickFilter);
        }
        if(reportType.equals(ReimDetailTypeEnum.WAIREIM)){
            return service.queryDataWaitReim(null,quickFilter);
        }
        if(reportType.equals(ReimDetailTypeEnum.REIMING)){
            return service.queryDataReiming(null,quickFilter);
        }
        if(reportType.equals(ReimDetailTypeEnum.COMPLETE)){
            return service.queryDataComplete(null,quickFilter);
        }
        if(reportType.equals(ReimDetailTypeEnum.REPAY)){
            return service.queryDataRepay(null,quickFilter);
        }
        return null;
    }

    protected String getQuicklyQueryContent(){
        return (String)getView().getParentView().getModel().getValue("nckd_quicklysearch");
    }

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

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

    @Override
    public void hyperLinkClick(HyperLinkClickEvent event) {
        String fieldName = event.getFieldName();
        int rowIndex = event.getRowIndex();
        DynamicObject entryRow = this.getModel().getEntryRowEntity(ENTITY_ENTRY, rowIndex);
        if("billno".equals(fieldName)){
            // 打开单据
            BillShowParameter parameter = new BillShowParameter();
            parameter.setFormId(entryRow.getString("billtype"));
            parameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
            parameter.setPkId(entryRow.getString("billid"));
            getView().showForm(parameter);
        }
        if("curapprovenode".equals(fieldName)){
            // 打开单据
            WorkflowServiceHelper.viewFlowchart(getView().getPageId(), entryRow.getString("billid"));
        }
    }
    public void botpCreateBillOpen(String sourceBillId,String sourceBillType,String targetBillType) {
        botpCreateBillOpen(sourceBillId,sourceBillType,targetBillType,"");
    }

    public void botpCreateBillOpen(String sourceBillId,String sourceBillType,String targetBillType,String ruleId){
        // 校验单据权限

        //构建选中行数据包
        List <ListSelectedRow> selectedRows = new ArrayList();
        ListSelectedRow selectedRow = new ListSelectedRow(Long.valueOf(sourceBillId));
        selectedRows.add(selectedRow);
        //获取转换规则id
        //ConvertRuleCache.loadRules()


        // 创建下推参数
        PushArgs pushArgs = new PushArgs();
        // 源单标识，必填
        pushArgs.setSourceEntityNumber(sourceBillType);
        // 目标单据标识，必填
        pushArgs.setTargetEntityNumber(targetBillType);
        // 生成转换结果报告，必填
        pushArgs.setBuildConvReport(true);
        //不检查目标单新增权限,非必填
        pushArgs.setHasRight(true);
        //传入下推使用的转换规则id，不填则使用默认规则
        pushArgs.setRuleId(ruleId);
        //下推默认保存，必填
        pushArgs.setAutoSave(true);
        // 设置源单选中的数据包，必填
        pushArgs.setSelectedRows(selectedRows);

        // 执行下推操作
        ConvertOperationResult convertResult = ConvertServiceHelper.push(pushArgs);
        //获取下推目标单id

        if (convertResult.isSuccess() && convertResult.getCachePageIds().size() + convertResult.getTargetBillIds().size() != 0) {
            if (convertResult.getCachePageIds().size() + convertResult.getTargetBillIds().size() == 1) {
                Push.showTargetBill(this.getView(), pushArgs, convertResult, false);
            } else {
                Push.showMultiTargetBills(this.getView(), pushArgs, convertResult, false);
            }
        }

    }
}
