import sdWebflow from '@/webflow/sd-webflow.vue'
// 把 ext-webflow-template 的一些处理拿出来，不用写到项目代码里面
const webflowTemplateMixin = {
  inheritAttrs: false,
  mounted() {
    /*
      ext-webflow-template 只是一个包装，实际的 API 是由内部 sd-webflow 提供的
      找到 refs 中引用的当前组件，替换成内部的sd-webflow（第一个子组件）
    */
    for (const key in this.$parent.$refs) {
      if (this.$parent.$refs[key] === this) this.$parent.$refs[key] = this.$children[0].$children[0]
    }
    /*
      将ext-webflow-template组件里面this.refs指向到sd-webflow
    */
    for (const key in this.$refs) {
      if (this.$refs[key] === this.$children[0]) this.$refs[key] = this.$children[0].$children[0]
    }
  },
  components: {
    // sd-webflow-delegate：包裹sd-webflow，把flowData作为prop传递进去
    'sd-webflow-delegate': {
      inheritAttrs: false,
      inject: ['FlowDataPanel', 'updateFlowPanel'],
      created() {
        this.flowDataInternal = { ...this.FlowDataPanel }
      },
      data() {
        return {
          flowDataInternal: undefined,
        }
      },
      render(h) {
        return (
          // @ts-ignore
          <sdWebflow
            {...{
              attrs: {
                ...this.$attrs,
                flowData: this.flowDataInternal,
              },
              on: {
                ...this.$listeners,
                requestUpdateFlowData: (evt) => {
                  evt.waitUntil(
                    this.updateFlowPanel().then(() => {
                      this.flowDataInternal = { ...this.FlowDataPanel }
                    })
                  )
                },
              },
              scopedSlots: this.$scopedSlots,
            }}
          />
        )
      },
    },
  },
}
export default webflowTemplateMixin
