package yem.wmc.ydn.formplugin.dynamic;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Search;
import kd.bos.form.control.events.*;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import yem.base.common.utils.HttpHelper;
import yem.base.common.utils.StringUtils;
import yem.base.common.utils.YEM;
import yem.wmc.ydn.utils.APIAddressUtils;
import yem.wmc.ydn.utils.JsonToDataUtils;

import java.util.*;

/**
 * @author lipan
 * @date 2024/4/30 10:07
 * @className QueryshipdyDynamicForm
 * @description
 */
public class QueryshipdyDynamicForm extends AbstractFormPlugin implements SearchEnterListener, RowClickEventListener {

    public void registerListener(EventObject e) {
        // 注册监听
        Search search = this.getControl("yem_searchap");
        search.addEnterListener(this);
        EntryGrid entryGrid = this.getView().getControl("yem_entryentity");
        entryGrid.addRowClickListener(this);
    }

    /**
     * 输入回车进入方法
     *
     * @param e
     */
    @Override
    public void search(SearchEnterEvent e) {
        Search search = (Search) e.getSource();
        String key = search.getKey();
        String searchText = e.getText();
        if (key.equals("yem_searchap")) {//资源号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                IFormView view = this.getView();
                IDataModel model = this.getModel();
                getQueryShipInfo(searchText, view, model);

            }
        }
    }

    /**
     * 自动补全风格 输入搜索条件后 进入该方法组织数据返回前端显示*。
     *
     * @param evt 上下文
     * @return
     */
    @Override
    public List<String> getSearchList(SearchEnterEvent evt) {
        Search search = (Search) evt.getSource();
        String key = search.getKey();
        String searchText = evt.getText();
        if (key.equals("yem_searchap")) {//资源号搜索
            if (StringUtils.isNotEmpty(searchText)) {
                IFormView view = this.getView();
                IDataModel model = this.getModel();
                getQueryShipInfo(searchText, view, model);
            }
        }
        return null;
    }

    /**
     * 调用第三方接口获取单船搜索信息，并给动态表单赋值
     */
    public static void getQueryShipInfo(String searchText, IFormView view, IDataModel model) {
        JSONObject JObject = new JSONObject();
        JObject.put("keyword", searchText);
        String param = JObject.toString();
        Map<String, String> map = new HashMap<>();
        map.put("tenant-id", "1");
        try {
            String jsonResult = HttpHelper.httpPost(APIAddressUtils.Queryship, map, param);
            JSONObject body = JSON.parseObject(jsonResult);
            int code = body.getInteger("code");//获取状态
            if (code == 0) {
                JSONObject data = body.getJSONObject("data");
                Boolean aBoolean = data.getBoolean("success");
                if (data.containsKey("data") && aBoolean) {
                    JSONArray dataJSONArray = data.getJSONArray("data");
                    if (dataJSONArray.size() == 0) {
                        model.deleteEntryData("yem_entryentity");
                        view.showTipNotification("未搜索到任何数据");
                        return;
                    }
                    for (int index = 0; index < dataJSONArray.size(); index++) {
                        JSONObject Data = (JSONObject) dataJSONArray.get(index);
                        int newEntryRow = model.createNewEntryRow("yem_entryentity");
                        if (Data.containsKey("vslname")) {
                            String vslname = Data.getString("vslname");
                            if (vslname == null || vslname.equals("{}") || vslname.equals("")) {
                                model.setValue("yem_name", null, newEntryRow);
                            } else {
                                model.setValue("yem_name", Data.getString("vslname"), newEntryRow);
                            }
                        }
                        if (Data.containsKey("imono")) {
                            String imono = Data.getString("imono");
                            if (imono == null || imono.equals("{}") || imono.equals("")) {
                                model.setValue("yem_imono", null, newEntryRow);
                            } else {
                                model.setValue("yem_imono", imono, newEntryRow);
                            }
                        }
                        if (Data.containsKey("mmsi")) {
                            String mmsi = Data.getString("mmsi");
                            if (mmsi == null || mmsi.equals("{}") || mmsi.equals("")) {
                                model.setValue("yem_mmsi", null, newEntryRow);
                            } else {
                                model.setValue("yem_mmsi", mmsi, newEntryRow);
                            }
                        }
                    }
                    view.showSuccessNotification("搜索成功");
                }
            } else {
                view.showErrorNotification("搜索失败");
            }
        } catch (Exception e) {
            view.showErrorNotification(e.getMessage());
        }
    }

    public List<String> SearchList(String searchText) {
        Map<String, String> searchList = new HashMap<String, String>();
        QFilter filter = new QFilter("yem_entryentity.yem_partnumber", QCP.like, "%" + searchText + "%");
        DynamicObjectCollection collection = QueryServiceHelper.query("yem_em_assatlasdet",
                "id,yem_entryentity.yem_partnumber,yem_entryentity.yem_partname", new QFilter[]{filter});
        for (DynamicObject obj : collection) {
            searchList.put(obj.get("id").toString(), obj.get("yem_entryentity.yem_partnumber").toString());
        }
        return new ArrayList<>(searchList.values());
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Object shipname = showParameter.getCustomParam("shipname");
        if (shipname == null || shipname.equals("")) {
            return;
        }
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String yemShipname = (String) shipname;//船名
        if (yemShipname.contains("[") && yemShipname.contains("]")) {
            int index = yemShipname.lastIndexOf("[");
            yemShipname = yemShipname.substring(0, index);
        }
        yemShipname = yemShipname.trim();
        Search search = this.getControl("yem_searchap");
        search.setSearchKey(yemShipname);
        this.getView().setEnable(false,"yem_searchap");
        getQueryShipInfo(yemShipname, view, model);
    }


    /**
     * 根据用户选择的行数，获取mmsi号进行赋值
     * @param evt
     */
    @Override
    public void entryRowDoubleClick(RowClickEvent evt) {
        EntryGrid entryGrid = (EntryGrid)evt.getSource();
        String key = entryGrid.getKey();//单据体标识
        if (key.equals("yem_entryentity")){
            int row = evt.getRow();
            String yemMmsi = (String) this.getModel().getValue("yem_mmsi", row);
            if ( yemMmsi==null || yemMmsi.isEmpty()){
                this.getView().showTipNotification("请选择有效的行数");
                return;
            }
            this.getView().returnDataToParent(yemMmsi);
            this.getView().close();
        }
    }
}
