<template>
  <mt-preview ref="MtPreviewRef" @on-event-call-back="onEventCallBack"></mt-preview>
</template>

<script setup lang="ts">
import { MtPreview } from '@/export';
import { onMounted, ref, reactive, onUnmounted } from 'vue';
import { ElMessage } from 'element-plus';
import { globalStore } from '@/components/mt-edit/store/global';
import { useExportJsonToDoneJson } from '@/components/mt-edit/composables';
import { useRoute } from 'vue-router';
import { modelApi } from '@/utils/request';
const route = useRoute();

const MtPreviewRef = ref<InstanceType<typeof MtPreview>>();
const onEventCallBack = (type: string, item_id: string) => {
  console.log(type, item_id);

  if (type == 'test-dialog') {
    ElMessage.success(`获取到了id:${item_id}`);
  }
};

//属性抽取
function extractValFromProps(props: any) {
  const result = {};

  for (const key in props) {
    if (props[key] && typeof props[key] === 'object' && 'val' in props[key]) {
      result[key] = props[key].val;
    }
  }

  return result;
}

onUnmounted(() => {
  console.log('view卸载完毕');
});

onMounted(() => {
  newLoadModel();
});

async function newLoadModel() {
  let endJson = {
    menuType: route.query.screen
  };

  try {
    const response = await modelApi.model_getModelData_post(endJson);

    if (response.code == 200) {
      const result = await response.data;
      const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(result);

      // 对 importDoneJson 集合中每个元素的 props 属性使用 reactive 包装
      const processedImportDoneJson = importDoneJson.map((item) => {
        if (item.props) {
          return {
            ...item,
            props: reactive(item.props || {})
          };
        }
        return {
          ...item,
          props: reactive(item.props || {})
        };
      });

      console.log('processedImportDoneJson:', processedImportDoneJson);
      MtPreviewRef.value?.setNewImportJson({ canvasCfg, gridCfg, json: processedImportDoneJson });
      if (globalStore.group_ids.has(route.query.screen as string)) {
        globalStore.group_ids.delete(route.query.screen as string);
      }
      globalStore.group_ids.set(route.query.screen as string, processedImportDoneJson);

      ElMessage.success('数据模型加载成功');
    } else {
      ElMessage.error(`数据模型加载失败: ${response.code} - ${response.message}`);
    }
  } catch (error) {
    console.error('请求错误：', error);
    ElMessage.error('网络请求失败');
  }
}
</script>

<style scoped>
.vertical-radio-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: flex-start;
}
</style>
