package com.yem.wm.im.csrCreditLine.op;

import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.property.ComboProp;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.List;

/**
 * @Description TODO
 * @Date 2024/1/15 9:31
 * @Created by ZZSLL
 */

public class CsrCreditLineSaveOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_customer");
        fieldKeys.add("org");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_customercountry");
        fieldKeys.add("yem_type");
    }
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity : dataEntities) {
            genCreditTitle(dataEntity);
        }
    }


    /**
     * 保存时，按照  客户所在国 +买方英文名称+类型+信保限额申请  （4个字段，以空格间隔，拼接生成）
     */
    private void genCreditTitle(DynamicObject dataEntity) {
        // 客户所在国
        String customercountry = dataEntity.getString("yem_customercountry");
        // 买方英文名称
        DynamicObject customer = dataEntity.getDynamicObject("yem_customer");
        if (customer == null) {
            dataEntity.set("yem_credittitle", null);
            return;
        }
        ;
        String customerName = customer.getString("name");
        // 类型
        String type = dataEntity.getString("yem_type");
        if (YEM.isNotEmpty(customercountry) && YEM.isNotEmpty(customerName) && YEM.isNotEmpty(type)) {
            dataEntity.set("yem_credittitle", customercountry + " " + customerName + " " + extracted(dataEntity, "yem_type") + " " + "信保限额申请");
        } else {
            dataEntity.set("yem_credittitle", null);
        }
//        SaveServiceHelper.save(new DynamicObject[]{dataEntity});
    }

    /**
     * @description: 获取下拉列表的标题
     * @author yhj
     * @date 2023/9/4 10:51
     * @version 1.0
     * obs 标识
     * obj 标识所在单据或分录的数据包
     */
    private static String extracted(DynamicObject obj, String obs) { //获取下拉列表v,获取标题方法
        MainEntityType mainEntityType = (MainEntityType) obj.getDataEntityType();//获取主实体
        DataEntityPropertyCollection properties = mainEntityType.getProperties();//获取属性
        ComboProp comboUnitProp = (ComboProp) properties.get(obs);//获取字段的数据模型
        String comb = comboUnitProp.getItemByName(obj.getString(obs));//根据value获取key（标题）
        return comb;
    }
}

