<script lang="ts" setup>
import DefaultToolButton from "@/components/base/default-tool-button/DefaultToolButton.vue";
import DefaultOperateButtonColumn from "@/components/base/default-column/DefaultOperateButtonColumn.vue";
import { usePage } from "@/composables/use-page";
import BaseForm from "@/components/base/base-form/BaseForm.vue";
import { $t } from "@/common/languages";
import type { FormInstance, FormRules } from "element-plus";
import { formatDate } from "@/common/utils/format-utils";
import TreeSidePageableTable from "@/components/base/treeside-pageable-table/TreeSidePageableTable.vue";
import DefaultStatusSwitchColumn from "@/components/base/default-column/DefaultStatusSwitchColumn.vue";
import StatusSwitch from "@/components/base/base-switch/StatusSwitch.vue";
import BaseTreeSelect from "@/components/base/base-tree-select/BaseTreeSelect.vue";

/**
 * 必须要的变量
 */

const getPageUrl = "/sys/syspermission/getSysPermissionPage";
const treeSideUrl = "/sys/syspermission/getPermissionTree";
const addUrl = "/sys/syspermission/addSysPermission";
const editUrl = "/sys/syspermission/updateSysPermission";
const removeUrl = "/sys/syspermission/deleteSysPermission";
const statusUrl = "/sys/syspermission/setStatus";
const searchers = [
  {
    name: "permissionName",
    type: "text" as const,
    placeholder: $t("_prop.systemset.permission.permissionName"),
  },
];
const rules = reactive<FormRules>({
  permissionName: [
    {
      required: true,
      message: $t("_message.systemset.permission.input_permissionName"),
      trigger: "blur",
    },
  ],
  permissionType: [
    {
      required: true,
      message: $t("_message.systemset.permission.select_permissionType"),
      trigger: "change",
    },
  ],
  sort: [
    {
      required: true,
      message: $t("_message.systemset.permission.input_sort"),
      trigger: "blur",
    },
  ],
});

/**
 * 权限类型枚举
 */
const permissionTypeOptions = [
  { code: 0, description: $t("_enum.permissionType.menu") },
  { code: 1, description: $t("_enum.permissionType.tableTopButton") },
  { code: 2, description: $t("_enum.permissionType.tableOperateButton") },
  { code: 3, description: $t("_enum.permissionType.statusButton") },
];

/**
 * 基本不变通用变量
 */
const tableRef = ref<InstanceType<typeof TreeSidePageableTable> | null>(null);
const { useAdd, useEdit, useRemove, useGeneralPageRef } = usePage(tableRef);
const { title, visible, formType, form } = useGeneralPageRef();

/**
 * 左侧树当前选中的节点
 */
const currentTreeNode = ref<any>(null);

/**
 * 可以自定义的变量
 */

const add = () => {
  form.value = {};
  // 如果左侧树有选中节点，自动设置父级权限
  if (currentTreeNode.value && currentTreeNode.value.id !== undefined) {
    form.value.parentId = currentTreeNode.value.id;
  }
  title.value = "_title.systemset.permission.add";
  visible.value = true;
  formType.value = false;
};
const edit = (row: any) => {
  title.value = "_title.systemset.permission.edit";
  form.value = { ...row };
  visible.value = true;
  formType.value = true;
};
const remove = (row: any) => {
  useRemove(removeUrl, row.id, "_message.systemset.permission.delete_message");
};
const submit = (formData: any, formRef: FormInstance | undefined) => {
  if (formRef !== undefined) {
    formRef.validate(valid => {
      if (valid) {
        if (formType.value) useEdit(editUrl, formData, visible);
        else useAdd(addUrl, formData, visible);
      }
    });
  }
};
const topButtonClick = (eventName: string) => {
  switch (eventName) {
    case "add":
      add();
      break;
  }
};
const operateButtonClick = (eventName: string, row: any) => {
  switch (eventName) {
    case "edit":
      edit(row);
      break;
    case "remove":
      remove(row);
      break;
  }
};

/**
 * 权限类型格式化
 */
const formatPermissionType = (row: any) => {
  const type = permissionTypeOptions.find(item => item.code === row.permissionType);
  return type?.description || "";
};

// 通用状态标签类型映射（启用/禁用）
const getCommonStatusTagType = (code: number | null): string => {
  const tagTypeMap: Record<number, string> = {
    0: "success", // 启用
    1: "info", // 禁用
  };
  return tagTypeMap[code ?? -1] || "info";
};
</script>

