package com.yem.wm.es.salescontrac.form;

import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IFormView;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.EventObject;

/**
 * @Description 框架合同表单插件
 * @Date 2024/1/29 14:16
 * @Created by ZZSLL
 */

public class SalesContractEdit extends AbstractBillPlugIn implements  BeforeF7SelectListener
{
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e)
    {
        super.afterDoOperation(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        String operateKey = e.getOperateKey();
        if ("save".equals(operateKey))
        {
            String billno = dataEntity.getString("billno");
            boolean isLastCharLetter = billno.matches(".*[A-Za-z]$");
            if (isLastCharLetter) return;
            String customBillno = SalesOrderUtils.replaceSerialNumberWithLetters(billno, dataEntity.getDataEntityType().getName());
            dataEntity.set("billno", customBillno);
            view.updateView("billno");
            SaveServiceHelper.save(new DynamicObject[]{model.getDataEntity(true)});
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit yem_internationalrate = this.getControl("yem_internationalrate");
        if (yem_internationalrate != null) {
            yem_internationalrate.addBeforeF7SelectListener(this);
        }
    }
    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject datas = model.getDataEntity(true);
        String key = e.getProperty().getName();
        int rowIndex = e.getRow();
        QFilter qFilter = null;
        switch (key) {
            case "yem_internationalrate":
                DynamicObject yem_currency = datas.getDynamicObject("yem_currency");
                if (yem_currency != null) {
                    qFilter = new QFilter("yem_currency.number", QCP.equals, yem_currency.getString("number"));
                    qFilter.and(new QFilter("enable", QCP.equals, "1"));
                    e.addCustomQFilter(qFilter);
                }
                break;
            default:
                break;
        }
    }
}
