package yem.base.common.module.meta.report;

import kd.bos.algo.Algo;
import kd.bos.algo.DataSet;
import kd.bos.algo.RowMeta;
import kd.bos.algo.input.CollectionInput;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.report.*;
import kd.bos.orm.ORM;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;
import yem.base.common.utils.RptUtil;
import yem.base.common.utils.YEM;

import java.util.*;

/**
 * 数据比对
 *
 * @Description: 报表查询插件
 * @Date: 2024/4/11 13:54
 * @Auther: longh
 */
public class DataCompareRptQuery extends AbstractReportListDataPlugin implements Plugin {
    private static final String algoKey = DataCompareRptQuery.class.getName();
    private static final Map<String, String> fieldMap = new HashMap<>();

    @Override
    public DataSet query(ReportQueryParam queryParam, Object o) throws Throwable {
        FilterInfo filterInfo = queryParam.getFilter();
        DynamicObject yem_fentityobj = filterInfo.getDynamicObject("yem_fentityobj");
        String entityKey = yem_fentityobj == null ? "" : yem_fentityobj.getString("number");
        boolean onlyChanged = filterInfo.getBoolean("yem_onlychanged");
        Object[] pkArray = (Object[]) filterInfo.getValue("yem_entryentity");
//        QFilter qFilter = new QFilter("billno", QCP.in, new String[]{"CGDD-240411-0010-P", "CGDD-240411-0009-P", "CGDD-240411-0008-P"});
//        DynamicObject[] ids = BusinessDataServiceHelper.load(entityKey, "id", qFilter.toArray());
//        Object[] pkArray = Stream.of(ids).map(DataEntityBase::getPkValue).collect(Collectors.toList()).toArray();
        DynamicObject[] bills = BusinessDataServiceHelper.load(pkArray, YEM.getDataEntityType(entityKey));

        //"pm_purorderbill"
        DataSet dataSet = DataDictionaryRptQuery.queryDataBill(entityKey);
        List<String> aliasList = RptUtil.getDataSetAliasList(dataSet);
        aliasList.add("false yem_change");
        fieldMap.clear();
        for (int i = 0; i < bills.length; i++) {
            String key = "yem_data" + i + 1;
            DynamicObject bill = bills[i];
            String valueKey = bill.containsProperty("billno") ? bill.getString("billno") : bill.containsProperty("number") ? bill.getString("number") : bill.getString("id");
            fieldMap.put(key, valueKey);
            aliasList.add("'' " + key);
        }
        dataSet = dataSet.select(aliasList.toArray(new String[0]));
        DynamicObjectCollection dynamicObjects = ORM.create().toPlainDynamicObjectCollection(dataSet);
        for (DynamicObject obj : dynamicObjects) {
            String number = obj.getString("yem_number2");//编码
            String fullnumber = obj.getString("yem_fullnumber2");//全编码
            Set<Object> values = new HashSet<>();
            for (int i = 0; i < bills.length; i++) {
                DynamicObject dyObj = bills[i];
                if (fullnumber.contains(".")) {
                    String[] split = fullnumber.split("\\.");
                    for (String entity : split) {
                        if (dyObj != null && !number.equals(entity)) {
                            DynamicObjectCollection entry = dyObj.getDynamicObjectCollection(entity);
                            dyObj = entry.size() > 0 ? entry.get(0) : null;
                        }
                    }
                }
                Object value = dyObj == null ? null : dyObj.get(number);
                values.add(value);
                obj.set("yem_data" + i + 1, value);
            }
            if (values.size() > 1) {
                obj.set("yem_change", true);
            }
        }
        RowMeta rowMeta = dataSet.getRowMeta();
        int fieldCount = rowMeta.getFieldCount();
        Collection<Object[]> collection = new ArrayList<>();
        for (DynamicObject col : dynamicObjects) {
            Object[] obj = new Object[fieldCount];
            for (int j = 0; j < fieldCount; j++) {
                obj[j] = col.get(j);
            }
            collection.add(obj);
        }
        CollectionInput inputs = new CollectionInput(rowMeta, collection);
        dataSet = Algo.create(algoKey).createDataSet(inputs);
        if (onlyChanged) {
            dataSet = dataSet.where("yem_change = true");
        }
        return dataSet;
    }

    @Override
    public List<AbstractReportColumn> getColumns(List<AbstractReportColumn> columns) throws Throwable {
        String fdatagroup = "fdatagroup";
        ReportColumnGroup reportColumnGroup = createReportColumnGroup(fdatagroup, "字段值");
        for (Map.Entry<String, String> field : fieldMap.entrySet()) {
            reportColumnGroup.getChildren().add(createReportColumn(field.getKey(), field.getValue(), ReportColumn.TYPE_TEXT));
        }
        columns.add(reportColumnGroup);
        return super.getColumns(columns);
    }

    private ReportColumnGroup createReportColumnGroup(String fieldkey, String fieldname) {
        ReportColumnGroup rptColumnGroup = new ReportColumnGroup();
        rptColumnGroup.setFieldKey(fieldkey);
        rptColumnGroup.setCaption(new LocaleString(fieldname));
        return rptColumnGroup;
    }

    private ReportColumn createReportColumn(String fieldkey, String fieldname, String fieldtype) {
        ReportColumn rptColumn = new ReportColumn();
        rptColumn.setFieldKey(fieldkey);
        rptColumn.setCaption(new LocaleString(fieldname));
        rptColumn.setFieldType(fieldtype);
        return rptColumn;
    }

}