<template>
  <section class="AppForm">
    <template v-if="showDetail">
      <form-detail/>
    </template>
    <ai-result v-else :tips="errMsg" :status="errStatus"/>
  </section>
</template>

<script>
import {mapActions, mapState} from "vuex";
import FormDetail from "./formDetail";
import AiResult from "../../components/AiResult";

export default {
  name: "AppForm",
  appName: "问卷表单",
  inject: {root: {}},
  components: {AiResult, FormDetail},
  data() {
    return {
      access: false,
      err: ""
    }
  },
  computed: {
    ...mapState(['user', 'token']),
    showDetail() {
      return !!this.$route.query?.id && this.access
    },
    errMsg() {
      this.access && (this.err = "表单不存在")
      return this.err || "数据读取中..."
    },
    errStatus() {
      return !!this.err ? "error" : "loading"
    },
    isPreview() {
      return !!this.$route.query?.preview
    }
  },
  methods: {
    ...mapActions(['getCode', 'getToken']),
    checkAccess() {
      let {corpId, code, suiteId, id} = this.$route.query
      if (this.isPreview) {
        this.access = true
      } else if (!!this.token) {
        this.$http.post("/app/appquestionnairetemplate/commitCheck", null, {
          params: {id}
        }).then(res => {
          if (res?.code == 0) {
            this.access = true
          }
        }).catch(err => {
          this.err = err
        })
      } else if (code) {
        this.getToken({code, corpId, suiteId, isAppForm: true}).then(() => {
          let {query, path, hash} = this.$route
          delete query.code
          this.root.goto({query, path, hash})
        })
      } else {
        this.getCode({corpId, suiteId, url: location.href})
      }
    },
  },
  created() {
    this.checkAccess()
    document.title = "问卷调查"
  }
}
</script>

<style lang="scss" scoped>
.AppForm {
  position: absolute;
  width: 100%;
  height: 100%;
  background: #fff;
}
</style>
