<template>
  <div class="vtj-code-factory-panel">
    <CodeFactoryList
      :file="props.file"
      :field="props.field"
      :list="props.list"
      :label="props.label"
      removable
      addable
      @add="handleAdd"
      @edit="handleEdit"
      @remove="handleRemove">
    </CodeFactoryList>
    <CodeFactoryForm
      v-if="formProps"
      :field="props.field"
      :key="`${props.file.id}-${props.field}-${formProps.name}`"
      :name="formProps.name"
      :code="formProps.code"
      :label="props.label"
      :data-type="props.dataType"
      :deep="formProps.deep"
      :immediate="formProps.immediate"
      :update="props.update"></CodeFactoryForm>
  </div>
</template>
<script lang="ts" setup>
import CodeFactoryList, { ListItem } from './CodeFactoryList.vue';
import CodeFactoryForm from './CodeFactoryForm.vue';
import { IFile } from '@vtj/engine';
import { ref } from 'vue';

export type Field = 'state' | 'lifeCycles' | 'methods' | 'computed' | 'watch';
export interface Props {
  file: IFile;
  field: Field;
  label: string;
  dataType: 'JSExpression' | 'JSFunction';
  list: ListItem[];
  update: (name: string, value: any) => void;
  remove: (name: string) => void;
}

const props = defineProps<Props>();

const getEmptyCode = () => {
  return props.dataType === 'JSExpression' ? '' : '(function () {\r\n  \r\n});';
};

const formProps = ref({
  name: undefined,
  code: getEmptyCode(),
  deep: false,
  immediate: false
});

const handleAdd = (field: Field) => {
  formProps.value = {
    name: undefined,
    code: getEmptyCode(),
    deep: false,
    immediate: false
  };
};

const handleEdit = (item: any) => {
  if (props.field === 'watch') {
    formProps.value = {
      name: item.name,
      code: item.value.handler.value,
      deep: item.value.deep,
      immediate: item.value.immediate
    };
  } else {
    formProps.value = {
      name: item.name,
      code: item.value.value,
      deep: false,
      immediate: false
    };
  }
};
// const handleSave = (name: string, code: string) => {};

const handleRemove = (name: string) => {
  if (name === formProps.value.name) {
    formProps.value = {
      name: undefined,
      code: getEmptyCode(),
      deep: false,
      immediate: false
    };
  }
  props.remove(name);
};
</script>
