<template>
  <div class="designer main-content-padding">
    <h-icon
      name="hoteam-back"
      :size="40"
      title="返回"
      class="hoteam-back"
      color="#1890ff"
      @click="closePage"
    >
      返回
    </h-icon>
    <div class="designer__form">
      <custom-form
        ref="formbuilderDom"
        v-bind="formProps"
        @onLoad="onLoad"
        :designSave="designSave"
      ></custom-form>
    </div>
    <!-- <div class="designer__footer">
      <h-button class="designer__footer--btn" @click="save">
        {{ t('FormDesign.common.save') }}
      </h-button>
    </div> -->
    <form-builder-save
      ref="formBuilderSaveRef"
      @FormBuilderSave="formBuilderSave"
    ></form-builder-save>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, nextTick } from 'vue';
import { CustomForm, FormBuilderSave } from '@/views/FormBuilder/components/custom-form';
import type { ICustomFormProps } from '@/views/FormBuilder/components/custom-form';
import * as useSave from './use/useSave';
import { useGetFormDesignData } from './use/useToolbar';
import { useRouter } from 'vue-router';
import { useI18n } from '@crami/locale';
// import { useMultiTab } from '@/components/multi-tab';
export default defineComponent({
  name: 'designer',
  components: { CustomForm, FormBuilderSave },
  setup() {
    const { t } = useI18n();
    const formbuilderDom = ref(null);
    const formReady = ref(false);
    const state = reactive({
      templateId: '',
      formData: null,
      saveVersionInfo: null,
      modelCode: '',
    });

    const formProps = reactive<ICustomFormProps>({
      url: {
        images: '/form/build/images/',
        imageupload: 'image-upload-in-config-url',
      },
      pattern: 'design', //'design','applying','view'
      toolbox: {},
      control: {},
      menu: {
        controls: {
          version: {
            options: {
              value: {
                text: '1',
                value: '1',
              },
              items: [
                {
                  text: '1',
                  value: '1',
                },
                {
                  text: '2',
                  value: '2',
                },
                {
                  text: '3',
                  value: '3',
                },
              ],
            },
            // value 改变时触发
            update() {
              const value: string = this.getValue();
              console.log(value);
              useGetFormDesignData(router.currentRoute.value.query.templateId as string, value)
                .then(data => {
                  if (formProps.menu.controls.version.options) {
                    formProps.menu.controls.version.options.items = data.versionList;
                    formProps.menu.controls.version.options.value = {
                      text: data.version,
                      value: data.versionId,
                    };
                    versionId = data.versionId;
                  }
                  layoutData = data.layoutData;
                  toolboxDatasource = data.templateData;
                  dataInit = true;
                  if (formIndexLoaded) {
                    initCustomForm();
                  }
                })
                .catch(e => {
                  console.log(e);
                });
            },
          },
        },
      },
      // data: data, // applying模式需要有值
      height: '100%',
    });
    let designUtils: any = null;

    // 获取设计数据
    const getData = () => {
      const data = formbuilderDom.value?.getData();
      console.log(data);
    };
    let formIndexLoaded = false;
    let dataInit = false;
    let toolboxDatasource: any = null;
    let layoutData = '';
    let versionId = null;
    const formBuilderSaveRef = ref();
    const initCustomForm = () => {
      // 设置toolbox
      const { toolbox, control } = designUtils.generateToolbox(toolboxDatasource, {
        basicText: t('FormDesign.common.basicText'),
      });
      formProps.data = designUtils.formatLoadData(layoutData);
      formProps.toolbox = { ...toolbox };
      formProps.control = {
        order: [...control.order],
      };
      nextTick(() => {
        formbuilderDom.value?.init();
      });
    };

    const onLoad = () => {
      // custom-form组件已经初始化完成
      formIndexLoaded = true;
      if (!designUtils) {
        designUtils = formbuilderDom.value?.getDesignUtils();
      }
      if (dataInit) {
        initCustomForm();
      }
    };
    const formBuilderSave = params => {
      console.log('data :>> ', params);
      if (params.primaryVersion && params.mode) {
        const saveVersionInfo = {
          versionId: versionId,
          mode: params.mode,
          isPrimary: params.primaryVersion,
        };
        const data = formbuilderDom.value?.getData();
        state.formData = designUtils.formatSaveData(data);
        state.saveVersionInfo = saveVersionInfo;
        useSave.saveCurrentVersion(state).then(res => {
          console.log(res);
          if (res == 200) {
            closePage();
          }
        });
      }
    };
    const designSave = () => {
      // 判断是否传versionId，默认新建应该为null，其他情况会有versionId
      if (versionId) {
        //如果存在则在保存时弹出弹框
        formBuilderSaveRef.value.show();
      } else {
        // 如果不存在则不弹框，默认修订1，默认不是主版本0
        const saveVersionInfo = {
          versionId: versionId,
          mode: '1',
          isPrimary: '0',
        };
        const data = formbuilderDom.value?.getData();
        state.formData = designUtils.formatSaveData(data);
        state.saveVersionInfo = saveVersionInfo;
        useSave.saveCurrentVersion(state).then(res => {
          console.log(res);
          if (res == 200) {
            closePage();
          }
        });
      }
    };

    // TODO: 暂时关闭页签处理
    // const [{ close }] = useMultiTab();
    const router = useRouter();
    const closePage = () => {
      const path = router.currentRoute.value?.path;
      if (!path) return;
      router.push('/FormList');
      // close(path);
    };
    const queryParams = router.currentRoute.value.params;
    onMounted(() => {
      const MODELCODE = queryParams.MODELCODE as string;
      const templateId = router.currentRoute.value.query.templateId as string;
      state.templateId = templateId;
      state.modelCode = MODELCODE;
      if (templateId) {
        useGetFormDesignData(templateId)
          .then(data => {
            if (formProps.menu.controls.version.options) {
              formProps.menu.controls.version.options.items = data.versionList;
              formProps.menu.controls.version.options.value = {
                text: data.version,
                value: data.versionId,
              };
              versionId = data.versionId;
            }
            layoutData = data.layoutData;
            toolboxDatasource = data.templateData;
            dataInit = true;
            if (formIndexLoaded) {
              initCustomForm();
            }
          })
          .catch(e => {
            console.log(e);
          });
      }
    });

    return {
      t,
      formReady,
      formbuilderDom,
      formProps,
      getData,
      onLoad,
      designSave,
      formBuilderSave,
      formBuilderSaveRef,
      closePage,
    };
  },
});
</script>

<style lang="less" scoped>
.designer {
  height: 100%;
  height: 800px;
  display: flex;
  flex-direction: column;
  &__form {
    flex: 1;
  }
  &__footer {
    // border-top: 1px solid #c5c5c5;
    height: 60px;
    text-align: center;
    display: flex;
    align-items: center;
    justify-content: center;
    &--btn {
      width: 120px;
    }
    &--margin {
      margin-left: 30px;
    }
  }
}
</style>
