<template>
  <div :key="key" :class="$style.panel">
    <sd-header :class="$style.panelHeader"><div slot="left"/></sd-header>
    <div v-show="state === -1" :class="$style.skeletonBox">
      <div :class="$style.ske">
        <a-skeleton :paragraph="{ rows: 25 }" :class="$style.skeleton" />
      </div>
    </div>
    <component :is="webform" v-show="state === 1" />
    <a-result
      v-if="state === 0"
      :class="$style.panelResult"
      status="404"
      :title="errorinfo.message"
    >
      <template v-slot:extra>
        <a-button type="primary" @click="close">
          关闭
        </a-button>
      </template>
    </a-result>
  </div>
</template>

<script>
import Vue from 'vue'
import formService from '@/webform/form-service'
import SdWebform from './sd-webform.vue'
import components from './_import-components/sd-webform-panel-import'

/* eslint-disable vue/match-component-file-name */
Vue.component('sd-webform', SdWebform)

export default {
  name: 'SdWebformPanel',
  metaInfo() {
    return {
      title: this.pageTitle,
    }
  },
  components,
  data() {
    return {
      webform: null,
      errorinfo: null,
      state: -1,
      pageTitle: undefined,
      key: 1,
      formData: {},
    }
  },
  watch: {
    '$route.query.id': function(a, b) {
      // id开始时有值，说明不是新建时保存，更新页面
      // 路由如果发生了变化，等到数据更新了再更新视图
      if (b) {
        this.state = -1
        this.loadForm().then(() => {
          this.key++
        })
      }
    },
  },
  created() {
    this.loadForm()
  },
  provide() {
    return {
      formDataPanel: this.formData,
      updateFormPanel: this.loadForm,
    }
  },
  methods: {
    close() {
      window.close()
    },
    loadForm() {
      let p = this.$route?.meta?.preData
      if (!p) {
        p = formService.getData(this.$route.query)
      } else {
        this.$route.meta.preData = undefined
      }
      return p
        .then((res) => {
          Object.assign(this.formData, res)
          this.pageTitle = res.pageTitle
          this.webform = formService.getWebForm(res)
          this.state = 1
        })
        .catch((e) => {
          this.errorinfo = e.response
          this.state = 0
        })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
$panel-margin: 5%;
.panel {
  height: 100%;
  overflow: hidden;
  .panel-header {
    position: fixed;
    top: 0;
    right: 0;
    width: 100%;
  }
  .skeleton-box {
    position: absolute;
    z-index: 0;
    display: flex;
    justify-content: space-around;
    width: 100%;
    height: 100%;
    padding: 1%;
    margin: auto;
    overflow: hidden;
    .ske {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 100%;
      margin-top: $panel-margin;
      .skeleton {
        margin-top: 1%;
      }
    }
  }
  .panel-result {
    margin-top: $panel-margin;
  }
}
</style>
