package nckd.jxccl.sit.hcsi.formplugin.web.tp;

import nckd.jxccl.base.common.utils.DateTimeUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.events.GetEntityTypeEventArgs;
import kd.bos.entity.property.DateProp;
import kd.bos.entity.property.TextProp;
import kd.bos.exception.KDBizException;
import kd.bos.form.FormShowParameter;
import kd.bos.form.container.Container;
import kd.bos.form.control.Control;
import kd.bos.form.events.BeforeCreateListColumnsArgs;
import kd.bos.form.events.BeforeCreateListDataProviderArgs;
import kd.bos.form.events.OnGetControlArgs;
import kd.bos.list.BillList;
import kd.bos.list.DateListColumn;
import kd.bos.list.IListColumn;
import kd.bos.list.ListColumn;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.list.ListDataProvider;
import kd.bos.mvc.list.ListView;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.swc.helper.SWCHelper;
import nckd.jxccl.sit.hcsi.business.importtaskguide.utils.ImportTaskUtils;
import org.apache.commons.lang.exception.ExceptionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Tyx 2025-11-27
 * 外部数据导入中间表列表插件
 * 根据模板配置的项目动态配置列
 * 包含构建列及provider
 */
public class SinsurTempDataViewBillListPlugin extends AbstractListPlugin implements Plugin {

    private static final Log logger = LogFactory.getLog(SinsurTempDataViewBillListPlugin.class);
    private SisurTempDataEntityTypeBillList billList;
    // 定义一个静态集合，存储常用列的key
    private static final Set<String> COMMONCOLUMNSET = new HashSet(8);

    // 静态代码块，初始化常用列集合
    static {
        COMMONCOLUMNSET.add("fseq");
        COMMONCOLUMNSET.add("nckd_datastatus");
        COMMONCOLUMNSET.add("billstatus");
        COMMONCOLUMNSET.add("nckd_importtask.name");
        COMMONCOLUMNSET.add("nckd_empname");
        COMMONCOLUMNSET.add("nckd_idcard");
        COMMONCOLUMNSET.add("nckd_periodname");
    }

    /**
     * 获取实体类型
     * @param args 获取实体类型的事件参数
     */
    public void getEntityType(GetEntityTypeEventArgs args) {
        super.getEntityType(args);
        args.setNewEntityType(this.getEntityType());
    }

    /**
     * 获取新的实体类型
     * @return 返回处理后的实体类型
     */
    private MainEntityType getEntityType() {
        MainEntityType mainType = EntityMetadataCache.getDataEntityType("nckd_sinsurtempdata");
        MainEntityType mainEntityType = null;

        try {
            mainEntityType = (MainEntityType)mainType.clone();
        } catch (CloneNotSupportedException var4) {
            logger.error("getNewEntityType: ", var4);
            throw new KDBizException(ExceptionUtils.getFullStackTrace(var4));
        }

        if (mainEntityType == null) {
            return mainType;
        } else {
            List<Map<String, String>> columnHeadList = this.getColumnHeadList();
            this.addItemProp(mainEntityType, columnHeadList);
            return mainEntityType;
        }
    }

    /**
     * 获取控件
     * @param args 获取控件的事件参数
     */
    public void onGetControl(OnGetControlArgs args) {
        super.onGetControl(args);
        String key = args.getKey();
        Control customControl = null;
        if ("billlistap".equals(key)) {
            customControl = this.createBillList(key);
        }
        if (customControl != null) {
            args.setControl(customControl);
        }
    }


    /**
     * 构建列表
     * @param key 列表的key值
     * @return 返回构建好的BillList对象
     */
    protected BillList createBillList(String key) {
        if (this.billList != null) {
            return this.billList;
        } else {
            this.billList = new SisurTempDataEntityTypeBillList(this.getEntityType());
            this.billList.setKey(key);
            this.billList.setEntityId("nckd_sinsurtempdata");
            ListView listView = (ListView)this.getView();
            this.billList.setBillFormId(listView.getBillFormId());
            this.billList.setView(listView);
            Container rootControl = (Container)this.getView().getRootControl();
            this.replaceBillList(rootControl.getItems(), this.billList);
            return this.billList;
        }
    }

    /**
     * 替换列表控件
     * @param items 控件列表
     * @param billList 要替换的列表控件
     */
    private void replaceBillList(List<Control> items, Control billList) {
        for(int i = 0; i < items.size(); ++i) {
            Control control = (Control)items.get(i);
            if (control.getKey().equals(billList.getKey())) {
                items.set(i, billList);
                return;
            }
            if (control instanceof Container) {
                this.replaceBillList(((Container)control).getItems(), billList);
            }
        }
    }

