<template>
  <view v-if="drawFlag" v-show="showFlag" class="wk-keep-alive-item">
    <slot />
  </view>
</template>

<script>
	/**
	 * keep alive 子项（注：该组件不能单独使用，需配合 wk-keep-alive 组件使用）
	 * @author yxk
	 */
  export default {
    name: 'WkKeepAliveItem',
    data() {
      return {
        drawFlag: false,
        showFlag: false,

        isCreatedOk: false,

        flag: false
      }
    },
    watch: {
      flag: {
        handler(val) {
          this.$nextTick(function() {
            if (val) {
              this.drawFlag = true
              this.showFlag = true
              this.runActivated()
            } else {
              if (this.drawFlag === true) {
                this.runDeActivated()
              }
              this.showFlag = false
            }
          })
        }
      }
    },
    methods: {
      /**
       * 执行子组件 wkActivated 钩子（模仿 Vue activated 生命周期钩子）
       */
      runActivated() {
        let vnodes = null
        // #ifdef MP-WEIXIN
        vnodes = this.$children
        // #endif
        // #ifndef MP-WEIXIN
        vnodes = this.$slots.default
        // #endif
        vnodes.forEach(node => {
          this.$nextTick(function() {
            if (!this.isCreatedOk) {
              this.isCreatedOk = true
            }
            const that = node.componentInstance || node
            console.log('vnodes', that)
            const options = that.$options
            // 第一次 created 时不触发 wkActivated 钩子
            // if (
            //   options.wkActivated &&
            // 	this.isCreatedOk &&
            // 	typeof options.wkActivated === 'function'
            // ) {
            // 	console.log('run wkActivated')
            // 	options.wkActivated.call(that)
            // }
            if (
              options.wkActivated &&
              typeof options.wkActivated === 'function'
            ) {
              console.log('run wkActivated')
              options.wkActivated.call(that)
            }
          })
        })
      },

      /**
       * 执行子组件 wkDeactivated 钩子（模仿 Vue deactivated 生命周期钩子）
       */
      runDeActivated() {
        let vnodes = null
        // #ifdef MP-WEIXIN
        vnodes = this.$children
        // #endif
        // #ifndef MP-WEIXIN
        vnodes = this.$slots.default
        // #endif
        vnodes.forEach(node => {
          this.$nextTick(function() {
            const that = node.componentInstance || node
            // const options = node.componentInstance.$options
            if (that.$options.wkDeactivated && typeof that.$options.wkDeactivated === 'function') {
              that.$options.wkDeactivated.call(that)
            }
          })
        })
      }
    }
  }
</script>

<style scoped lang="scss">
</style>
