<script lang="ts" setup>
import StatusSwitch from "../base-switch/StatusSwitch.vue";
import { ElMessage } from "element-plus";
import { $t } from "@/common/languages";
import { useStatus } from "@/common/languages/mapping/base-info-mapping";

const props = defineProps({
  tableEl: ref,
  statusLabelMapping: Function,
  tagTypeMapping: Function,
  statusParamName: {
    type: String,
    default: "status",
  },
  switchOnValue: {
    type: Number,
    default: 0,
  },
  switchOffValue: {
    type: Number,
    default: 1,
  },
});

const emit = defineEmits<{
  change: [val: any, row: any];
}>();

const { getCommonStatusLabel } = useStatus();

const buttonList = useRoute().meta.statusButtonAuth ?? [];

const change = (val: any, row: any) => {
  emit("change", val, row);
};

const getLabel = (code: number | null) => {
  if (props.statusLabelMapping === undefined) return getCommonStatusLabel(code);
  return props.statusLabelMapping(code);
};

const getTagType = (code: number | null): string => {
  if (props.tagTypeMapping !== undefined) {
    return props.tagTypeMapping(code);
  }
  // 默认逻辑：switchOnValue 为 success，其他为 info
  return code === props.switchOnValue ? "success" : "info";
};
</script>
<template>
  <el-table-column :label="$t('_prop.common.status')" :prop="statusParamName" min-width="100" align="center">
    <template #default="scope">
      <!-- 没有权限按钮时，显示带框标签 -->
      <span v-if="buttonList.length === 0">
        <el-tag :type="getTagType(scope.row[statusParamName])" size="small">
          {{ getLabel(scope.row[statusParamName]) }}
        </el-tag>
      </span>
      <!-- 有权限按钮时，显示开关或标签 -->
      <template v-else v-for="button in buttonList" :key="button.buttonName">
        <StatusSwitch
          v-model="scope.row[statusParamName]"
          @change="val => change(val, scope.row)"
          v-if="
            (button.eventName === 'enable' && scope.row[statusParamName] === switchOffValue) ||
            (button.eventName === 'disable' && scope.row[statusParamName] === switchOnValue)
          "
        />
      </template>
      <!-- 有权限但没有匹配到开关时，显示带框标签 -->
      <el-tag
        v-if="
          buttonList.length > 0 &&
          !buttonList.some(
            button =>
              (button.eventName === 'enable' && scope.row[statusParamName] === switchOffValue) ||
              (button.eventName === 'disable' && scope.row[statusParamName] === switchOnValue)
          )
        "
        :type="getTagType(scope.row[statusParamName])"
        size="small"
      >
        {{ getLabel(scope.row[statusParamName]) }}
      </el-tag>
    </template>
  </el-table-column>
</template>
