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

import com.yem.wm.utils.GiftAmount;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author power
 * @ClassName
 * @description: 礼品额度申请 礼品退库申请 审核 服务插件
 * @date 2023/7/28
 */
public class LimitAuditOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        e.getFieldKeys().add("id");
        e.getFieldKeys().add("yem_customer");
        e.getFieldKeys().add("billno");

        e.getFieldKeys().add("yem_bizdate");
        e.getFieldKeys().add("yem_currency");
        e.getFieldKeys().add("yem_amount");

        e.getFieldKeys().add("yem_amountbase");
        e.getFieldKeys().add("yem_exrate");
        e.getFieldKeys().add("yem_remark");
        e.getFieldKeys().add("yem_billtype");
        e.getFieldKeys().add("org");
        e.getFieldKeys().add("yem_department");
        e.getFieldKeys().add("yem_proposer");
        e.getFieldKeys().add("yem_bd_products");
        e.getFieldKeys().add("yem_currencybase");
        e.getFieldKeys().add("yem_giftapplytype");
        e.getFieldKeys().add("yem_groupcusfields");

    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        // TODO 在此添加业务逻辑
        super.endOperationTransaction(e);
        //获取按钮
        String key = e.getOperationKey();
        DynamicObject[] entities = e.getDataEntities();
