package com.yem.wm.im.tracktaskconsole.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.RequestEAS;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.Button;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.util.*;

/**
 * 配件库存查询-yem_accessorystorequery
 */
public class AccessoryStoreQueryFormPlugin extends AbstractFormPlugin {
    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        FormShowParameter fsp = view.getFormShowParameter();
        Map<String, Object> customParams = fsp.getCustomParams();
        //materialid
        long materialid = (long) customParams.get("materialid");
        //materialnum
        String materialnum = (String) customParams.get("materialnum");
        //yem_inqureqty
        BigDecimal yem_inqureqty = (BigDecimal) customParams.get("yem_inqureqty");
        model.setValue("yem_inqureqty", yem_inqureqty);
        String yem_stockway = (String) customParams.get("yem_stockway");
        model.setValue("yem_stockway", yem_stockway);
        //yem_isvmi
        String yem_isvmi = customParams.get("yem_isvmi").toString();
        //查询所有仓库
        DynamicObjectCollection whs = QueryServiceHelper.query("yem_warehouse", "id,number,yem_belong",
                new QFilter[]{new QFilter("yem_sort", QCP.equals, yem_isvmi),
                        new QFilter("enable",QCP.equals,"1")},
                "yem_belong");
        DynamicObjectCollection whs1 = QueryServiceHelper.query("yem_warehouse", "id,number,useorg.number,yem_belong",
                new QFilter[]{new QFilter("yem_sort", QCP.equals, yem_isvmi),
                        new QFilter("yem_belong", QCP.equals, "A"),
                        new QFilter("enable",QCP.equals,"1")
                },
                "yem_belong");
        DynamicObjectCollection connColl = QueryServiceHelper.query("yem_cmmpconfig", "yem_remark,id,yem_belong", new QFilter[]{new QFilter("yem_num", QCP.in, new String[]{"ZZJ", "CC", "NZ"})});
//        this.getModel().deleteEntryData("yem_entryentity");
        queryCMMP(customParams, materialid, materialnum, yem_isvmi, whs, connColl);
        //TODO
        queryEAS(customParams, materialid, materialnum, yem_isvmi, whs1);
    }

    /**
     * 查询EAS库存
     *
     * @param customParams 参数
     * @param materialid   物料ID
     * @param materialnum  物料编码
     * @param yemIsvmi     仓库类型
     * @param whs          仓库集合
     */
    private void queryEAS(Map<String, Object> customParams, long materialid, String materialnum, String yemIsvmi, DynamicObjectCollection whs) {
        {
            //通过仓库分类查询所有EAS的仓库
            JSONArray storageOrgs = new JSONArray();
            Set storageOrgs1 = new HashSet();
            Set warehouses1 = new HashSet();
            JSONArray warehouses = new JSONArray();
            for (DynamicObject wh : whs) {
                String useorgnum = wh.getString("useorg.number");
                storageOrgs1.add(useorgnum);
                String whnum = wh.getString("number");
                warehouses1.add(whnum);
            }
            for (Object o : storageOrgs1) {
                storageOrgs.add(o);
            }
            for (Object o : warehouses1) {
                warehouses.add(o);
            }
            JSONObject json = new JSONObject();
            json.put("start", 0);
            json.put("len", 1000);
            json.put("storageOrgs", storageOrgs);
            json.put("warehouses", warehouses);
            json.put("materialNumFrom", materialnum);//物料起--必填
            json.put("materialNumTo", materialnum);//物料止--必填
            String s = RequestEAS.InventoryListServiceFacadeGetData(json.toString());
            JSONObject result = JSONObject.parseObject(s);
            JSONArray list = result.getJSONArray("list");
            BigDecimal qty = BigDecimal.ZERO;
            if (list != null) {
                if (list.size() == 1000) {
                    json.put("start", (json.getIntValue("start") + 1) * json.getIntValue("len"));
                    s = RequestEAS.InventoryListServiceFacadeGetData(json.toString());
                    result = JSONObject.parseObject(s);
                    list.addAll(result.getJSONArray("list"));
                }
                for (int i = 0; i < list.size(); i++) {
                    JSONObject o = (JSONObject) list.get(i);
                    BigDecimal fRealQty = o.getBigDecimal("FRealQty");
                    if (fRealQty == null) {
                        qty = qty.add(BigDecimal.ZERO);
                    } else {
                        qty = qty.add(fRealQty);
                    }
                }
            }
        }

    }

    /**
     * 查询CMMP库存
     *
     * @param customParams 参数
     * @param materialid   物料ID
     * @param materialnum  物料编码
     * @param yem_isvmi    仓库类型
     * @param whs          仓库集合
     * @param connColl     链接集合
     */
    private void queryCMMP(Map<String, Object> customParams, long materialid, String materialnum, String yem_isvmi, DynamicObjectCollection whs, DynamicObjectCollection connColl) {
        //CMMP查询
        for (DynamicObject connObj : connColl) {
            //每个数据库链接执行一次
            String yem_belong = connObj.getString("yem_belong");
            ArrayList<String> whnumlist = new ArrayList<>();
            for (DynamicObject wh : whs) {
                if (yem_belong.equals(wh.getString("yem_belong"))) {
                    whnumlist.add(wh.getString("number"));
                }
            }
            StringBuilder sb = new StringBuilder();
            for (String s : whnumlist) {
                sb.append("'" + s + "',");
            }
            sb.append("''");
            String sql = "SELECT sum(canuse_num) b,wh_code from " +
                    "VIEW_MATER_STOCK_WM where mater_code ='" + materialnum + "' and wh_code in (" + sb.toString() + ") group by wh_code";
            List<Map> qtyList = RequestCmmp.getFromCmmpWithConnId(connObj.getLong("id"), sql);
            for (Map map : qtyList) {
                BigDecimal canuseNum = (BigDecimal) map.get("b");
                String wh_code = (String) map.get("wh_code");
                int yemEntryentity = this.getModel().createNewEntryRow("yem_entryentity");
                this.getModel().setValue("yem_materiel", materialid, yemEntryentity);
                this.getModel().setValue("yem_isvmi", yem_isvmi, yemEntryentity);
                DynamicObject obj = QueryServiceHelper.queryOne("yem_warehouse", "id", new QFilter[]{new QFilter("number", QCP.equals, wh_code)});
                this.getModel().setValue("yem_wh", obj.getLong("id"), yemEntryentity);
                this.getModel().setValue("yem_store", canuseNum, yemEntryentity);
                this.getModel().setValue("yem_enableqty", canuseNum, yemEntryentity);
                this.getModel().setValue("yem_retqty", BigDecimal.ZERO, yemEntryentity);
                JSONObject map1 = (JSONObject) customParams.get("map");
                if (map1.containsKey(wh_code)) {
                    BigDecimal yem_alreadyqty = (BigDecimal) map1.get(wh_code);
                    this.getModel().setValue("yem_alreadyqty", yem_alreadyqty, yemEntryentity);
                    this.getModel().setValue("yem_enableqty", canuseNum.subtract(yem_alreadyqty), yemEntryentity);
                    this.getModel().setValue("yem_retqty", yem_alreadyqty, yemEntryentity);
                }
            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if ("yem_useqty".equals(e.getProperty().getName())) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_entryentity");
            //返回数量=
            Integer yem_alreadyqty = (Integer) collection.get(rowIndex).get("yem_alreadyqty");
            Integer yem_useqty = (Integer) collection.get(rowIndex).get("yem_useqty");
            collection.get(rowIndex).set("yem_retqty", yem_alreadyqty + yem_useqty);
            this.getView().updateView();
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        Button btnok = this.getView().getControl("btnok");
        if (null != btnok) {
            this.addClickListeners(new String[]{"btnok"});
        }
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control c = (Control) evt.getSource();
        String key = c.getKey().toLowerCase();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        if (key.equals("btnok")) {
            //校验分录和
            int yemInqureqty = (int) model.getValue("yem_inqureqty");
            int sumyem_retqty = 0;
            DynamicObjectCollection entrys = model.getDataEntity().getDynamicObjectCollection("yem_entryentity");
            int erow = model.getEntryRowCount("yem_entryentity");
            for (int i = 0; i < erow; i++) {
                int yemRetqty = (int) model.getValue("yem_retqty", i);
                int yem_store = (int) model.getValue("yem_store", i);
                if (yem_store < yemRetqty) {
                    view.showErrorNotification("返回数量大于可用数量！");
                    return;
                }
                if (yemRetqty < 0) {
                    view.showErrorNotification("返回数量总和大于0！");
                    return;
                }
                sumyem_retqty = yemRetqty + sumyem_retqty;
            }
            if (yemInqureqty < sumyem_retqty) {
                view.showErrorNotification("返回数量总和大于需求数量总和！");
                return;
            } else {
                ArrayList<Map<String, Object>> list = new ArrayList<>();
                EntryGrid control = this.getControl("yem_entryentity");
                int[] rows = control.getSelectRows();
                if (rows.length > 0) {
                    int i = rows[0];
                    HashMap<String, Object> map = new HashMap<>();
                    //物料ID
                    long yem_materielg = ((DynamicObject) model.getValue("yem_materiel", i)).getLong("id");
                    map.put("yem_materielg", yem_materielg);
                    //仓库类型
                    String yem_isvmi = (String) model.getValue("yem_isvmi", i);
                    map.put("yem_isvmi", yem_isvmi);
                    //仓库
                    long yem_outhouse = ((DynamicObject) model.getValue("yem_wh", i)).getLong("id");
                    map.put("yem_outhouse", yem_outhouse);
                    //返回数量
                    int yem_stockqty = (int) model.getValue("yem_retqty", i);
                    map.put("yem_stockqty", yem_stockqty);
                    map.put("yem_stockway", model.getValue("yem_stockway"));
                    list.add(map);
                }

                if (erow > 0 && rows.length < 1) {
                    view.showMessage("请选择需要返回的数据！！");
                    return;
                }

                view.returnDataToParent(list);
                view.close();
            }
        }
    }
}
