<template>
  <div>
    <BasicDrawer
      v-bind="$attrs"
      :title="getTitle"
      @register="register"
      width="500px"
      @ok="handleSubmit"
      showFooter
    >
      <BasicForm @register="registerForm">
        <template #function>
          <Card title="转换函数" :bodyStyle="{ padding: 0, height: '280px' }">
            <template #extra>
              <Tag color="blue">Transform Function</Tag>
              <a-button @click="handleFormat" size="small">格式化</a-button>
            </template>
            <div class="ml-8">function Transform(msg, metadata) {</div>
            <div ref="aceRef" class="overflow-hidden"></div>
            <div class="ml-7">}</div>
          </Card>
          <a-button type="primary" class="mt-4" @click="testTransformFunc">测试转换功能</a-button>
        </template>
      </BasicForm>
    </BasicDrawer>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { useDrawerInner, BasicDrawer } from '/@/components/Drawer/index';
  import { useForm, BasicForm } from '/@/components/Form/index';
  import { formSchema } from '../config/config.data';
  import { Card, Tag } from 'ant-design-vue';
  // import { createOrEditTransformScriptApi } from '/@/api/device/TransformScriptApi';
  import { useMessage } from '/@/hooks/web/useMessage';
  import ace from 'ace-builds';
  import 'ace-builds/src-noconflict/theme-chrome'; // 默认设置的主题
  import 'ace-builds/src-noconflict/mode-javascript'; // 默认设置的语言模式
  import { beautify } from 'ace-builds/src-noconflict/ext-beautify.js';

  const emit = defineEmits(['register', 'isStatus', 'success']);
  const isUpdate: any = ref(false);
  const isView = ref(true);
  const aceEditor = ref();
  const aceRef = ref();
  const getTitle = computed(() => (isUpdate.value ? '编辑转换脚本' : '新增转换脚本'));
  const editId = ref('');
  const [register, { setDrawerProps, closeDrawer }] = useDrawerInner((data) => {
    resetFields();
    setDrawerProps({ confirmLoading: false });
    isUpdate.value = data.isUpdate;
    initEditor(data.record?.configuration.jsScript);
    switch (isUpdate.value) {
      case 'view':
        isView.value = false;
        setDrawerProps({
          showFooter: unref(isView),
          title: '查看转换脚本',
          loading: false,
        });
        editId.value = data.record.id;
        setFieldsValue(data.record);
        break;
      case true:
        isView.value = true;
        setDrawerProps({
          showFooter: unref(isView),
          title: '编辑转换脚本',
          loading: false,
        });
        editId.value = data.record.id;
        setFieldsValue(data.record);
        break;
      case false:
        isView.value = true;
        setDrawerProps({
          showFooter: unref(isView),
          title: '新增转换脚本',
          loading: false,
        });
        break;
    }
  });
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    showActionButtonGroup: false,
    colProps: { span: 24 },
    schemas: formSchema,
  });

  // 初始化编辑器
  const initEditor = (jsScript?: string) => {
    aceEditor.value = ace.edit(aceRef.value, {
      maxLines: 12, // 最大行数，超过会自动出现滚动条
      minLines: 12, // 最小行数，还未到最大行数时，编辑器会自动伸缩大小
      fontSize: 14, // 编辑器内字体大小
      theme: 'ace/theme/chrome', // 默认设置的主题
      mode: 'ace/mode/javascript', // 默认设置的语言模式
      tabSize: 2, // 制表符设置为 4 个空格大小
    });

    aceEditor.value.setOptions({
      enableBasicAutocompletion: true,
      enableLiveAutocompletion: true,
    });
    aceEditor.value.setValue(jsScript ?? 'return {msg: msg, metadata: metadata};');
    beautify(aceEditor.value.session);
  };

  const testTransformFunc = () => {
    closeDrawer();
    const jsCode = aceEditor.value.getValue();
    emit('isStatus', { status: 1, jsCode });
  };
  const handleSubmit = async () => {
    const editIdPost = isUpdate.value ? { id: editId.value } : {};
    try {
      setDrawerProps({ confirmLoading: true });
      const fieldsValue = await validate();
      if (!fieldsValue) return;
      await createOrEditTransformScriptApi({
        configuration: {
          jsScript: aceEditor.value.getValue(),
        },
        type: 'org.thingsboard.rule.engine.transform.TbTransformMsgNode',
        ...fieldsValue,
        ...editIdPost,
      });
      closeDrawer();
      emit('success');
      const { createMessage } = useMessage();
      createMessage.success('保存成功');
    } catch (e) {
    } finally {
      setTimeout(() => {
        setDrawerProps({ confirmLoading: false });
      }, 300);
    }
  };
  const handleFormat = () => {
    beautify(aceEditor.value.session);
  };
  defineExpose({ aceEditor });
</script>
