<template>
  <Dialog
    class="vtj-binder vtj-event-binder"
    :body-padding="false"
    title="事件绑定"
    :subtitle="subtitle"
    top="50%s"
    width="70%"
    height="80%">
    <div class="vtj-binder__body">
      <ElTabs v-model="currentTab" type="border-card" tab-position="left">
        <ElTabPane name="context" label="上下文变量"> </ElTabPane>
        <ElTabPane name="state" label="状态数据"></ElTabPane>
        <ElTabPane name="computed" label="计算属性"></ElTabPane>
        <ElTabPane name="methods" label="自定义方法"></ElTabPane>
        <ElTabPane name="dataSources" label="数据源"></ElTabPane>
        <ElTabPane name="utils" label="全局变量"></ElTabPane>
      </ElTabs>
      <div class="vtj-binder__panel">
        <Panel class="vtj-binder__list" title="可选项">
          <DataItem
            v-for="n in list"
            clickable
            :title="n.title"
            @click="onPicker(n.title)">
            <template #action>
              <i
                class="vtj-icon-copy"
                title="复制"
                @click.stop="copy(n.title)"></i>
            </template>
          </DataItem>
          <ElEmpty v-if="list.length === 0" :image-size="50"></ElEmpty>
        </Panel>
        <Panel class="vtj-binder__binding" title="绑定内容">
          <ElForm label-position="top">
            <!-- <ElFormItem label="参数"></ElFormItem> -->
            <ElFormItem label="修饰符">
              <ElCheckboxGroup v-model="modifiers">
                <ElCheckbox
                  v-for="item in EVENT_MODIFIERS"
                  :key="item"
                  :label="item"></ElCheckbox>
              </ElCheckboxGroup>
            </ElFormItem>
            <ElFormItem label="处理函数" class="next-code-editor"></ElFormItem>
          </ElForm>
          <CodeEditor
            ref="codeEditor"
            height="350px"
            :model-value="codeContent"></CodeEditor>
          <template #footer>
            <div class="vtj-binder__footer">
              <ElButton
                size="default"
                type="warning"
                :disabled="!hasContent"
                @click="onRemoveBinding">
                移除绑定
              </ElButton>
              <span>
                <ElButton size="default" @click="onCancel">取消</ElButton>
                <ElButton size="default" type="primary" @click="onBinding">
                  确定
                </ElButton>
              </span>
            </div>
          </template>
        </Panel>
      </div>
    </div>
  </Dialog>
</template>
<script lang="ts" setup>
import { ref, computed } from 'vue';
import {
  Dialog,
  Panel,
  DataItem,
  INode,
  EVENT_MODIFIERS,
  CodeEditor
} from '@vtj/engine';
import {
  ElTabs,
  ElTabPane,
  ElButton,
  ElMessage,
  ElEmpty,
  ElForm,
  ElFormItem,
  ElCheckboxGroup,
  ElCheckbox
} from 'element-plus';
import useCore from '../hooks/useCore';
import { useVariables } from '../hooks/useVariables';

export interface Props {
  node: INode;
  eventItem: any;
}

const { engine } = useCore();

const props = withDefaults(defineProps<Props>(), {});
const emit = defineEmits(['submit', 'cancel', 'remove']);
const subtitle = ref(props.node.id);
const codeEditor = ref();
const eventItem = ref(props.eventItem);
const modifiers = ref(eventItem.value.event?.modifiers || []);

const hasContent = computed(() => {
  return !!eventItem.value.event?.handler.value;
});
const currentTab = ref('context');
const { list, copy } = useVariables(props.node, currentTab);

const eventAssetsParams = computed(() => {
  const nodeName = props.node.name;
  const desc = engine.assets.componentMap[nodeName];
  if (desc && desc.events) {
    // events 配置配型是  string | ComponentEvent
    const item = desc.events.find(
      (n: any) =>
        n === props.eventItem?.name || n.name === props.eventItem?.name
    );
    if (item && (item as any).params) {
      return (item as any).params;
    }
  }
  return [];
});

const codeContent = computed(() => {
  if (hasContent.value) {
    return eventItem.value.event.handler.value;
  } else {
    return `(function(${eventAssetsParams.value.join(', ')}){\r\n\r\n})`;
  }
});

const onBinding = () => {
  const editor = codeEditor.value?.getEditor();
  if (editor) {
    const content = editor.getValue();
    if (!content) {
      ElMessage.warning({
        message: '请输入变量内容'
      });
      return;
    }

    const item = {
      name: props.eventItem.name,
      event: {
        handler: {
          type: 'JSFunction',
          value: content
        },
        modifiers: modifiers.value,
        params: []
      }
    };

    emit('submit', item);
  }
};

const onCancel = () => {
  emit('cancel');
};

const onRemoveBinding = () => {
  emit('remove', props.eventItem.name);
};

const onPicker = (text: string) => {
  const editor = codeEditor.value?.getEditor();
  if (editor) {
    const content = editor.getValue();
    if (!eventItem.value.event) {
      eventItem.value.event = {
        handler: {
          type: 'JSFunction',
          value: ''
        }
      };
    }
    eventItem.value.event.handler.value = content ? content + ';' + text : text;
  }
};
</script>
