<template>
  <div :type="type" :openid="oid"/>
</template>

<script>
import {mapActions} from "vuex";

export default {
  name: "AiOpenData",
  props: ['type', 'openid'],
  computed: {
    oid() {
      /**
       * 后端返回格式(cropId|userId)
       */
      return this.openid?.split("|")?.[1] || this.openid || ""
    }
  },
  methods: {
    ...mapActions(['injectJWeixin']),
    bindWWOpenData() {
      window?.WWOpenData?.checkSession({
        success: () => {
          WWOpenData.bind(this.$el)
        },
        fail: () => {
          this.injectJWeixin().then(() => {
            WWOpenData.bind(this.$el)
          })
        }
      }) || this.injectJWeixin().then(() => {
        WWOpenData.bind(this.$el)
      })
    }
  },
  watch: {
    openid(v) {
      v && this.bindWWOpenData()
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.bindWWOpenData()
    })
  }
}
</script>
