<template>
  <div class="container" v-loading="loading">
    <div class="header-container" v-if="fileTitle" v-show="text">
      {{ fileTitle }}
    </div>
    <div :id="'codeEditBox' + idIndex" class="codeEditBox" v-show="text"></div>
    <div class="footer-container" v-if="!readonly" v-show="text">
      <el-button type="primary" @click="saveFile">保存</el-button>
    </div>
    <div v-show="!text" class="w100p flex-center">
      <!-- <img class="mt100 w100p h150" src="@/assets/img/common/common-no-data.svg" alt="" /> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, toRaw, watchEffect, onBeforeUnmount } from 'vue';
import * as monaco from 'monaco-editor';
import { ElMessage } from 'element-plus';
import { dataDownloadFileApi, getFileBaseInfoApi } from '@/api/data/data';
import { upload } from '@/api/request';

const env = import.meta.env;
const PREFIX = env.VITE_API_PREFIX_DATA;

const props = withDefaults(
  defineProps<{
    idIndex?: any;
    readonly?: boolean;
    autoFormat?: boolean;
    fileId: string;
  }>(),
  {
    readonly: false,
    idIndex: 1,
    autoFormat: false,
    fileId: '',
  }
);

const text = ref<string>('');
const emits = defineEmits(['saveHandle']);

const editor = ref();
const isChange = ref<boolean>(false);
// const FILE_TYPE: any = {
//   py: 'python',
//   tcl: 'tcl',
//   json: 'json',
//   xml: 'xml',
// };
const initEditor = () => {
  // 初始化编辑器，确保dom已经渲染

  editor.value = monaco.editor.create(
    document.getElementById('codeEditBox' + props.idIndex) as any,
    {
      value: '', // 编辑器初始显示文字
      // 语言支持自行查阅demo
      language: '',
      theme: 'vs-dark', // 官方自带三种主题vs, hc-black, or vs-dark
      selectOnLineNumbers: true, // 显示行号
      roundedSelection: false,
      cursorStyle: 'line', // 光标样式
      automaticLayout: true, // 自动布局
      glyphMargin: true, // 字形边缘
      useTabStops: false,
      fontSize: 14, // 字体大小
      quickSuggestionsDelay: 100, // 代码提示延时
      autoIndent: 'full', // 自动布局
    }
  );
  // // 监听值的变化
  editor.value.onDidChangeModelContent(() => {
    // editor.value.getAction('editor.action.formatDocument').run();
    // 拿到变化后的值
    const currentValue = toRaw(editor.value).getValue();
    isChange.value = currentValue !== text.value;
  });
};
// const fileParentPath = ref<string>('');
// 保存编辑
const saveFile = async () => {
  if (isChange.value) {
    const currentValue = toRaw(editor.value).getValue();

    const form = new FormData();
    // form.append('fileType', String(FILE_TYPE.FLOW_PYTHON));
    form.append('scriptFileId ', props.fileId);
    form.append('fileName ', fileTitle.value);
    form.append('updateFile   ', new Blob([currentValue], { type: 'text/txt' }));
    const res: any = await upload(`${PREFIX}data/updateScriptFile`, form);

    // const res = await fragmentUpload(
    //   false,
    //   new Blob([currentValue], { type: 'text/txt' }),
    //   fileParentPath.value,
    //   fileTitle.value
    // );
    if (res.code === 200) {
      ElMessage.success('修改成功！');
      text.value = toRaw(editor.value).getValue();
      isChange.value = false;
    } else {
      ElMessage.error(res as any);
    }
    emits('saveHandle');
  } else {
    ElMessage('暂无内容更新');
  }
};
const getValue = () => {
  return toRaw(editor.value).getValue();
};
const loading = ref<boolean>(false);
const fileTitle = ref<string>('');
// const clearEditor = () => {
//   text.value = '';
//   fileTitle.value = '';
//   toRaw(editor.value).setValue(text.value);
// };
const getFile = async () => {
  loading.value = true;
  const baseRes: any = await getFileBaseInfoApi({ fileId: props.fileId });
  if (baseRes.code === 200) {
    fileTitle.value = baseRes.data.originalName;
  }
  const res: any = await dataDownloadFileApi({ fileId: props.fileId });
  if (res) {
    // 设置语言
    // let fileSuffix = '';
    // if (fileName.lastIndexOf('.') != -1) {
    //   fileSuffix = fileName.substring(fileName.lastIndexOf('.')).slice(1);
    // }
    // const language = fileSuffix && (window as any).FILE_TYPE_MAP[fileSuffix] ? FILE_TYPE[fileSuffix] : '';
    // 获取当前的文本模型
    const model = toRaw(editor.value).getModel();
    //  setModelLanguage 方法来设置新的语言
    if (model) {
      monaco.editor.setModelLanguage(model, 'python');
    }
    // 填入内容时设置只读为false
    toRaw(editor.value).updateOptions({ readonly: true });
    // 设置内容
    text.value = JSON.stringify(res) as string;
    toRaw(editor.value).setValue(text.value);
    // 设置光标位置为第一行第一列
    toRaw(editor.value).setPosition({ lineNumber: 1, column: 1 });
    // 确保滚动视图使光标可见
    toRaw(editor.value).revealLine(1);
    // 格式化代码
    // if (props.autoFormat) {
    //   toRaw(editor.value)
    //     .getAction('editor.action.formatDocument')
    //     .run()
    //     .then(() => {
    //       // 格式化完成后，设置编辑器是否只读只读
    //       props.readonly && toRaw(editor.value).updateOptions({ readonly: props.readonly });
    //     });
    // } else {
    if (props.readonly) {
      toRaw(editor.value).updateOptions({ readonly: props.readonly });
    }
    // }
  }
  loading.value = false;
};

watchEffect(() => {
  if (toRaw(editor.value)) {
    getFile();
  }
});
const keyboardSave = (event: any) => {
  if (event.ctrlKey && event.key === 's') {
    event.preventDefault();
    // 在这里执行你想要的操作，例如显示一个提示或者进行其他处理
    saveFile();
  }
};
onMounted(() => {
  initEditor();
  window.addEventListener('keydown', keyboardSave);
});
onBeforeUnmount(() => {
  window.removeEventListener('keydown', keyboardSave);
});
defineExpose({
  editor,
  isChange,
  getValue,
});
</script>

<style lang="scss" scoped src="./index.scss"></style>
