<template>
  <span>
    <a-button
      v-for="btn in buttonsComputed"
      :key="btn.buttonId"
      :type="btn.type"
      :class="'sd-form-btns-' + btn.buttonId"
      :loading="loadingStates[btn.buttonId]"
      @click="btnClick(btn)"
    >
      {{ btn.buttonName }}
    </a-button>
  </span>
</template>

<script>
import components from './_import-components/sd-form-buttons-import'

export default {
  name: 'SdFormButtons',
  components,
  props: {
    buttons: {
      type: Array,
      default: undefined,
    },
    reverseBtns: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loadingStates: {},
    }
  },
  computed: {
    buttonsComputed() {
      // save按钮设为主要按钮
      let btns = this.buttons.map((btn) => {
        if (btn.buttonId === 'save') btn.type = 'primary'
        return btn
      })
      // 只有两个按钮，且其中一个是关闭
      if (btns.length === 2 && btns[1].buttonId === 'close') {
        // 另一个设置成主要按钮
        btns[0].type = 'primary'
      }
      // 保证主要按钮在最前面
      btns = btns.sort((a, b) => {
        if (a.type === 'primary') return -1
        if (b.type === 'primary') return 1
        return 0
      })
      return this.reverseBtns ? btns.reverse() : btns
    },
  },

  methods: {
    btnClick(btn) {
      this.loadingStates[btn.buttonId] = true
      this.loadingStates = { ...this.loadingStates }
      this.sdEmit('btnClick', btn).finally(() => {
        this.loadingStates[btn.buttonId] = false
        this.loadingStates = { ...this.loadingStates }
      })
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
</style>