    /**
     * 构建列表列之前方法
     * @param args
     */
    @Override
    public void beforeCreateListColumns(BeforeCreateListColumnsArgs args) {
        List<IListColumn> columnList = args.getListColumns();
        List<IListColumn> commonColumnList = new ArrayList(10);
        Map<String, IListColumn> otherFixColumnMap = new HashMap(16);
        Iterator it = columnList.iterator();

        while(it.hasNext()) {
            IListColumn obj = (IListColumn)it.next();
            if (COMMONCOLUMNSET.contains(obj.getListFieldKey())) {
                commonColumnList.add(obj);
            } else {
                otherFixColumnMap.put(obj.getListFieldKey(), obj);
            }
        }

        columnList.clear();
        columnList.addAll(commonColumnList);
        List<Map<String, String>> columnHeadList = this.getColumnHeadList();
        if (!SWCHelper.isEmpty(columnList)) {
            int seq = columnList.size() + 1;
            String key = null;
            String itemType = null;
            it = columnHeadList.iterator();

            while(it.hasNext()) {
                Map<String, String> tempMap = (Map)it.next();
                Long dataTypeId = Long.valueOf((String)tempMap.get("datatypeid"));
                String name = (String)tempMap.get("name");
                key = (String)tempMap.get("key");
                itemType = (String)tempMap.get("itemType");
                if ("0".equals(itemType)) {
                    if (!COMMONCOLUMNSET.contains(key)) {
                        IListColumn tempColumn = (IListColumn)otherFixColumnMap.get(key);
                        if (tempColumn != null) {
                            columnList.add(tempColumn);
                            ++seq;
                        }
                    }
                } else {
                    if (1050L == dataTypeId) {
                        DateListColumn dateListColumn = new DateListColumn();
                        dateListColumn.setDisplayFormatString("yyyy-MM-dd");
                        dateListColumn.setCaption(new LocaleString(name));
                        dateListColumn.setKey(key);
                        dateListColumn.setListFieldKey(key);
                        dateListColumn.setSeq(seq);
                        columnList.add(dateListColumn);
                    } else {
                        ListColumn column = new ListColumn();
                        column.setCaption(new LocaleString(name));
                        column.setKey(key);
                        column.setListFieldKey(key);
                        column.setSeq(seq);
                        columnList.add(column);
                    }
                    ++seq;
                }
            }

        }
    }

    /**
     * 获取导入任务模板上的字段
     * @return
     */
    private List<Map<String, String>> getColumnHeadList() {
        List<Map<String, String>> columnHeadList = new ArrayList(10);
        Long sinsurTplId = (Long)this.getView().getFormShowParameter().getCustomParam("sinsurTplId");
        FormShowParameter parameter = this.getView().getFormShowParameter();
        return (List)(sinsurTplId != null && sinsurTplId != 0L ? ImportTaskUtils.getColumnHeadList(sinsurTplId, (Long)parameter.getCustomParam("importTaskId")) : columnHeadList);
    }

    /**
     * 添加ListDataProvider
     * @param args
     */
    @Override
    public void beforeCreateListDataProvider(BeforeCreateListDataProviderArgs args) {
        args.setListDataProvider(new ImportItemDataResultImpl());
    }

    private void addItemProp(DynamicObjectType mainEntityType, List<Map<String, String>> columnHeadList) {
        String key = null;
        Long dataTypeId = null;
        String name = null;
        String itemType = null;
        Iterator it = columnHeadList.iterator();

        while(true) {
            while(true) {
                Map temMap;
                do {
                    if (!it.hasNext()) {
                        return;
                    }
                    temMap = (Map)it.next();
                    key = (String)temMap.get("key");
                    itemType = (String)temMap.get("itemType");
                } while("0".equals(itemType));

                dataTypeId = Long.valueOf((String)temMap.get("datatypeid"));
                name = (String)temMap.get("name");
                if (1030L != dataTypeId && 1010L != dataTypeId && 1020L != dataTypeId) {
                    if (1050L == dataTypeId) {
                        DateProp property = new DateProp();
                        property.setName(key);
                        property.setDisplayName(new LocaleString(name));
                        mainEntityType.addProperty(property);
                    }
                } else {
                    TextProp property = new TextProp();
                    property.setName(key);
                    property.setDisplayName(new LocaleString(name));
                    property.setMaxLenth(200);
                    mainEntityType.addProperty(property);
                }
            }
        }
    }


