<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: "input"
  },
  props: {
    value: {default: ""},
    type: {default: "resident"},
    nodeKey: {default: "idNumber"},
    selected: {default: () => []},
    placeholder: {default: "选择人员"},
    ops: {default: () => ({})},
    valueObj: Boolean,
    params: {default: () => ({})},
    multiple: 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, multiple} = 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("input", valueObj ? data :
            data ? (multiple ? [data].flat()?.map(e => e[nodeKey]) : data[nodeKey]) : "")
      })
      let url = `${config.url}`,
          qsstr = qs.stringify({
            selected, nodeKey, multiple, ...this.params
          })
      if (!!qsstr) {
        url += `?${qsstr}`
      }
      uni.navigateTo({url})
    }
  }
}
</script>

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