package fi.em.opplugin;

import fi.cas.opplugin.PayBillToolUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

/**
 * @description:代发处理单，传给九恒星
 */
public class AgentpaybillOpPlugin extends AbstractOperationServicePlugIn {




    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        DynamicObject[] dynamicObjects = e.getDataEntities();
        String operationKey = e.getOperationKey();
        //关闭付款则将支付状态更改为支付关闭状态
        if ("sendtojhx".equals(operationKey)){
            for (DynamicObject dataEntity : dynamicObjects) {
                DynamicObject payBillEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), "cas_agentpaybill");

                String paystatus = payBillEntity.getString("nckd_paystatus");
                int bbh = payBillEntity.getInt("nckd_bbh");
                int fkcs = payBillEntity.getInt("nckd_fkcs");
                String billstatusString = payBillEntity.getString("billstatus");
                if ("C".equals(billstatusString)&&("4".equals(paystatus)||"5".equals(paystatus))&&bbh>=0 && bbh==fkcs-1) {//状态为传输失败或驳回，（驳回必须走调整才能支付）
                    //状态为已审批，支付状态为失败，版本号>0,版本号=付款次数-1。符合付款条件，修改状态和版本号先
                    payBillEntity.set("nckd_paystatus", "1");//支付状态改回未支付
                    payBillEntity.set("nckd_bbh",bbh+1);
                    SaveServiceHelper.update(payBillEntity);
                }
            }



            String errMsg = "";
            errMsg =  PayBillToolUtil.agentpayBillForCBSSync(dynamicObjects);
            if(!errMsg.isEmpty()) {
                //将成功错误信息返回到前端
                e.setCancelMessage(errMsg);
                e.setCancel(true);
            }
        }
    }

}
