<template>
  <section class="AppForm">
    <template v-if="showDetail">
      <form-detail :actions="actions"/>
    </template>
    <AiResult v-else :tips="errMsg" :status="errStatus" class="t-center"/>
  </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: v => !!v.$route.query?.id && v.access,
    errMsg() {
      this.access && (this.err = "表单不存在")
      return this.err || "数据读取中..."
    },
    errStatus: v => !!v.err ? "error" : "loading",
    isPreview: v => !!v.$route.query?.preview,
    actions() {
      const config = {
        default: {
          pageTitle: "调查问卷",
          common: "appquestionnairetemplate",
          detail: "appquestionnairetemplate",
          preview: true //是否有预览模式的存在,若存在需要无登录查询模板数据
        },
        AppAssessmentScoreTask: {
          pageTitle: "考核评分",
          common: "appassessmentscortask",
          detail: "appassessmentscoretemplate",
          preview: false, //是否有预览模式的存在,若存在需要无登录查询模板数据
          back: true,//填写完是否要返回按钮
        }
      }
      return config[this.$route.query.from || "default"]
    },
  },
  methods: {
    ...mapActions(['getCode', 'getToken']),
    checkAccess(review) {
      const {code, suiteId, id, result} = this.$route.query
      if (this.isPreview || result) {
        this.access = true
      } else if (!!this.user.token) {
        this.$http.post(`/app/${this.actions.common}/commitCheck`, null, {
          params: {id}
        }).then(res => {
          if (res?.code == 0) {
            this.access = true
          } else if (res?.code == 401) {
            this.checkAccess()
          } else {
            this.err = res?.msg || "无法获取表单"
          }
        }).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 = this.actions.pageTitle
    wx.hideOptionMenu()
  },
}
</script>

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