<script>
import { Select } from 'ant-design-vue'

function sortVNode(a, b) {
  return (
    (a.data?.attrs['data-order'] || Number.POSITIVE_INFINITY) -
    (b.data?.attrs['data-order'] || Number.POSITIVE_INFINITY)
  )
}

export default {
  name: 'SdPrintContainer',
  inheritAttrs: false,
  props: {
    defaultPrintBlocks: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      showBlocks: this.defaultPrintBlocks,
    }
  },
  methods: {
    getPrintBlocks() {
      // 获取可用的区块列表
      return (
        this.$slots.default
          // 用sd-webflow-print-block包裹的才是可选区块
          .filter((vNode) => vNode.componentOptions?.tag === 'sd-webflow-print-block')
          .sort(sortVNode) // 按order排序
          .map((vNode) => {
            return {
              value: vNode.data.key,
              label: vNode.data.attrs.title,
            }
          })
      )
    },
    getChildren() {
      return this.$slots.default
        .filter((vNode) => {
          if (vNode.componentOptions?.tag === 'sd-webflow-print-block') {
            // 未选中的部分直接排除
            return this.showBlocks.includes(vNode.data.key)
          } else {
            return true
          }
        })
        .sort(sortVNode)
    },
  },
  render(h) {
    return (
      <div>
        <Select
          class={this.$style.select}
          maxTagCount={4}
          mode='multiple'
          placeholder='显示项'
          default-value={this.showBlocks}
          options={this.getPrintBlocks()}
          getPopupContainer={() => this.$el}
          dropdownClassName={this.$style.dropdown}
          on={{
            change: (data) => (this.showBlocks = data),
          }}
        />
        {this.getChildren()}
      </div>
    )
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
@use "@/common/components/sd-web-print.scss" as print;

.select {
  position: absolute;
  top: 16px; // 与modal header的padding相同
  left: 105px; // 留出打印按钮的空间
  z-index: 100;
  min-width: 15%;
}

@include print.wrapper-for-printer {
  .select,
  .dropdown {
    display: none;
  }
}
</style>
