<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入显示名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业务类型编码" prop="typeCode">
              <el-input v-model="queryParams.typeCode" placeholder="请输入业务类型编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['business:type:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['business:type:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['business:type:remove']"
              >删除</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- ✅ 树形表格：增强版（带层级缩进+图标+路径） -->
      <el-table
        v-loading="loading"
        border
        :data="treeData"
        @selection-change="handleSelectionChange"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="显示名称" align="left" width="200">
          <template #default="{ row }">
            <span :style="{ paddingLeft: `${row.level * 24}px` }">
              <el-icon v-if="row.hasChildren" class="mr-1 text-blue-600">
                <FolderOpened />
              </el-icon>
              <el-icon v-else class="mr-1 text-gray-500">
                <Document />
              </el-icon>
              {{ row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="路径" align="left" width="250">
          <template #default="{ row }">
            {{ getFullPath(row) }}
          </template>
        </el-table-column>
        <el-table-column label="业务类型编码" align="center" prop="typeCode" />
        <el-table-column label="类型值" align="center" prop="typeValue" />
        <el-table-column label="父级ID" align="center" prop="parentId">
          <template #default="{ row }">
            <span :class="{ 'font-bold text-gray-700': row.parentId == null }">
              {{ row.parentId || '--' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 'enabled' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:type:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:type:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="typeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="显示名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入显示名称" />
        </el-form-item>
        <el-form-item label="类型编码" prop="typeCode">
          <el-input v-model="form.typeCode" placeholder="请输入业务类型编码" />
        </el-form-item>
        <el-form-item label="类型值" prop="typeValue">
          <el-input v-model="form.typeValue" placeholder="请输入类型值" />
        </el-form-item>
        <el-form-item label="父级节点" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父级节点" clearable filterable>
            <el-option v-for="item in itemOptionsGiftList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" value="enabled"></el-option>
            <el-option label="禁用" value="disabled"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Type" lang="ts">
import { listType, getType, delType, addType, updateType, selectGiftTypeParentList } from '@/api/system/business/type';
import { TypeVO, TypeQuery, TypeForm } from '@/api/system/business/type/types';
import { ref, reactive, toRefs, onMounted } from 'vue';
import { FolderOpened, Document } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 数据状态
const typeList = ref<TypeVO[]>([]);
const treeData = ref<TypeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const typeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: TypeForm = {
  id: undefined,
  name: undefined,
  typeCode: undefined,
  typeValue: undefined,
  parentId: undefined,
  status: 'enabled',
  createdAt: undefined,
  updatedAt: undefined
};

const data = reactive<PageData<TypeForm, TypeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 50,
    name: undefined,
    typeCode: undefined,
    typeValue: undefined,
    parentId: undefined,
    status: undefined,
    createdAt: undefined,
    updatedAt: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '显示名称不能为空', trigger: 'blur' }],
    typeCode: [{ required: true, message: '业务类型编码不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 全局 map 用于路径计算
const nodeMap = ref<Map<number, TypeVO>>(new Map());

// 构建树 + 注入 level/hasChildren
const buildTree = (list: TypeVO[]): TypeVO[] => {
  if (!list || list.length === 0) return [];

  const map = new Map<number, TypeVO>();
  const roots: TypeVO[] = [];

  // 1. 创建副本并初始化
  list.forEach((item) => {
    map.set(item.id, { ...item, children: [], level: 0, hasChildren: false });
  });

  // 2. 构建父子关系 & 计算层级
  list.forEach((item) => {
    const node = map.get(item.id)!;
    if (item.parentId == null) {
      roots.push(node);
    } else {
      const parent = map.get(item.parentId);
      if (parent) {
        if (!parent.children) parent.children = [];
        parent.children.push(node);
        node.level = parent.level + 1;
        parent.hasChildren = true;
      }
    }
  });

  // 保存全局 map 供路径计算使用
  nodeMap.value = map;
  return roots;
};

// 获取完整路径（如：线上参赛 > 普通参赛卡）
const getFullPath = (node: TypeVO): string => {
  const path: string[] = [node.name];
  let current = node;
  while (current.parentId && nodeMap.value.has(current.parentId)) {
    current = nodeMap.value.get(current.parentId)!;
    path.unshift(current.name);
  }
  return path.join(' > ');
};

/** 查询权益类型树列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listType(queryParams.value);
    typeList.value = res.rows;
    total.value = res.total;
    treeData.value = buildTree(res.rows);
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  typeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: TypeVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  loadCategoryOptions();
  dialog.visible = true;
  dialog.title = '添加权益类型';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: TypeVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getType(_id);
  Object.assign(form.value, res.data);
  loadCategoryOptions();
  dialog.visible = true;
  dialog.title = '修改权益类型';
};

/** 提交按钮 */
const submitForm = () => {
  typeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.value.id) {
          await updateType(form.value);
        } else {
          await addType(form.value);
        }
        proxy?.$modal.msgSuccess('操作成功');
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: TypeVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm(`是否确认删除编号为 "${_ids}" 的数据项？`);
  await delType(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 加载父级选项 */
const itemOptionsGiftList = ref<{ id: number; label: string }[]>([]);
const loadCategoryOptions = async () => {
  try {
    const res = await selectGiftTypeParentList();
    if (res.code === 200) {
      const data = res.data as unknown as { id: number; name: string }[];
      itemOptionsGiftList.value = data.map((item) => ({
        id: item.id,
        label: item.name
      }));
    }
  } catch (error) {
    console.error('加载父级选项失败:', error);
  }
};

onMounted(() => {
  getList();
  loadCategoryOptions();
});
</script>

<style scoped>
.font-bold {
  font-weight: 600;
}
.text-gray-700 {
  color: #303133;
}
.mr-1 {
  margin-right: 4px;
}
.text-blue-600 {
  color: #409eff;
}
.text-gray-500 {
  color: #909399;
}
</style>
