<!-- 商品分类管理 -->
<template>
  <div class="page">
    <div class="ele-body">
      <a-card :bordered="false" :body-style="{ padding: '16px' }">
        <ele-pro-table
          ref="tableRef"
          row-key="categoryId"
          :columns="columns"
          :datasource="datasource"
          :customRow="customRow"
          v-model:selection="selection"
          tool-class="ele-toolbar-form"
          class="sys-org-table"
        >
          <template #toolbar>
            <search
              @search="reload"
              :selection="selection"
              @add="openEdit"
              @remove="removeBatch"
            />
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'title'">
              <a-space :style="{ paddingLeft: ((depthMap.get(record.categoryId || 0) || 0) * 20) + 'px' }">
                <img v-if="record.image" :src="record.image" style="width: 24px; height: 24px; object-fit: cover; border-radius: 4px;" />
                <span class="font-bold">{{ record.title }}</span>
              </a-space>
            </template>
            <template v-if="column.key === 'type'">
              <a-tag :color="record.type === 0 ? 'blue' : 'orange'">
                {{ record.type === 0 ? '商城分类' : '外卖分类' }}
              </a-tag>
            </template>
            <template v-if="column.key === 'parentId'">
              {{ getParentName(record.parentId) }}
            </template>
            <template v-if="column.key === 'status'">
              <a-switch
                :checked="record.status === 0"
                checked-children="正常"
                un-checked-children="禁用"
                size="small"
                @change="(val: boolean) => toggleStatus(record, val)"
              />
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">编辑</a>
                <a-divider type="vertical" />
                <a-popconfirm
                  title="确定要删除此分类吗？"
                  @confirm="remove(record)"
                >
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>

      <!-- 编辑弹窗 -->
      <ShopGoodsCategoryEdit
        v-model:visible="showEdit"
        :data="current"
        :categoryList="flatCategoryList"
        @done="reload"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message } from 'ant-design-vue';
  import type { EleProTable } from 'ele-admin-pro';
  import { toDateString } from 'ele-admin-pro';
  import type {
    DatasourceFunction,
    ColumnItem
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import Search from './components/search.vue';
  import ShopGoodsCategoryEdit from './components/shopGoodsCategoryEdit.vue';
  import {
    listShopGoodsCategory,
    removeShopGoodsCategory,
    removeBatchShopGoodsCategory,
    updateShopGoodsCategory
  } from '@/api/shop/shopGoodsCategory';
  import type { ShopGoodsCategory, ShopGoodsCategoryParam } from '@/api/shop/shopGoodsCategory/model';

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  // 表格选中数据
  const selection = ref<ShopGoodsCategory[]>([]);
  // 当前编辑数据
  const current = ref<ShopGoodsCategory | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);
  // 分类列表（扁平，用于父级选择）
  const flatCategoryList = ref<ShopGoodsCategory[]>([]);
  // 分类层级深度映射
  const depthMap = ref<Map<number, number>>(new Map());

  // 计算每个分类的层级深度
  const computeDepth = (list: ShopGoodsCategory[]) => {
    const map = new Map<number, number>();
    const getDepth = (id?: number): number => {
      if (!id || id === 0) return 0;
      if (map.has(id)) return map.get(id)!;
      const parent = list.find((c) => c.categoryId === id);
      const d = parent ? getDepth(parent.parentId) + 1 : 0;
      map.set(id, d);
      return d;
    };
    list.forEach((c) => {
      if (c.categoryId) {
        map.set(c.categoryId, getDepth(c.categoryId));
      }
    });
    depthMap.value = map;
  };

  // 表格数据源（不分页，全量展示便于查看层级）
  const datasource: DatasourceFunction = ({ where, orders }) => {
    return listShopGoodsCategory({ ...where, ...orders }).then((res) => {
      const list = res || [];
      flatCategoryList.value = list;
      computeDepth(list);
      return { list, count: list.length };
    });
  };

  // 获取父级分类名称
  const getParentName = (parentId?: number) => {
    if (!parentId || parentId === 0) return '顶级分类';
    const parent = flatCategoryList.value.find((c) => c.categoryId === parentId);
    return parent?.title || '顶级分类';
  };

  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      title: 'ID',
      dataIndex: 'categoryId',
      key: 'categoryId',
      align: 'center',
      width: 70
    },
    {
      title: '分类名称',
      dataIndex: 'title',
      key: 'title',
      align: 'left',
      minWidth: 160
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      width: 100
    },
    {
      title: '上级分类',
      dataIndex: 'parentId',
      key: 'parentId',
      align: 'center',
      width: 120
    },
    {
      title: '排序',
      dataIndex: 'sortNumber',
      key: 'sortNumber',
      align: 'center',
      width: 80,
      sorter: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 90
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: 120,
      sorter: true,
      customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd')
    },
    {
      title: '操作',
      key: 'action',
      width: 140,
      fixed: 'right',
      align: 'center',
      hideInSetting: true
    }
  ]);

  /* 搜索 */
  const reload = (where?: ShopGoodsCategoryParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where: where });
  };

  /* 打开编辑弹窗 */
  const openEdit = (row?: ShopGoodsCategory) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 切换状态 */
  const toggleStatus = (row: ShopGoodsCategory, val: boolean) => {
    const newStatus = val ? 0 : 1;
    updateShopGoodsCategory({ ...row, status: newStatus })
      .then((msg) => {
        message.success(msg);
        row.status = newStatus;
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 删除单个 */
  const remove = (row: ShopGoodsCategory) => {
    const hide = message.loading('请求中..', 0);
    removeShopGoodsCategory(row.categoryId)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 批量删除 */
  const removeBatch = () => {
    if (!selection.value.length) return;
    const ids = selection.value.map((item) => item.categoryId);
    const hide = message.loading('请求中..', 0);
    removeBatchShopGoodsCategory(ids)
      .then((msg) => {
        hide();
        message.success(msg);
        reload();
      })
      .catch((e) => {
        hide();
        message.error(e.message);
      });
  };

  /* 行属性：双击编辑 */
  const customRow = (record: ShopGoodsCategory) => {
    return {
      onDblclick: () => {
        openEdit(record);
      }
    };
  };

  // 初始化由 ele-pro-table 自动触发 datasource 加载
</script>
