<script setup lang="ts">
import { ref } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  getCategoryListApi,
  deleteCategoryApi,
  CategoryDTO
} from "@/api/shop/category";
import EditPen from "@iconify-icons/ep/edit-pen";
import Delete from "@iconify-icons/ep/delete";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import CategoryFormModal from "./category-form-modal.vue";
import CategoryEditModal from "./category-edit-modal.vue";
import { ElMessage, ElMessageBox } from "element-plus";

defineOptions({
  name: "ShopCategory"
});

const formRef = ref();
const tableRef = ref();
const modalVisible = ref(false);
const editVisible = ref(false);
const currentRow = ref<CategoryDTO>();

// 搜索表单
const searchFormParams = ref({
  categoryName: "",
  sort: null
});

// 分页参数
const pagination = ref({
  pageSize: 10,
  currentPage: 1,
  total: 0
});

// 加载数据
const loading = ref(false);
const dataList = ref([]);
const multipleSelection = ref<number[]>([]);

// API调用
const getList = async () => {
  try {
    loading.value = true;
    const { data } = await getCategoryListApi({
      ...searchFormParams.value,
      pageSize: pagination.value.pageSize,
      pageNum: pagination.value.currentPage
    });
    dataList.value = data.rows;
    pagination.value.total = data.total;
  } finally {
    loading.value = false;
  }
};

// 搜索
const onSearch = () => {
  pagination.value.currentPage = 1;
  getList();
};

// 重置
const resetForm = () => {
  formRef.value.resetFields();
  getList();
};

// 分页处理
const onSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  getList();
};

const onCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  getList();
};

// 删除处理
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除分类【${row.categoryName}】？`,
      "提示",
      {
        type: "warning"
      }
    );
    await deleteCategoryApi(row.categoryId);
    ElMessage.success("删除成功");
    getList();
  } catch (error) {
    console.error("删除失败", error);
  }
};

// 批量删除
const handleBulkDelete = async () => {
  if (multipleSelection.value.length === 0) return;

  try {
    await ElMessageBox.confirm(
      `确认删除选中的${multipleSelection.value.length}项？`,
      "提示",
      { type: "warning" }
    );

    await Promise.all(
      multipleSelection.value.map(id => deleteCategoryApi(id))
    );

    ElMessage.success("批量删除成功");
    getList();
  } catch (error) {
    console.error("批量删除失败", error);
  }
};
const handleEdit = (row: CategoryDTO) => {
  currentRow.value = row;
  editVisible.value = true;
};

// 表格列配置
const columns = [
  {
    label: "分类名称",
    prop: "categoryName"
  },
  {
    label: "排序",
    prop: "sort",
    width: 120
  },
  {
    label: "描述",
    prop: "description",
    showOverflowTooltip: true
  },
  {
    label: "创建时间",
    prop: "createTime",
    width: 180
  }
];
// 初始化加载
getList();
</script>

<template>
  <div class="main">
    <el-form ref="formRef" :inline="true" :model="searchFormParams"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]">
      <el-form-item label="分类名称：" prop="categoryName">
        <el-input @keydown.enter.prevent="onSearch" v-model="searchFormParams.categoryName" placeholder="请输入分类名称"
          clearable class="!w-[200px]" />
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input-number @keydown.enter.prevent="onSearch" v-model="searchFormParams.sort" :min="0"
          class="!w-[120px]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="useRenderIcon(Search)" @click="onSearch">
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar title="分类列表" @refresh="getList">
      <template #buttons>
        <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="modalVisible = true">
          新增分类
        </el-button>
        <el-button type="danger" :icon="useRenderIcon(Delete)" :disabled="multipleSelection.length === 0"
          @click="handleBulkDelete">
          批量删除
        </el-button>
      </template>

      <el-table ref="tableRef" v-loading="loading" :data="dataList" row-key="categoryId"
        @selection-change="val => multipleSelection = val.map(item => item.categoryId)">
        <el-table-column type="selection" width="55" />
        <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label" :width="col.width"
          :show-overflow-tooltip="col.showOverflowTooltip" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link :icon="useRenderIcon(EditPen)" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-popconfirm :title="`确认删除【${row.categoryName}】？`" @confirm="handleDelete(row)">
              <template #reference>
                <el-button type="danger" link :icon="useRenderIcon(Delete)">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
        @size-change="onSizeChange" @current-change="onCurrentChange" />
    </PureTableBar>

    <category-form-modal v-model:visible="modalVisible" @refresh="getList" />
    <category-edit-modal v-model:visible="editVisible" :row="currentRow" @refresh="getList" />
  </div>
</template>