<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"},
    isRequire: {default: 1},
    selected: {default: () => []},
    placeholder: {default: "选择人员"},
    ops: {default: () => ({})},
    valueObj: Boolean
  },
  data() {
    return {
      configList: {
        resident: {url: "/components/pages/selectResident", label: "name"},
        sysUser: {url: "/components/pages/selectSysUser", label: "name"},
        gird: {url: "/components/pages/selectGird", label: "girdName"},
        party: {url: "/components/pages/selectParty", label: "name"},
        dept: {url: "/components/pages/selectDept", label: "name"},
        custom: {...this.ops}
      },
    }
  },
  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, valueObj, isRequire} = this,
          selected = (valueObj ? this.value[nodeKey] : this.value) || this.selected?.map(e => e[nodeKey])
      uni.$once('pagePicker:' + this.type, data => {
        console.log('发送', data)
        this.$emit("update:selected", data)
        this.$emit("select", data)
        this.$emit("change", valueObj ? data : data ? [data].flat()?.map(e => e[nodeKey]) : "")
      })
      let url = `${config.url}`,
          qsstr = qs.stringify({
            selected, nodeKey, isRequire, ...this.$attrs
          })
      if (!!qsstr) {
        url += `?${qsstr}`
      }
      uni.navigateTo({url})
    }
  }
}
</script>

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