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

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.jimin.jyyy.fi.common.constant.ErReimBurseBillConstant;
import nckd.jimin.jyyy.fi.plugin.operate.validator.ReimBurseBillReceiveTicketValidator;

import java.util.Arrays;
import java.util.Date;

public class ReimBurseBillReceiveTicketOp extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        e.getFieldKeys().add(ErReimBurseBillConstant.KEY_BILLSTATUS);
        e.getFieldKeys().add(ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON);
        e.getFieldKeys().add(ErReimBurseBillConstant.KEY_NCKD_HANDIN_DATE);
        e.getFieldKeys().add(ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON);
        e.getFieldKeys().add(ErReimBurseBillConstant.KEY_NCKD_RECEIPT_DATE);
    }

    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.getValidators().add(new ReimBurseBillReceiveTicketValidator());
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        String operationKey = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        String billtype = this.billEntityType.getName();
        Arrays.stream(dataEntities).forEach(bill -> doHandInReceiptTicket(bill.getPkValue(),billtype,operationKey));
    }

    protected void doHandInReceiptTicket(Object billId , String billType,String operationKey){

        DynamicObject billInfo = BusinessDataServiceHelper.loadSingle(billId, billType, String.join(",", ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON,
                ErReimBurseBillConstant.KEY_NCKD_HANDIN_DATE, ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON, ErReimBurseBillConstant.KEY_NCKD_RECEIPT_DATE));
        long currUserId = RequestContext.get().getCurrUserId();
        Date now = new Date();
        if(operationKey.equals(ErReimBurseBillConstant.OPERATE.HANDIN_TICKET)){
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_HANDIN_PERSON,currUserId);
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_HANDIN_DATE,now);
        }

        if(operationKey.equals(ErReimBurseBillConstant.OPERATE.RECEIVE_TICKET)){
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_RECEIPT_PERSON,currUserId);
            billInfo.set(ErReimBurseBillConstant.KEY_NCKD_RECEIPT_DATE,now);
        }
        SaveServiceHelper.save(new DynamicObject[]{ billInfo });
    }

}
