package fi.cas.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import com.alibaba.druid.util.StringUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;


public class PayToZFQZOP  extends AbstractOperationServicePlugIn {
    private static final String ENTITY_NAME = "cas_paybill";

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);


    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {

        String errMsg = "";

        //获取选中行
        DynamicObject[] billEntities = e.getDataEntities();
        String operationKey = e.getOperationKey();


        //获取操作按钮操作编码
        if (StringUtils.equals( "paytojhx",operationKey)){
            for (DynamicObject dataEntity : billEntities) {
                DynamicObject payBillEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), ENTITY_NAME);

                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);
                }
            }
            errMsg =  PayBillToolUtil.payBillForCBSSync(billEntities);
        }
        if(!errMsg.isEmpty()) {
            //将成功错误信息返回到前端
            e.setCancelMessage(errMsg);
            e.setCancel(true);
        }
    }


    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);

    }
}
