<template>
  <a-modal
    :title="props.title"
    width="80%"
    :visible="props.visible"
    :body-style="{ padding: '0 24px' }"
    :destroy-on-close="true"
    @cancel="fnCronModal(false)"
    @ok="fnCronModal(true)"
  >
    <div ref="mergeViewContainer" class="mergeViewContainer"></div>
  </a-modal>
</template>
<script lang="ts" setup>
import { javascript } from '@codemirror/lang-javascript';
import { oneDark } from '@codemirror/theme-one-dark';
import { MergeView } from '@codemirror/merge';
import { EditorView, basicSetup } from 'codemirror';
import { EditorState } from '@codemirror/state';

import { watch, ref } from 'vue';
import { nextTick } from 'vue';

const emit = defineEmits(['cancel', 'ok', 'update:visible']);
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
  },
  title: {
    type: String,
    default: '内容比较',
  },
  newArea: {
    type: String,
    default: '当前内容',
  },
  oldArea: {
    type: String,
    default: '原始内容',
  },
  height: {
    type: String,
    default: '400px !important',
  },
  /**是否禁止输入 */
  disabled: {
    type: Boolean,
    default: true,
  },
});

const mergeViewContainer = ref();

/**监听是否显示，初始cron属性 */
watch(
  () => props.visible,
  val => {
    if (val) {
      // 开启时等待dom完成

      nextTick(() => {
        // 设置高度
        mergeViewContainer.value.style.height = props.height;
        // 实例到dom
        new MergeView({
          a: {
            doc: props.oldArea,
            extensions: [
              javascript(),
              oneDark,
              basicSetup,
              EditorView.editable.of(false),
              EditorState.readOnly.of(true),
            ],
          },
          b: {
            doc: props.newArea,
            extensions: [
              javascript(),
              oneDark,
              basicSetup,
              EditorView.editable.of(!props.disabled),
              EditorState.readOnly.of(props.disabled),
            ],
          },
          parent: mergeViewContainer.value,
        });
      });
    }
  }
);

/**
 * 窗口事件
 * @param val modal触发事件
 */
function fnCronModal(val: boolean) {
  emit('update:visible', false);
  if (val) {
    emit('ok', true);
  } else {
    emit('cancel');
  }
}
</script>

<style lang="less" scoped>
.mergeViewContainer {
  height: 400px;
  overflow-y: scroll;
  overflow-x: hidden;
  color: #abb2bf;
  background-color: #282c34;
}
</style>
