<template>
  <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">加载模型</el-button>
      </div>
    </template>
  </el-drawer>
</template>

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

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 { useRoute } from 'vue-router';
import { modelApi } from '@/utils/request';
const route = useRoute();

console.log('参数11：', 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('/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(() => {
  newLoadModel();
});

//获取组数据
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> = objectDeepClone(
      globalStore.group_ids.get(route.query.screen as string)
    );
    console.log('json1', json);

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

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

//加载数据模型
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);
        });
    }
  });
}
</script>

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