<template>
  <view>
    <u-checkbox-group @change="checkboxGroupChange">
      <u-checkbox
        v-model="item.checked"
        @change="checkboxChange"
        v-for="(item, index) in getOptions"
        :key="item.value"
        :name="item.value"
        >{{ item.label }}</u-checkbox
      >
    </u-checkbox-group>
  </view>
</template>
<script>
import { omit } from 'lodash-es'
export default {
  props: {
    api: {
      type: Function,
      default: () => {},
    },
    value: {
      type: [Array, Object, String, Number],
    },
    params: {
      type: Object,
      default: () => ({}),
    },
    labelField: {
      type: String,
      default: 'label',
    },
    valueField: {
      type: String,
      default: 'value',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
  },
  data() {
    return {
      checkValue: [],
      options: [],
      getOptions: [],
    }
  },
  computed: {},
  created() {
    this.fetch()
  },
  methods: {
    getOptionsFun() {
      const { labelField, valueField } = this
      return this.options.reduce((prev, next) => {
        if (next) {
          const value = next[valueField]
          prev.push({
            ...omit(next, [labelField, valueField]),
            label: next[labelField],
            value: value,
            key: value,
            checked: this.checkValue.includes(value),
          })
        }
        return prev
      }, [])
    },
    checkboxChange(e) {},
    checkboxGroupChange(e) {
      this.checkValue = e
      this.$emit('change', e)
      this.$emit('input', e)
    },
    async fetch() {
      const api = this.api
      if (!api || !this.isFunction(api)) return
      this.options = []
      try {
        const data = await api(this.params)
        this.isFirstLoad = false
        if (Array.isArray(data)) {
          this.options = data
          this.getOptions = this.getOptionsFun()
          this.emitChange()
          return
        }

        this.emitChange()
      } catch (error) {
        console.warn(error)
      }
    },
    emitChange() {
      this.$emit('options-change', this.getOptions)
    },
    isFunction(fn) {
      return typeof fn === 'function'
    },
  },
  watch: {
    value: {
      handler(val) {
        this.checkValue = val ?? []
        this.getOptionsFun()
      },
      immediate: true,
      deep: true,
    },
  },
}
</script>
