package com.yem.em.dynamic;

import com.yem.wm.utils.YEM;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhouc
 * @date 2023/9/2 16:37
 * @className ShoppingListDynamicEdit
 * @description 购物清单动态表单插件
 */
public class ShoppingListDynamicEdit extends AbstractFormPlugin {

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        IDataModel model = this.getModel();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParas = showParameter.getCustomParams();
        //查询当前用户共购物车，下单状态为未下单的
        setentryentity();
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        FormOperate operate = (FormOperate) e.getSource();
        String key = operate.getOperateKey();
        if (key.equals("place")) {
            int Success = 0;
            EntryGrid entryGrid = this.getControl("yem_entryentity");
            //获取选中行，数组为行号，从0开始int[]
            int selectRows[] = entryGrid.getSelectRows();
            Success = Addpartsorder(selectRows);
            if (Success > 0) {
                setentryentity();
                this.getView().showSuccessNotification(ResManager.loadKDString("下单成功！", "EtcmanualEdit_10", "yem_em_shoppinglist"));
            }
        }
        if (key.equals("cancel")) {
            this.getView().close();
        }
    }


    public void setentryentity() {
        IDataModel model = this.getModel();
        QFilter qFilters = new QFilter("yem_shoppingstatus", QCP.equals, "N");
        qFilters.and(new QFilter("yem_user.id", QCP.equals, YEM.getCurrentUserId()));
        DynamicObjectCollection yem_em_shopcartbill = QueryServiceHelper.query("yem_em_shopcartbill", "id,number,name,yem_pnumber,yem_enname,yem_materielmodel,yem_qty", new QFilter[]{qFilters});
        if (yem_em_shopcartbill.size() > 0) {
            model.deleteEntryData("yem_entryentity");
            for (int i = 0; i < yem_em_shopcartbill.size(); i++) {
                DynamicObject shopcartbill = yem_em_shopcartbill.get(i);
                int row = this.getModel().createNewEntryRow("yem_entryentity");
                model.setValue("yem_pnumber", shopcartbill.getString("yem_pnumber"), row);
                model.setValue("yem_name", shopcartbill.getString("name"), row);
                model.setValue("yem_enname", shopcartbill.getString("yem_enname"), row);
                model.setValue("yem_materielmodel", shopcartbill.getString("yem_materielmodel"), row);
                model.setValue("yem_qty", shopcartbill.getBigDecimal("yem_qty"), row);
                model.setValue("yem_shopcartbillid", shopcartbill.getString("id"), row);
            }
            this.getView().updateView("yem_entryentity");
        }
        else{
            model.deleteEntryData("yem_entryentity");
        }

    }

    /**
     * 构建购物清单
     *
     * @param selectRows 选择分录行
     * @return 成功行数
     */
    public int Addpartsorder(int selectRows[]) {
        if (selectRows.length > 0) {
            Map<String, Object> map = new HashMap<>();
            //新增配件订单
            Random random = new Random();
            int randomNumber = random.nextInt(10000);
            String formattedNumber = String.format("%04d", randomNumber);
            Date totay = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String dayStr = sdf.format(totay);
            MainEntityType type = EntityMetadataCache.getDataEntityType("yem_em_partsorder");
            DynamicObject carShop = new DynamicObject(type);
            carShop.set("billno", dayStr + "_" + formattedNumber);
            carShop.set("yem_date", totay);
            carShop.set("billstatus", "A");
            DynamicObjectCollection entryentity = carShop.getDynamicObjectCollection("entryentity");
            for (int i = 0; i < selectRows.length; i++) {
                DynamicObject shopcartbill = this.getModel().getEntryRowEntity("yem_entryentity", selectRows[i]);
                DynamicObject Newentryentity = entryentity.addNew();
                Newentryentity.set("yem_pnumber", shopcartbill.getString("yem_pnumber"));
                Newentryentity.set("yem_name", shopcartbill.getString("yem_name"));
                Newentryentity.set("yem_enname", shopcartbill.getString("yem_enname"));
                Newentryentity.set("yem_materielmodel", shopcartbill.getString("yem_materielmodel"));
                Newentryentity.set("yem_qty", shopcartbill.getBigDecimal("yem_qty"));
                map.put(shopcartbill.getString("yem_shopcartbillid"), shopcartbill.getString("yem_shopcartbillid"));
            }
            OperationResult Operate = OperationServiceHelper.executeOperate("save", carShop.getDynamicObjectType().getName(), new DynamicObject[]{carShop}, OperateOption.create());
            if (Operate.isSuccess()) {
                int k = 0;
                for (String key : map.keySet()) {
                    DynamicObject yem_em_substitution = BusinessDataServiceHelper.loadSingle(key, "yem_em_shopcartbill");
                    yem_em_substitution.set("yem_shoppingstatus", "Y");
                    SaveServiceHelper.save(new DynamicObject[]{yem_em_substitution});
                    k++;
                }
                return k;
            }
        }
        return 0;
    }


}
