<template>
  <template v-for="item in filteredActions" :key="item.key">
    <a-button
      v-if="item.key === 'field'"
      :type="item.type"
      @click="handleShowField"
      >{{ item.title }} <DownOutlined v-show="!showField" />
      <UpOutlined v-show="showField" />
      <div class="c-field__panel" v-show="showField">
        <div
          class="c-field__item"
          v-for="field in tableColumns.filter((v) => v.key !== 'action')"
          :key="field.key"
          @click.stop
        >
          <a-checkbox
            :value="field.key"
            :checked="!field.hidden"
            @change="fieldChange"
            :disabled="field.disabled"
          >
            {{ field.title }}
          </a-checkbox>
        </div>
      </div>
    </a-button>
    <a-button
      v-else
      :disabled="hasOperatePermission(item.permission) ? false : true"
      @click="didClick(item)"
      :type="item.type"
      >{{ item.title }}</a-button
    >
  </template>
</template>

<script setup lang="ts">
import { inject, ref } from "vue";
import { DownOutlined, UpOutlined } from "@ant-design/icons-vue";

const emit = defineEmits(["change"]);

const injectHasOperatePermission: any = inject("hasOperatePermission");

const cTableProvideData: any = inject("cTableProvideData");

const { filteredActions, tableColumns, didClick } = cTableProvideData;

const hasOperatePermission = (val) => {
  return injectHasOperatePermission ? injectHasOperatePermission(val) : true;
};

const showField = ref<boolean>(false);

const fieldChange = (e): void => {
  tableColumns.forEach((v) => {
    if (v.key === e.target.value) {
      v.hidden = !e.target.checked;
    }
  });

  let raceItem = tableColumns.filter((v) => {
    return v.hidden == false && v.key !== "action";
  });
  if (raceItem.length === 1 && !tableColumns.find((v) => v.disabled == true)) {
    tableColumns.forEach((v) => {
      if (v.key === raceItem[0].key) {
        v.hidden = raceItem[0].hidden;
        v.disabled = true;
      }
    });
  } else {
    tableColumns
      .filter((v) => {
        return v.disabled === true;
      })
      .forEach((j) => {
        j.disabled = false;
      });
  }
  emit("change", tableColumns);
};

const handleShowField = (): void => {
  showField.value = !showField.value;
};
</script>

<style lang="less" scoped>
.c-field__panel {
  position: absolute;
  top: 40px;
  right: 0px;
  background: #ffffff;
  box-shadow: 0px 9px 28px 8px rgba(0, 0, 0, 0.05),
    0px 6px 16px 0px rgba(0, 0, 0, 0.08), 0px 3px 6px -4px rgba(0, 0, 0, 0.12);
  border-radius: 4px;
  max-height: 300px;
  overflow-y: auto;
  z-index: 100;
  .c-field__item {
    padding: 6px 20px;
    font-weight: 400;
    color: #222222;
    border-bottom: 1px solid #edeef2;
  }
}
.ant-btn:not(:first-child) {
  margin-left: 10px;
}
</style>
