<template>
  <div>
    <!-- 拿到 模板名称和图片地址信息等信息 -->
    <base-info
      :showBaseInfo.sync="showBaseInfo"
      :defaultFolderId="folderId"
      @next="baseInfoNext"
      @cancel="cancelCreateTempl"
    ></base-info>
    <!-- 对words进行修改。 -->
    <words-manager
      :data.sync="words"
      @show-preview="showPreview = true"
      @confirm-words="confirm"
    ></words-manager>
    <transition name="van-slide-up">
      <preview-template
        :data="words"
        v-if="showPreview"
        @cancel="showPreview = false"
        @employ="employ"
      ></preview-template>
    </transition>
  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from 'vue-property-decorator';
import { TEMPLATETYPE, DataType } from '@/const/enum';
import BaseInfo from './components/BaseInfo.vue';
import PreviewTemplate from './components/PreviewTemplate.vue';
import WordsManager from './components/WordsManager.vue';
@Component({
  components: {
    BaseInfo,
    PreviewTemplate,
    WordsManager,
  },
})
export default class Add extends Vue {
  @Prop({
    required: false,
  })
  private folderId!: number | undefined;

  private showBaseInfo: boolean = true;

  /* 创建存证所需要的数据 */
  private baseInfo: any = {
    templateName: '',
    folder: {},
    imgUrl: '',
  };
  private words: any[] = [];

  private showWordsManager: boolean = false;

  private showPreview: boolean = false;
  get templateData() {
    const { baseInfo, words } = this;
    const { templateName, folder } = baseInfo;
    return {
      templateName,
      words,
      folder,
    };
  }
  private baseInfoNext(data: any) {
    this.baseInfo = { ...data };
  }
  private cancelCreateTempl() {
    this.$router.back();
  }
  private commitTemplate() {
    if (this.words.length <= 0) {
      return Promise.reject('请添加字段');
    }
    /* 创建存证 */
    return this.$api.template.customize(
      this.baseInfo.templateName,
      this.words,
      this.baseInfo.folder.id,
      {
        s_image_url: this.baseInfo.imgUrl,
      }
    );
  }
  private async confirm() {
    try {
      /* 创建存证 */
      const res = await this.commitTemplate();
      this.$dialog
        .confirm({
          title: '提示',
          message: '仅存还是去存证',
          confirmButtonText: '立即存证',
          cancelButtonText: '仅保存',
        })
        .then(() => {
          this.$router.push({
            name: 'ProofDetail',
            query: { templateId: res.id },
          });
        })
        .catch(() => {
          this.$router.push({ path: '/' });
        });
    } catch (err) {
      this.$toast(err);
    }
  }
  private async employ() {
    try {
      const res = await this.commitTemplate();
      this.$router.push({
        name: 'ProofDetail',
        query: { templateId: res.id },
      });
    } catch (err) {
      this.$toast(err);
    }
  }
}
</script>
