<template>
  <section class="AiPagePicker">
    <div @click="handleJump">
      <slot v-if="$scopedSlots.default" :selected="pickList"/>
      <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},
    isShowPhone: {default: ''},
    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"},
        gridMember: {url: "/components/pages/selectGridMember", label: "name"},
        gridUser: {url: "/components/pages/selectGirdUser", label: "name"},
        party: {url: "/components/pages/selectParty", label: "name"},
        dept: {url: "/components/pages/selectDept", label: "name"},
        deptUser: {url: "/components/pages/selectDeptUser", label: "name"},
        custom: {...this.ops}
      },
      pickList: []
    }
  },
  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, isShowPhone} = this,
          selected = (valueObj ? this.value[nodeKey] : this.value) || this.selected?.map(e => e[nodeKey])
      uni.$off('pagePicker:' + this.type)
      uni.$once('pagePicker:' + this.type, data => {
        console.log('发送', data)
        this.pickList = 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, isShowPhone, ...this.$attrs
          })
      if (!!qsstr) {
        url += `?${qsstr}`
      }
      uni.navigateTo({url})
    }
  }
}
</script>

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