import { computed, Ref } from 'vue';
import { INode, IFile } from '@vtj/engine';
import { useClipboard } from '@vueuse/core';
import { ElMessage } from 'element-plus';

const fields: string[] = ['state', 'dataSources', 'methods', 'computed'];

export function useVariables(node: INode, type: Ref) {
  const { copy } = useClipboard({});
  const file = node.root as IFile;
  const list = computed(() => {
    if (fields.includes(type.value)) {
      const record = (file as any)[type.value] || {};
      return Object.keys(record).map((n) => {
        return {
          title: `this.${type.value}.${n}`
        };
      });
    }

    if ('context' === type.value) {
      const renderer = file.renderer._;
      const id = node.id;
      const record = renderer.data.context[id] || {};
      const result: string[] = [];
      for (let name in record) {
        result.push(name);
      }
      return result.map((n) => {
        return {
          title: `this.context['${id}'].${n}`
        };
      });
    }
    return [];
  });

  return {
    list,
    copy: (text: string) => {
      copy(text);
      ElMessage.success({
        message: '已经复制到粘贴板'
      });
    }
  };
}
