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

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

export default {
  name: "AppForm",
  appName: "问卷表单",
  inject: {root: {}},
  components: {FormDetail},
  data() {
    return {
      access: false,
      err: ""
    }
  },
  computed: {
    ...mapState(['user']),
    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
    },
    action: v => v.$route.query.action || "appquestionnairetemplate"
  },
  methods: {
    ...mapActions(['getCode', 'getToken']),
    checkAccess(review) {
      let {code, suiteId, id} = this.$route.query
      if (this.isPreview) {
        this.access = true
      } else if (!!this.user.token) {
        this.$http.post(`/app/${this.action}/commitCheck`, null, {
          params: {id}
        }).then(res => {
          if (res?.code == 0) {
            this.access = true
          } else if (res?.code == 401) {
            this.checkAccess()
          } else {
            this.err = "无法获取表单"
          }
        }).catch(err => {
          this.err = err
        })
      } else if (code) {
        this.getToken({code, suiteId}).then(() => this.checkAccess(true))
      } else if (!review) this.getCode()
      else this.err = "登录失败!"

    },
  },
  created() {
    this.checkAccess()
  },
  onShow() {
    document.title = '问卷调查'
    wx.hideOptionMenu()
  },
}
</script>

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