    public class ImportItemDataResultImpl extends ListDataProvider {
        public ImportItemDataResultImpl() {
        }
        @Override
        public DynamicObjectCollection getData(int start, int limit) {
            DynamicObjectCollection list = super.getData(start, limit);
            if (this.getQueryBuilder().isSelectedAllRows()) {
                return list;
            } else {
                List<Map<String, String>> columnHeadList = SinsurTempDataViewBillListPlugin.this.getColumnHeadList();
                if (SWCHelper.isEmpty(columnHeadList)) {
                    return list;
                } else {
                    SinsurTempDataViewBillListPlugin.this.addItemProp(list.getDynamicObjectType(), columnHeadList);
                    List<Long> idList = (List)list.stream().map((objx) -> {
                        return objx.getLong("id");
                    }).collect(Collectors.toList());
                    Map<Long, Map<String, Object>> itemDataMap = this.getItemDataMap(idList);
                    if (itemDataMap.size() == 0) {
                        return list;
                    } else {
                        Map<String, Object> tempMap = null;
                        Iterator it = list.iterator();
                        while(true) {
                            DynamicObject obj;
                            do {
                                do {
                                    if (!it.hasNext()) {
                                        return list;
                                    }
                                    obj = (DynamicObject)it.next();
                                    tempMap = (Map)itemDataMap.get(obj.getLong("id"));
                                } while(tempMap == null);
                            } while(tempMap.size() == 0);

                            Iterator it1 = tempMap.entrySet().iterator();

                            while(it1.hasNext()) {
                                Map.Entry<String, Object> entry = (Map.Entry)it1.next();
                                obj.set((String)entry.getKey(), entry.getValue());
                            }
                        }
                    }
                }
            }
        }

        private Map<Long, Map<String, Object>> getItemDataMap(List<Long> idList) {
            Map<Long, Map<String, Object>> itemDataMap = new HashMap(16);
            HRBaseServiceHelper helper = new HRBaseServiceHelper("nckd_sinsurtempdata");
            String fields = "id,entryentity.nckd_itemtype,entryentity.nckd_itemid,entryentity.nckd_datatype,entryentity.nckd_itemvalue";
            QFilter qFilter = new QFilter("id", "in", idList);
            DynamicObjectCollection itemData = helper.queryOriginalCollection(fields, new QFilter[]{qFilter});
            if (itemData.size() == 0) {
                return itemDataMap;
            } else {
                Map<String, Object> tempMap = null;
                long dataTypeId = 0L;
                String itemValue = null;
                String columnKey = null;
                Iterator var12 = itemData.iterator();

                while(true) {
                    while(true) {
                        DynamicObject obj;
                        do {
                            if (!var12.hasNext()) {
                                return itemDataMap;
                            }

                            obj = (DynamicObject)var12.next();
                            tempMap = (Map)itemDataMap.get(obj.getLong("id"));
                            if (tempMap == null) {
                                tempMap = new HashMap(16);
                                itemDataMap.put(obj.getLong("id"), tempMap);
                            }

                            dataTypeId = obj.getLong("entryentity.nckd_itemtype");
                            itemValue = obj.getString("entryentity.nckd_itemvalue");
                        } while(itemValue == null);

                        columnKey = this.getColumnKey(obj.getString("entryentity.nckd_itemtype"), obj.getLong("entryentity.nckd_itemid"));
                        if (1020L != dataTypeId && 1010L != dataTypeId) {
                            if (1050L == dataTypeId) {
                                try {
                                    ((Map)tempMap).put(columnKey, DateTimeUtils.parseDate(itemValue, "yyyy-MM-dd"));
                                } catch (ParseException var15) {
                                    SinsurTempDataViewBillListPlugin.logger.error("parse itemValue error", var15);
                                    throw new KDBizException(ExceptionUtils.getFullStackTrace(var15));
                                }
                            } else {
                                ((Map)tempMap).put(columnKey, itemValue);
                            }
                        } else {
                            ((Map)tempMap).put(columnKey, new BigDecimal(itemValue));
                        }
                    }
                }
            }
        }

        private String getColumnKey(String itemType, long itemId) {
            String columnKey = "";
            if ("4".equals(itemType)) {
                columnKey = "ft" + itemId;
            } else if ("1".equals(itemType)) {
                columnKey = "ii" + itemId;
            } else if ("3".equals(itemType)) {
                columnKey = "bs" + itemId;
            } else if ("2".equals(itemType)) {
                columnKey = "sp" + itemId;
            }

            return columnKey;
        }


    }
}