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

<script setup lang="ts">
// 定义组件名称用于 keep-alive
defineOptions({
  name: 'PreviewIndex'
});

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 { type IDoneJson } from '@/components/mt-edit/store/types';
import { genExportJson, useExportJsonToDoneJson } from '@/components/mt-edit/composables';
import { objectDeepClone, randomString } from '@/components/mt-edit/utils/index';
import { useRoute } from 'vue-router';
import { modelApi } from '@/utils/request';
const route = useRoute();

console.log('参数：', route.query.screen);

let drawerVisible = ref(false);
let fileNames: Array<{ id: string; name: string }> = reactive([]);
let radio = ref('-1');
// 用于调试：跟踪组件是否被重新创建
let randomString1 = randomString();

//文件读取
function fileRead() {
  fetch('/dataModes/index.json')
    .then((response) => response.json())
    .then((data) => {
      fileNames = Object.assign(data);
    })
    .catch((error) => {
      console.error('获取JSON文件错误：', error);
    });
}

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: Record<string, any> = {};
  for (const key in props) {
    if (props[key] && typeof props[key] === 'object' && 'val' in props[key]) {
      result[key] = props[key].val;
    }
  }

  return result;
}

function initLoad() {
  let canvasCfg = globalStore.canvasCfg;
  let gridCfg = globalStore.gridCfg;
  // let json = globalStore.done_json;
  let json: Array<any> = objectDeepClone(globalStore.done_json);
  globalStore.done_json.forEach((item) => {
    const extractedProps = extractValFromProps(item.props);
    json.forEach((obj) => {
      if (obj.id === item.id) {
        obj.props = extractedProps;
      }
    });
  });

  let endJson = {
    canvasCfg: canvasCfg,
    gridCfg: gridCfg,
    json: json
  };
  MtPreviewRef.value?.setImportJson(endJson);
}

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

//获取组数据
// function loadModeData() {
//   console.log('文件', route.query.screen);
//   console.log('xx:', globalStore.group_ids.get(route.query.screen as string));

//   if (globalStore.group_ids.get(route.query.screen as string)) {
//     let json: Array<IDoneJson> = globalStore.group_ids.get(route.query.screen as string);
//     let endJson = {
//       canvasCfg: globalStore.canvasCfg,
//       gridCfg: globalStore.gridCfg,
//       json: json
//     };

//     console.log('endJson：', endJson);

//     MtPreviewRef.value?.setImportJson(endJson);
//   }
// }

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.map((item) => item.id)
      );

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

onMounted(() => {
  console.log('view挂载完毕');
  newLoadModel();
});

//加载数据模型
function loadModel() {
  console.log('选中：', radio.value, radio);
  if (!radio.value || radio.value == '-1') {
    ElMessage.warning('请先选择一个模型文件');
  }
  fileNames.forEach((item) => {
    if (item.id == radio.value) {
      fetch(`/dataModes/${item.name}`)
        .then((response) => response.json())
        .then((data) => {
          console.log('文件内容：', data);
          const { canvasCfg, gridCfg, importDoneJson } = useExportJsonToDoneJson(data);
          globalStore.canvasCfg = canvasCfg;
          globalStore.gridCfg = gridCfg;
          globalStore.setGlobalStoreDoneJson(importDoneJson);
          initLoad();
        })
        .catch((error) => {
          ElMessage.error('获取文件错误：', error);
        });
    }
  });
}
</script>

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