package com.yem.wm.bd.customer.from.Validator;

import com.yem.or.utils.OrderApiUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.Map;

/**
 * ljw
 * 同步数据至下单平台
 */

public class CustomerValidator extends AbstractValidator {
    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for (ExtendedDataEntity dataEntitie : dataEntities) {
            DynamicObject mechanical = dataEntitie.getDataEntity();
            boolean yemCheckboxfield = mechanical.getBoolean("yem_checkboxfield");
            DynamicObject group = mechanical.getDynamicObject("group");
            if (!yemCheckboxfield && group != null) {
                long groupid = group.getLong("id");
                QFilter qFilter = new QFilter("parent.number", QCP.equals, "11602");
                QFilter qFilter1 = new QFilter("id", QCP.equals, groupid);
                 qFilter1.and(new QFilter("enable", QCP.equals, "1"));
                DynamicObject[] dynamicObjects = BusinessDataServiceHelper.load("bd_customergroup", "id,number,parent"
                        , new QFilter[]{qFilter, qFilter1});
                if (dynamicObjects.length > 0) {
                    String number = mechanical.getString("number");
                    String replace = number.replace("-", "");
                    String name = mechanical.getString("name");
                    Map<String, String> demands = OrderApiUtils.demands(name, replace);
                    String msg = demands.get("msg");
                    if (msg == null) {
                        String id = demands.get("id");
                        if (!"".equals(id)) {
                            mechanical.set("yem_torderid", id);
                            mechanical.set("yem_checkboxfield", true);
                            SaveServiceHelper.update(mechanical);
                            SaveServiceHelper.save(new DynamicObject[]{mechanical});
                        }
                    } else {
                        this.addErrorMessage(dataEntitie, msg);
                    }
                } else {
                    this.addErrorMessage(dataEntitie, "当前客户不满足同步条件，禁止同步至下单平台！！！");
                }
            } else {
                if (yemCheckboxfield) {
                    this.addErrorMessage(dataEntitie, "当前客户已同步下单平台！！");
                } else if (group == null) {
                    this.addErrorMessage(dataEntitie, "当前客户分组为空！！");
                }

            }
        }
    }
}
