<template>
  {{ randomString1 }}
  <button @click="test2">查看pina数据</button>

  <!-- 数据文件存储 -->
  <el-button type="primary" @click="drawerVisible = true"> 数据文件222 </el-button>
  <mt-preview ref="MtPreviewRef" @on-event-call-back="onEventCallBack"></mt-preview>
  <!-- 数据模型 -->
  <el-drawer v-model="drawerVisible" :modal="false" title="数据模型文件" modal-penetrable>
    <el-radio-group class="vertical-radio-group" v-model="radio">
      {{ drawerVisible }}
      <el-radio v-for="item in fileNames" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-radio>
    </el-radio-group>
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="loadModel">加载模型11</el-button>
      </div>
    </template>
  </el-drawer>
</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 { genExportJson, useExportJsonToDoneJson } from '@/components/mt-edit/composables';
import { objectDeepClone, randomString } from '@/components/mt-edit/utils/index';
import { it } from 'element-plus/es/locales.mjs';

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

//文件读取
function fileRead() {
  fetch('/public/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 = {};

  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
  };

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

  MtPreviewRef.value?.setImportJson(endJson);
}

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

onMounted(() => {
  console.log('view挂载完毕');
  fileRead();
  initLoad();
  // let sessionJson = JSON.parse(sessionStorage.getItem('exportJson') as any);
  // if (sessionJson) {
  //   let endArr: Array[any] = [];
  //   if (route.query.screen && sessionJson.json) {
  //     console.log(
  //       '赛选：',
  //       route.query.screen,
  //       globalStore.group_ids,
  //       globalStore.group_ids.has(route.query.screen)
  //     );
  //     if (globalStore.group_ids.has(route.query.screen)) {
  //       let startArr = sessionJson.json;
  //       let arr = globalStore.group_ids.get(route.query.screen);
  //       console.log('arr', arr);
  //       arr.forEach((item: string) => {
  //         console.log('item', item);
  //         startArr.forEach((obj: any) => {
  //           console.log('obj', obj.id);
  //           if (obj.id === item) {
  //             console.log('匹配成功obj：', obj);
  //             endArr.push(obj);
  //           }
  //         });
  //       });
  //       sessionJson.json = endArr;
  //     }
  //   }
  //   console.log('endArr', endArr);
  //   MtPreviewRef.value?.setImportJson(sessionJson);
  // }
});

//加载数据模型
function loadModel() {
  console.log('选中：', radio.value, radio);
  if (!radio.value || radio.value == '-1') {
    ElMessage.warning('请先选择一个模型文件');
  }
  fileNames.forEach((item) => {
    if (item.id == radio.value) {
      fetch(`/public/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);
        });
    }
  });
}

function test2() {
  console.log('test3：', globalStore);
}
</script>

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