<template>
  <Page name="search">
    <template #header>
      <search-bar v-model="searchForm.query" placeholder="请输入搜索关键词" auto @confirm="onSearch" />
    </template>
    <template #content>
      <List ref="list" v-model="list" :api="searchAPI" :addOption='addOption'>
        <template v-for="(item, index) in list">
          <zui-cell :key="index" @click="onSelect(item, index)">
            <template #title>{{ item[label] }}</template>
            <template #right>
              <render-dict v-if="dict" :dict="dict" :value="item[value]"></render-dict>
              <text v-else-if="value">{{ item[value] }}</text>
            </template>
          </zui-cell>
        </template>
      </List>
    </template>
  </Page>
</template>

<script>
export default {
  data() {
    return {
      searchForm: {
        query: ''
      },
      list: [],
      label: 'name',
      value: null,
      dict: null,
      isAdd: true,
      url: 'org',
    }
  },
  onLoad(option) {
    if (option.label) this.label = option.label;
    if (option.value) this.value = option.value;
    if (option.dict) this.dict = option.dict;
    if (option.url) this.url = option.url;
    if (!option.url) {
      uni.navigateBack();
    }
    if (option.mode === 'select') {
      uni.setNavigationBarTitle({ title: `选择${option.title}` || '选择' });
    }
  },
  methods: {
    searchAPI(params) {
      const $params = this.$params;
      let searchParams = { ...params, ...this.searchForm };
      if($params.params){
        let obj = JSON.parse($params.params)
        searchParams = { ...params, ...this.searchForm, ...obj }
      }
      return uni.$u.api.filter[this.url](searchParams);
    },
    onSelect(item) {
      const $params = this.$params;
      if ($params.mode === 'select') {
        uni.$emit('select-common', item.name == '不限' && !item.code ? { code: '', name: '' } : item);
        uni.navigateBack();
      }
    },
    addOption(list){
      let obj = { code: '',  name: '不限', id: '', };
      let hash = {};
      let options = [obj, ...list].reduce((result, item) => {
        let hashKey = `${item.id || item.code || item.username}` || '_empty';
        if (!hash[hashKey]) {
          hash[hashKey] = true;
          if (item.name) {
            result.push(item);
          }
        }
        return result; // 返回结果数组
      }, []);
      this.$emit('input', options);
    }
  }
}
</script>
