<template>
  <div class="vtj-code-factory-panel">
    <CodeFactoryList
      :file="props.file"
      label="数据源"
      field="dataSources"
      :list="list"
      addable
      removable
      @edit="onEdit"
      @add="onAdd"
      @remove="onRemove"></CodeFactoryList>
    <Panel
      :title="`${isEdit ? '编辑' : '新增'}数据源`"
      class="vtj-code-factory-form">
      <ElForm
        ref="form"
        label-position="top"
        size="small"
        :model="formModel"
        :rules="rules">
        <ElFormItem label="类型" prop="type">
          <ElRadioGroup
            v-model="formModel.type"
            @change="onTypeChange"
            :disabled="isEdit">
            <ElRadio label="api">API</ElRadio>
            <ElRadio label="meta">数据配置</ElRadio>
            <ElRadio label="cube" disabled>数据魔方</ElRadio>
          </ElRadioGroup>
        </ElFormItem>
        <ElFormItem label="数据源标识" prop="id">
          <ElSelect v-model="formModel.id" filterable :disabled="isEdit">
            <ElOption v-for="item in options" :value="item.id">
              {{ item.id }}
            </ElOption>
          </ElSelect>
        </ElFormItem>
        <ElFormItem class="next-code-editor" label="数据转换函数"> </ElFormItem>
      </ElForm>
      <CodeEditor
        ref="codeEditor"
        :model-value="formModel.transform"></CodeEditor>
      <template #footer>
        <ElButton type="default" size="default">测试</ElButton>
        <ElButton type="primary" size="default" @click="onSubmit"
          >保存</ElButton
        >
      </template>
    </Panel>
  </div>
</template>
<script lang="ts" setup>
import CodeFactoryList, { ListItem } from './CodeFactoryList.vue';
import {
  ElForm,
  ElFormItem,
  ElRadioGroup,
  ElRadio,
  ElSelect,
  ElOption,
  ElButton,
  ElMessage
} from 'element-plus';
import {
  IFile,
  Panel,
  CodeEditor,
  DataSourceType,
  useCore,
  IFileDataSource
} from '@vtj/engine';
import { ref, computed } from 'vue';

export interface Props {
  file: IFile;
}

interface FormModel {
  type: DataSourceType;
  id?: string;
  transform?: string;
}

const { project } = useCore();

const props = defineProps<Props>();

const form = ref();
const codeEditor = ref();
const formModel = ref<FormModel>({
  type: 'api',
  transform: `(function (res) {
    return res;
})`
});
const isEdit = ref(false);

const options = computed(() => {
  const dataSources = project.dataSources.find(
    (n) => n.type === formModel.value.type
  );
  return dataSources?.items || [];
});

const list = computed(() => {
  return Object.values(props.file.dataSources).map((n) => {
    return {
      name: n.id,
      value: n
    };
  });
});

const rules = {
  id: [{ required: true, message: '请选择数据源标识', trigger: 'blur' }]
};

const save = () => {
  const { type, id = '' } = formModel.value;
  const editor = codeEditor.value.getEditor();
  const content = editor.getValue();
  const source = options.value.find((n) => n.id === id);
  const item: IFileDataSource = {
    type,
    id,
    transform: {
      type: 'JSFunction',
      value: content
    },
    params: source?.params || {}
  };
  props.file.setDataSource(id, item);
  ElMessage.success({
    message: '保存成功！'
  });
};

const onSubmit = () => {
  form.value.validate((vaild: boolean) => {
    if (vaild) {
      save();
    }
  });
};

const onAdd = () => {
  isEdit.value = false;
  formModel.value = {
    type: 'api',
    id: '',
    transform: `(function (res) {
    return res;
})`
  };
};

const onEdit = (item: ListItem) => {
  isEdit.value = true;
  formModel.value = {
    ...item.value,
    transform: item.value.transform?.value
  };
};

const onRemove = (name: string) => {
  props.file.removeDataSource(name);
};

const onTypeChange = () => {
  formModel.value.id = '';
};
</script>
