<script setup lang="ts">
import type { IVFormComponent } from '../../types';

import { unref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import InputCode from '#/components/form/components/input-code/input-code-modal-ignore.vue';
import { Icon } from '#/components/icon';

import { useFormDesignState } from '../../hooks/useFormDesignState';

const emit = defineEmits(['save']);

const [InputCodeModal, inputCodeApi] = useVbenModal({
  connectedComponent: InputCode,
});

const { formConfig, formDesignMethods } = useFormDesignState();

const handleClear = () => {
  formConfig.value.schemas = [];
  formDesignMethods.setSelectSchema({ component: '' } as IVFormComponent);
};

const handleSuccess = (scriptCode: any) => {
  formConfig.value.config = { ...scriptCode.config };
  formConfig.value.schemas = [...(scriptCode.schemas || [])];
  formDesignMethods.setSelectSchema({ component: '' } as IVFormComponent);
};

const handleImport = () => {
  inputCodeApi
    .setData({
      baseData: {
        scriptCode: {
          config: {
            wrapperClass: 'grid-cols-1',
            showDefaultActions: false,
            commonConfig: {
              labelWidth: 100,
            },
          },
          schemas: [],
        },
        name: '导入JSON',
        language: 'json',
      },
    })
    .open();
};

const handleExport = () => {
  const scriptCode = cloneDeep(unref(formConfig));
  delete scriptCode.selectSchema;
  inputCodeApi
    .setData({
      baseData: {
        scriptCode,
        name: '导出JSON',
        language: 'json',
      },
      isPreview: true,
    })
    .open();
};

const handleSave = () => {
  emit('save');
};
</script>
<template>
  <div class="flex items-center justify-between border-b px-4">
    <InputCodeModal :close-on-click-modal="false" @success="handleSuccess" />
    <h3 class="text-lg">设计区域</h3>
    <div class="flex flex-wrap gap-3">
      <Icon
        icon="tabler:package-import"
        size="24"
        class="cursor-pointer"
        @click="handleImport"
      />
      <Icon
        icon="tabler:package-export"
        size="24"
        class="cursor-pointer"
        @click="handleExport"
      />
      <Icon
        icon="carbon:clean"
        size="24"
        class="cursor-pointer"
        @click="handleClear"
      />
      <Icon icon="hugeicons:view" size="24" class="cursor-pointer" />
      <Icon
        icon="fluent:save-multiple-24-filled"
        size="24"
        class="cursor-pointer"
        @click="handleSave"
      />
    </div>
  </div>
</template>