//        DynamicObject billTypese = BusinessDataServiceHelper.loadSingle("bos_billtype",
//                new QFilter[]{new QFilter("number", QCP.equals, "yem_spcapitalpool_BT"),});
        DynamicObject billTypeObject = BusinessDataServiceHelper.loadSingle("bos_billtype",
                "id", new QFilter[]{new QFilter("number", QCP.equals, "yem_im_giftamount_BT")});
        Long billTypes = billTypeObject.getLong("id");

        if(key.equals("audit")) {
            for (DynamicObject bill : entities) {
                String billType = bill.getString("yem_billtype.number");
                if (billType.equals("yem_im_giftapply_ED") || billType.equals("yem_im_giftapply_TK")){
//                    Long customer = bill.getLong("yem_customer.id");
                    DynamicObject saleorderCustomer = bill.getDynamicObject("yem_customer");
                    Long customer = null;//
                    if (saleorderCustomer != null) {
                        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(saleorderCustomer.getPkValue(), saleorderCustomer.getDynamicObjectType().getName());
                        if (dynamicObject != null) {
                            DynamicObject groupcusfields = dynamicObject.getDynamicObject("yem_groupcustomers");
                            if (groupcusfields  != null) {
                                customer = groupcusfields.getLong("id");
                            }
                        }
                    }
                    String id = String.valueOf(bill.getLong("id"));

                    DynamicObject org = bill.getDynamicObject("org");
                    DynamicObject customers = bill.getDynamicObject("yem_customer");

                    DynamicObject groupcusfields = bill.getDynamicObject("yem_groupcusfields");

                    DynamicObject department = bill.getDynamicObject("yem_department");
                    long proposer = bill.getLong("yem_proposer.id");

                    String billno = bill.getString("billno");
                    Date bizDate = bill.getDate("yem_bizdate");
                    DynamicObject currency = bill.getDynamicObject("yem_currency");

                    DynamicObject currencybase = bill.getDynamicObject("yem_currencybase");

                    BigDecimal amount = bill.getBigDecimal("yem_amount");
                    BigDecimal amountBase = bill.getBigDecimal("yem_amountbase");
                    BigDecimal exrate = bill.getBigDecimal("yem_exrate");
                    String remark = bill.getString("yem_remark");

                    Long orgs = bill.getLong("org.id");
                    Long yem_bd_products = bill.getLong("yem_bd_products.id");
                    DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_im_giftamount",
                            new QFilter[]{new QFilter("yem_groupcusfields.id", QCP.equals, customer),
                                    new QFilter("org", QCP.equals,orgs),
                                    new QFilter("yem_bd_products", QCP.equals,yem_bd_products)});

                    if (data != null){
                        DynamicObjectCollection entryentity = data.getDynamicObjectCollection("yem_im_giftamount_o");
                        DynamicObject newEntryEntity =  entryentity.addNew();
                        //礼品额度申请
                        if (billType.equals("yem_im_giftapply_ED")){
                            newEntryEntity.set("yem_origintype", "B");
                        }
                        //礼品退货
                        if (billType.equals("yem_im_giftapply_TK")){
                            newEntryEntity.set("yem_origintype", "C");
                        }
                        newEntryEntity.set("yem_producttype", yem_bd_products);
                        newEntryEntity.set("yem_giftapplicationtype", bill.getDynamicObject("yem_giftapplytype"));
                        newEntryEntity.set("yem_originno", billno);
                        newEntryEntity.set("yem_datetime", bizDate);
                        newEntryEntity.set("yem_origincurr", currency);
                        newEntryEntity.set("yem_originamt", amount);
                        newEntryEntity.set("yem_amountbase", amountBase);
                        newEntryEntity.set("yem_originexrate", exrate);
                        newEntryEntity.set("yem_entrygiftenable", amount);
                        newEntryEntity.set("yem_sneycrgiftenable", amountBase);
                        newEntryEntity.set("yem_originremark", remark);
                        newEntryEntity.set("yem_im_giftapplyids",id);
                        newEntryEntity.set("yem_userman", proposer);
                        newEntryEntity.set("yem_departmentes", department);

                        SaveServiceHelper.save(new DynamicObject[] {data});
                        GiftAmount.Calculate(customer,orgs,yem_bd_products);
                    }
                    if (data == null) {
                        DynamicObject datas = BusinessDataServiceHelper.newDynamicObject("yem_im_giftamount");
                        datas.set("yem_billtype",billTypes);
                        // 调用自动编码规则
                        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(datas.getDataEntityType().getName(), datas, null);
                        // 获取单据编码
                        String number = CodeRuleServiceHelper.getNumber(codeRule, datas);


                        datas.set("billno",number);

                        datas.set("billstatus","C");

                        datas.set("org",org);
                        datas.set("yem_bizdate",bizDate);
                        datas.set("yem_customer",customers);

                        datas.set("yem_groupcusfields", groupcusfields);

                        datas.set("yem_department",department);
                        datas.set("yem_currency",currencybase);
                        datas.set("yem_sumoriginamt",amount);
                        datas.set("yem_giftuse",amount);
                        datas.set("yem_giftenable",amount);
                        datas.set("yem_giftuseable",BigDecimal.ZERO);
                        datas.set("yem_bd_products",yem_bd_products);
                        datas.set("creator",proposer);
                        DynamicObjectCollection entryentity = datas.getDynamicObjectCollection("yem_im_giftamount_o");
                        DynamicObject newEntryEntity =  entryentity.addNew();
                        //礼品额度申请
                        if (billType.equals("yem_im_giftapply_ED")){
                            newEntryEntity.set("yem_origintype", "B");
                        }
                        //礼品退货
                        if (billType.equals("yem_im_giftapply_TK")){
                            newEntryEntity.set("yem_origintype", "C");
                        }
                        newEntryEntity.set("yem_producttype", yem_bd_products);
                        newEntryEntity.set("yem_originno", billno);
                        newEntryEntity.set("yem_giftapplicationtype", bill.getDynamicObject("yem_giftapplytype"));
                        newEntryEntity.set("yem_datetime", bizDate);
                        newEntryEntity.set("yem_origincurr", currency);
                        newEntryEntity.set("yem_originamt", amount);
                        newEntryEntity.set("yem_amountbase", amountBase);
                        newEntryEntity.set("yem_originexrate", exrate);
                        newEntryEntity.set("yem_entrygiftenable", amount);
                        newEntryEntity.set("yem_sneycrgiftenable", amountBase);
                        newEntryEntity.set("yem_originremark", remark);
                        newEntryEntity.set("yem_userman", proposer);
                        newEntryEntity.set("yem_departmentes", department);
                        newEntryEntity.set("yem_im_giftapplyids",id);

                        SaveServiceHelper.save(new DynamicObject[] {datas});
                        GiftAmount.Calculate(customer,orgs,yem_bd_products);


                    }
                }
            }

        }
        if (key.equals("unaudit")){
            for (DynamicObject bill : entities) {
                String billType = bill.getString("yem_billtype.number");
                if (billType.equals("yem_im_giftapply_ED") || billType.equals("yem_im_giftapply_TK")){
                    Long customer = bill.getLong("yem_customer.id");
                    Long orgs = bill.getLong("org.id");
                    Long yem_bd_products = bill.getLong("yem_bd_products.id");
                    String id = String.valueOf(bill.getLong("id"));
                    DynamicObject data = BusinessDataServiceHelper.loadSingle("yem_im_giftamount",
                            new QFilter[]{new QFilter("yem_groupcusfields.id", QCP.equals, customer),
                                    new QFilter("org", QCP.equals,orgs),
                                    new QFilter("yem_bd_products", QCP.equals,yem_bd_products)});
                    if (data!=null){
                        if (data.getDynamicObjectCollection("yem_im_giftamount_o").size()>0){
                            DynamicObjectCollection entryentity = data.getDynamicObjectCollection("yem_im_giftamount_o");
//                            int i=-1;
                            for (int j = 0; j < entryentity.size(); j++) {
                                if (entryentity.get(j).getString("yem_im_giftapplyids").equals(id)){
                                    entryentity.remove(j);
                                }
                            }
//                            for (DynamicObject entryentitys: entryentity) {
//                                i=i+1;
//                                if (entryentitys.getString("yem_im_giftapplyids").equals(id)){
//                                    break;
//                                }
//                            }
                        }
//                        DeleteServiceHelper.delete("yem_im_giftamount",
//                               null
//                        );
                        SaveServiceHelper.save(new DynamicObject[] {data});
                        GiftAmount.Calculate(customer,orgs,yem_bd_products);
                    }
                }
            }
        }

    }

}
