<template>
  <div class="c-table">
    <template v-if="panelWrapped">
      <c-panel :title="title" :collapsible="false">
        <template #extra v-if="(filteredActions || []).length > 0">
          <table-actions @change="handleFieldChange" />
        </template>
        <table-vue v-bind="$attrs">
          <template
            v-for="item in Object.keys($slots)"
            #[item]="data"
            :key="item"
          >
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </table-vue>
      </c-panel>
    </template>
    <template v-else>
      <Space direction="vertical">
        <div class="action-group">
          <Space align="end">
            <table-actions @change="handleFieldChange" />
          </Space>
        </div>
        <table-vue v-bind="$attrs">
          <template
            v-for="item in Object.keys($slots)"
            #[item]="data"
            :key="item"
          >
            <slot :name="item" v-bind="data || {}"></slot>
          </template>
        </table-vue>
      </Space>
    </template>
  </div>
</template>

<script lang="ts" setup>
import { Space } from "ant-design-vue";
import type { CTableColumn, CTableAction, CTableCellAction } from "../types";
import { useVModel } from "@vueuse/core";
import {
  computed,
  toRefs,
  useSlots,
  inject,
  PropType,
  provide,
  reactive,
} from "vue";
import TableActions from "./actions.vue";
import TableVue from "./table.vue";
// const injectHasPermission: any = inject("hasPermission");
const injectHasOperatePermissionFunction: any = inject("hasOperatePermission");
const injectHasViewPermission: any = inject("hasViewPermission");

const emit = defineEmits<{
  (e: "didClickCell", param: CTableCellAction | any): void;
  (e: "didClick", action: CTableAction): void;
  (e: "change", any): void;
  (e: "fieldChange", param: any): void;
}>();

const props = defineProps({
  /**
   * 显示序列号
   */
  showIndex: {
    type: Boolean,
    default: false,
  },
  /**
   * 可选择
   */
  checkable: {
    type: Boolean,
    default: false,
  },
  /**
   * 多选 /单选
   */
  checkType: {
    type: String as PropType<"radio" | "checkbox">,
    default: "checkbox",
    required: false,
  },
  /**
   * v-modelnpm
   */
  selectedKeys: {
    type: Array as PropType<string[] | number[]>,
    required: false,
  },

  /**
   *  v-model
   */
  selectedRows: {
    type: Array as PropType<any[]>,
    required: false,
  },
  /**
   * 只在  panelWrapped true 时候生效
   */
  title: {
    type: String,
    default: "",
    required: false,
  },
  columns: {
    type: Array as PropType<CTableColumn[]>,
    required: true,
  },
  /**
   * 只在  panelWrapped true 时候生效
   */
  actions: {
    type: Array as PropType<CTableAction[]>,
    required: false,
  },

  /**
   * 表格行 事件
   */
  cellActions: {
    type: Array as PropType<CTableCellAction[]>,
    required: false,
  },
  /**
   * 是否外层使用面板包裹 默认是
   */
  panelWrapped: {
    type: Boolean,
    default: true,
  },
});

// 防止组件库内部测试报错

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

const showFooter = computed(() => useSlots().footer);

const { columns: tableColumns } = toRefs(props);
const rowSelection = computed(() =>
  props.checkable
    ? {
        type: props.checkType,
        selectedRowKeys: vselectedKeys,
        onChange: onSelectTableChange,
      }
    : null
);
const vselectedKeys = useVModel(props, "selectedKeys");
const vselectedRows = useVModel(props, "selectedRows");
/**
 * @param record 表格行
 * @param action cell aciton
   @param index  数据index
 */
const didClickCell = (record: any, action: CTableCellAction, index: number) => {
  //如果没有操作权限不触发
  if (action.permission) {
    if (!injectHasOperatePermission(action.permission)) {
      return;
    }
  }
  emit("didClickCell", { record, action, index });
};

const didClick = (action: CTableAction) => {
  //如果没有操作权限不触发
  if (action.permission) {
    if (!injectHasOperatePermission(action.permission)) {
      return;
    }
  }
  emit("didClick", action);
};

const handleTableChange = (page: any, filters: any, sorter: any) => {
  emit("change", { page, filters, sorter });
};
const onSelectTableChange = (values: string[] | number[], rows: any[]) => {
  console.debug("CTable , onSelectTableChange", values, rows);
  vselectedKeys.value = values;
  vselectedRows.value = rows;
};
const ifEnableIndex = () => {
  if (props.showIndex) {
    if (tableColumns.value.some((c) => c.key == "index")) {
      return;
    }
    tableColumns?.value.unshift({
      title: "序号",
      dataIndex: "index",
      key: "index",
      customRender: ({ index }) => index + 1,
      align: "center",
    });
  }
};
ifEnableIndex();
//是否拥有操作权限 或者 查看权限
const hasPermission = (code) => {
  if (injectHasOperatePermission === undefined) {
    return true;
  }
  if (!code) {
    return true;
  }
  // 能操作或者能看都显示出来
  if (injectHasOperatePermission(code) || injectHasViewPermission(code)) {
    return true;
  }
  return false;
};
//过滤权限
const filteredCellActions = computed(() =>
  props.cellActions?.filter((c) => {
    return hasPermission(c.permission);
  })
);
//过滤表头菜单
const filteredActions = computed(() =>
  props.actions?.filter((c) => hasPermission(c.permission))
);

const handleFieldChange = (value) => {
  emit("fieldChange", value);
};

// 处理表格内按钮禁用状态
const hanldeActionCellDisabled = (item, record) => {
  const customDisable = item.handleDisable ? item.handleDisable(record) : false;
  return !injectHasOperatePermission(item.permission) || customDisable;
};

const cTableProvideData = reactive({
  hanldeActionCellDisabled,
  filteredCellActions,
  handleTableChange,
  filteredActions,
  rowSelection,
  didClickCell,
  tableColumns,
  showFooter,
  didClick,
});

provide("cTableProvideData", cTableProvideData);
</script>
<style lang="less" scoped>
.c-table {
  .action-group {
    display: flex;
    justify-content: right;
  }
}
</style>
