<template>
  <section class="AiPagePicker">
    <div @click="handleJump">
      <slot v-if="$slots.default"/>
      <div v-else v-text="selectedLabel"/>
    </div>
  </section>
</template>

<script>
import qs from 'query-string'

export default {
  name: "AiPagePicker",
  model: {
    prop: "value",
    event: "change"
  },
  props: {
    value: {default: ""},
    type: {default: "resident"},
    nodeKey: {default: "idNumber"},
    selected: {default: () => []},
    placeholder: {default: "选择人员"}
  },
  data() {
    return {
      configList: {
        resident: {url: "/components/pages/selectResident", label: "name"},
        gird: {url: "/components/pages/selectGird", label: "girdName"}
      },
    }
  },
  computed: {
    config() {
      return this.configList[this.type] || {}
    },
    selectedLabel() {
      let {placeholder, config: {label}} = this
      return this.selected?.map(e => e[label])?.toString() || placeholder
    }
  },
  methods: {
    handleJump() {
      let {config, nodeKey} = this,
          selected = this.value || this.selected?.map(e => e[nodeKey])
      uni.$once('pagePicker:' + this.type, data => {
        this.$emit("update:selected", data)
        this.$emit("select", data)
        this.$emit("change", data.map(e => e[nodeKey]))
      })
      let url = `${config.url}`,
          qsstr = qs.stringify({
            selected, ...this.$attrs
          })
      if (!!qsstr) {
        url += `?${qsstr}`
      }
      uni.navigateTo({url})
    }
  }
}
</script>

<style lang="scss" scoped>
.AiPagePicker {
}
</style>
