<!--
 * @Author: wlo_o
 * @Date: 2022-02-24 15:09:57
 * @LastEditors: wlo_o
 * @LastEditTime: 2022-02-28 09:59:42
 * @FilePath: /frontend/lib/components/MdRangeSelect.vue
 * @Description: 值域选择 - EleForm 扩展控件
 *
 * 源码参考：https://github.com/dream2023/vue-ele-form/blob/5e3f261cdd2d2d176678e4e384aeb723ec5bf2fd/lib/components/EleFormSelect.vue
 * 配置样例：
 {
  formDesc: {
    drink:{
      type: "md-range-select",
      label: "饮料",
      isOptions: true,
      options: [],
      rangeConfig: {
        parentId: 'drink_dict',
        searchKey: 'label'
      },
      attrs:{
        filterable: true,
        remote: true,
        allowCreate: true
      }
    }
  }
}
 * Copyright (c) 2022 by 青岛百洋智能科技股份有限公司, All Rights Reserved.
-->
<template>
  <el-select
    :class="desc.class"
    :style="desc.style"
    class="ele-form-full-line"
    v-bind="attrs"
    v-model="newValue"
    :loading="loading"
    :remote-method="remoteMethod?changeOptions:null"
    v-on="onEvents"
    ref="select"
  >
    <template
      v-for="(render, key) of slots"
      v-slot:[key]
    >
      <extend-slot
        :data="{
          options: desc.options
        }"
        :key="key"
        :render="render"
      />
    </template>
    <el-option
      :key="option.value"
      :label="option.text"
      :value="option.value"
      v-bind="option.attrs"
      v-for="option in options"
    ></el-option>
    <el-pagination
      small
      layout="prev, pager, next"
      :total="pagination.total"
      :page-size.sync="pagination.pageSize"
      :current-page.sync="pagination.page"
      hide-on-single-page
    >
    </el-pagination>
  </el-select>
</template>
<script>
import formMixin from 'vue-ele-form/lib/mixins/formMixin'
import { fetchApi } from '../common/apis.js'

export default {
  name: 'MdRangeSelect',
  mixins: [formMixin],
  inject: ['EleForm'],
  props: {
    field: String,
  },
  data() {
    return {
      loading: false,
      mockRule: 'radio',
      type: ['Boolean', 'Number', 'String', 'Array'],
      pagination: {
        total: 0,
        page: 1,
        pageSize: 5,
      },
      lastOptions: [],
    }
  },
  watch: {
    'pagination.page': function () {
      this.changeOptions(this.$refs.select.previousQuery)
    },
  },
  computed: {
    remoteMethod() {
      return this.attrs['remote-method'] || this.attrs.remoteMethod || this.getRangeValueOptions
    },
    defaultAttrs() {
      return {
        placeholder: this.t('ele-form.select') + this.desc._label,
      }
    },
  },
  methods: {
    getRangeValueOptions(q, callback) {
      let that = this
      let { page, pageSize } = this.pagination
      let { text = 'label', value = 'value' } = this.desc.prop || {}
      let { parentId, searchKey = 'label' } = this.desc.rangeConfig || {}
      let query = { ...(parentId && { parentId }), ...(q && { [searchKey]: q }), page, pageSize }
      fetchApi
        .call(this, '/element/values/pageList', query)
        .then(({ records = [], total = 0 }) => {
          let list = []
          records.forEach(o => {
            list.push({ id: o.id, text: o[text], value: o[value] })
          })
          that.pagination = { ...that.pagination, total }
          that.lastOptions = list
          callback(list)
        })
        .catch(() => {
          that.pagination = { ...that.pagination, total: 0 }
          callback([])
        })
    },
    changeOptions(q) {
      let that = this
      if (this.remoteMethod) {
        this.loading = true
        this.remoteMethod(q, options => {
          that.loading = false
          that.$set(that.EleForm.formDescData[that.field], '_options', options)
          that.EleForm.formDescData[that.field].isRestValByOptions = false
          that.EleForm.changeOptions(options, that.field)
        })
      }
    },
  },
  mounted() {
    if (this.remoteMethod && this.newValue) {
      this.changeOptions(this.newValue)
    } else if (this.desc.rangeConfig && this.desc.rangeConfig.parentId) {
      this.changeOptions()
    }
  },
}
</script>

