<template>
  <Panel :title="title" class="vtj-code-factory-form">
    <ElForm size="small" label-position="top">
      <ElFormItem label="名称">
        <ElSelect v-if="isLifeCycles" v-model="model.name">
          <ElOption v-for="item in lifeCycles" :key="item" :value="item">
            {{ item }}
          </ElOption>
        </ElSelect>
        <ElInput v-else v-model="model.name"></ElInput>
      </ElFormItem>
      <ElFormItem v-if="isWatch" label="deep">
        <ElSwitch v-model="model.deep"></ElSwitch>
      </ElFormItem>
      <ElFormItem v-if="isWatch" label="immediate">
        <ElSwitch v-model="model.immediate"></ElSwitch>
      </ElFormItem>
      <ElFormItem class="next-code-editor" :label="valueLabel"></ElFormItem>
    </ElForm>
    <CodeEditor
      border
      :height="`${isWatch ? 'calc(100% - 250px)' : 'calc(100% - 110px)'}`"
      :modelValue="model.code"
      @blur="handleBlur"
      :options="{ minimap: { enabled: false } }"></CodeEditor>
    <template #footer>
      <ElButton type="primary" @click="save">保存</ElButton>
    </template>
  </Panel>
</template>
<script lang="ts" setup>
import Panel from './Panel.vue';
import { LIFE_CYCLES_LIST as lifeCycles, CodeEditor } from '@vtj/engine';
import {
  ElForm,
  ElFormItem,
  ElInput,
  ElButton,
  ElMessage,
  ElSelect,
  ElOption,
  ElSwitch
} from 'element-plus';
import { computed, reactive } from 'vue';

export interface Props {
  name?: string;
  code?: string;
  field: string;
  label: string;
  dataType: 'JSExpression' | 'JSFunction';
  update: (name: string, value: any) => void;
  deep?: boolean;
  immediate?: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits(['save']);
const model = reactive({
  name: props.name,
  code: props.code,
  deep: props.deep,
  immediate: props.immediate
});

const isLifeCycles = computed(() => {
  return props.field === 'lifeCycles';
});

const isAdd = computed(() => {
  return !props.name;
});

const isWatch = computed(() => {
  return props.field === 'watch';
});

const title = computed(() => {
  return isAdd.value ? `新增${props.label}` : `编辑${props.label}`;
});

const valueLabel = computed(() => {
  return props.dataType === 'JSExpression' ? '值表达式' : '函数';
});

const handleBlur = (content: string) => {
  model.code = content;
};

const save = () => {
  if (!model.name) {
    ElMessage.warning('请输入名称');
    return;
  }
  props.update(model.name, {
    type: props.dataType,
    value: model.code,
    deep: model.deep,
    immediate: model.immediate
  });

  emit('save');
  ElMessage.success('保存成功');
};
</script>
