<script setup lang="ts">
import { reactive, watchEffect, computed } from 'vue';
import { isEmpty, every, omit } from 'src/common/utils';
import type {
  CellRenderButtonsType as ButtonsType,
  MoreButtonsType,
} from 'src/common/types';

const props = defineProps<{
  params: any;
}>();

/**
 * buttons: [
 *   {
 *     tooltip: '删除',
 *     round: true,
 *     icon: 'add',
 *     unelevated: true,
 *     callback: (data: any) => {
 *       onDel(data);
 *     },
 *   },
 * ];
 */

const state = reactive({
  buttons: [] as ButtonsType[],
  moreButtons: {} as MoreButtonsType,
});

watchEffect(() => {
  state.buttons = props.params.buttons || [];
  state.moreButtons = props.params.moreButtons || {};
});

const showMoreButtons = computed(() => {
  const hide = state.moreButtons.hide;
  const children = state.moreButtons.children;

  if (hide) {
    return false;
  } else {
    if (isEmpty(children)) {
      return false;
    } else {
      if (every(children, 'hide')) {
        return false;
      } else {
        return true;
      }
    }
  }
});

const showButtons = computed(() => {
  const buttons = state.buttons;
  if (isEmpty(buttons)) {
    return false;
  } else {
    if (every(buttons, 'hide')) {
      return false;
    } else {
      return true;
    }
  }
});

const moreButton = computed(() => {
  return omit(state.moreButtons, 'children');
});
</script>
<template>
  <div>
    <div class="row">
      <div class="q-gutter-xs" v-if="showButtons">
        <q-btn
          v-for="(item, index) in state.buttons"
          :key="index"
          v-bind="item"
          @click="item.callback(props.params)"
        >
          <q-tooltip v-if="item.tooltip">
            {{ item.tooltip }}
          </q-tooltip>
        </q-btn>
      </div>
      <div class="q-gutter-xs" v-if="showMoreButtons">
        <q-btn v-bind="moreButton">
          <q-menu>
            <q-list style="min-width: 100px">
              <q-item
                clickable
                v-close-popup
                v-for="(item, index) in state.moreButtons.children"
                :key="index"
                @click="item.callback(props.params)"
              >
                <q-item-section avatar v-if="!isEmpty(item.icon)">
                  <q-icon :color="item.color || 'grey-9'" :name="item.icon" />
                </q-item-section>
                <q-item-section>{{ item.label }}</q-item-section>
              </q-item>
            </q-list>
          </q-menu>
        </q-btn>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