<template>
  <TreeSidePageableTable
    :url="getPageUrl"
    :searchers="searchers"
    ref="tableRef"
    :tree-side-url="treeSideUrl"
    tree-side-param-name="parentId"
    tree-side-node-name="id"
    @update:current-node="currentTreeNode = $event"
  >
    <template #tool-button>
      <DefaultToolButton @top-button-click="topButtonClick" />
    </template>
    <template #columns>
      <el-table-column :label="$t('_prop.systemset.permission.permissionName')" prop="permissionName" />
      <el-table-column :label="$t('_prop.systemset.permission.permissionCode')" prop="permissionCode" />
      <el-table-column
        :label="$t('_prop.systemset.permission.permissionType')"
        prop="permissionType"
        :formatter="formatPermissionType"
      />
      <el-table-column :label="$t('_prop.systemset.permission.pageLink')" prop="pageLink" />
      <el-table-column :label="$t('_prop.systemset.permission.eventName')" prop="eventName" />
      <el-table-column :label="$t('_prop.systemset.permission.iconName')" prop="iconName" />
      <el-table-column :label="$t('_prop.systemset.permission.sort')" prop="sort" />
      <el-table-column :label="$t('_prop.systemset.permission.hidden')" prop="hidden">
        <template #default="{ row }">
          <el-tag v-if="row.hidden" type="info" size="small">
            {{ $t("_common.yes") }}
          </el-tag>
          <el-tag v-else type="success" size="small">
            {{ $t("_common.no") }}
          </el-tag>
        </template>
      </el-table-column>
      <DefaultStatusSwitchColumn :url="statusUrl" :tag-type-mapping="getCommonStatusTagType" />
      <el-table-column :label="$t('_prop.common.createDate')" prop="createDate" :formatter="formatDate" />
      <DefaultOperateButtonColumn @operate-button-click="operateButtonClick" />
    </template>
  </TreeSidePageableTable>

  <BaseForm v-model:visible="visible" @submit="submit" v-model:form="form" :title="$t(title)" :rules="rules">
    <template #form-items>
      <el-form-item prop="id" v-if="false">
        <el-input v-model="form.id" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.permissionName')" prop="permissionName">
            <el-input
              v-model="form.permissionName"
              :placeholder="$t('_message.systemset.permission.input_permissionName')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.permissionI18n')" prop="permissionI18n">
            <el-input
              v-model="form.permissionI18n"
              :placeholder="$t('_message.systemset.permission.input_permissionI18n')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.permissionType')" prop="permissionType">
            <el-select
              v-model="form.permissionType"
              :placeholder="$t('_message.systemset.permission.select_permissionType')"
              style="width: 100%"
            >
              <el-option
                v-for="item in permissionTypeOptions"
                :key="item.code"
                :label="item.description"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.permissionCode')" prop="permissionCode">
            <el-input
              v-model="form.permissionCode"
              :placeholder="$t('_message.systemset.permission.input_permissionCode')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.pageLink')" prop="pageLink">
            <el-input v-model="form.pageLink" :placeholder="$t('_message.systemset.permission.input_pageLink')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.viewLink')" prop="viewLink">
            <el-input v-model="form.viewLink" :placeholder="$t('_message.systemset.permission.input_viewLink')" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.eventName')" prop="eventName">
            <el-input v-model="form.eventName" :placeholder="$t('_message.systemset.permission.input_eventName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.className')" prop="className">
            <el-input v-model="form.className" :placeholder="$t('_message.systemset.permission.input_className')" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.iconName')" prop="iconName">
            <el-input v-model="form.iconName" :placeholder="$t('_message.systemset.permission.input_iconName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.sort')" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="0"
              :placeholder="$t('_message.systemset.permission.input_sort')"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('_prop.common.status')" prop="status">
            <StatusSwitch v-model="form.status" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('_prop.systemset.permission.hidden')" prop="hidden">
            <el-switch v-model="form.hidden" :active-text="$t('_common.yes')" :inactive-text="$t('_common.no')" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="$t('_prop.systemset.permission.parentId')" prop="parentId">
        <BaseTreeSelect
          v-model="form.parentId"
          :url="treeSideUrl"
          :placeholder="$t('_message.systemset.permission.select_parentId')"
        />
      </el-form-item>
    </template>
  </BaseForm>
</template>
