<template>
  <el-container class="category-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset">
        </sa-search-simple>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">{{ t('modules.goods.goodsCategory') }}</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button icon="Plus" type="primary" @click="addRow">{{ t('common.create') }}</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="sa-table-wrap panel-block panel-block--bottom" v-loading="loading">
        <el-table height="100%" class="sa-table" :data="table.data" @selection-change="changeSelection"
          @sort-change="fieldFilter" row-key="id" stripe>
          <template #empty>
            <sa-empty />
          </template>
          <el-table-column type="selection" width="48" align="center"></el-table-column>
          <el-table-column prop="id" label="ID" min-width="100" sortable="custom">
          </el-table-column>
          <el-table-column :label="t('modules.goods.categoryName')" min-width="120">
            <template #default="scope">
              <span class="sa-table-line-1">
                {{ scope.row.name || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :label="t('form.sort')" min-width="80" align="center">
            <template #default="scope">
              {{ scope.row.sort || 0 }}
            </template>
          </el-table-column>
          <el-table-column :label="t('form.createTime')" min-width="160">
            <template #default="scope">
              {{ scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('form.updateTime')">
            <template #default="scope">
              {{ scope.row.updateTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="t('common.actions')">
            <template #default="scope">
              <el-button class="is-link" type="primary" @click="editRow(scope.row)">{{
                t('common.edit')
              }}</el-button>
              <el-popconfirm width="fit-content" :confirm-button-text="t('common.confirm')"
                :cancel-button-text="t('common.cancel')" :title="t('message.confirmDelete')"
                @confirm="deleteApi(scope.row.id)">
                <template #reference>
                  <el-button class="is-link" type="danger">{{ t('common.delete') }}</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #left>
        <sa-batch-handle :batchHandleTools="batchHandleTools" :selectedLeng="table.selected.length"
          @batchHandle="batchHandle"></sa-batch-handle>
      </template>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { api } from '../goods.service';
import { ElMessageBox } from 'element-plus';
import { useModal } from '@/sheep/hooks';
import { usePagination } from '@/sheep/hooks';
import { useI18n } from 'vue-i18n';
import categorytagEdit from './edit.vue';

const { t } = useI18n();
const { pageData } = usePagination();

// 搜索字段配置
const searchFields = reactive({
  name: {
    type: 'input',
    get label() {
      return t('modules.goods.categoryName');
    },
    get placeholder() {
      return t('form.inputCategoryName');
    },
    width: 200,
  },
});
// 默认搜索值
const defaultSearchValues = reactive({
  name: '',
});

// 当前搜索条件 - 使用 ref 支持双向绑定
const currentSearchParams = ref({});
// 列表
const table = reactive({
  data: [],
  order: '',
  sort: '',
  selected: [],
});
const loading = ref(true);
// 获取
async function getData(page, searchParams = null) {
  if (page) pageData.page = page;
  loading.value = true;

  // 构建请求参数 - 优先使用传入的参数，否则使用双向绑定的搜索条件
  const finalSearchParams = searchParams !== null ? searchParams : currentSearchParams.value;

  const { code, data } = await api.category.list({
    page: pageData.page,
    size: pageData.size,
    ...finalSearchParams,
  });
  if (code == 200) {
    table.data = data.list;
    pageData.page = data.pageNum;
    pageData.size = data.pageSize;
    pageData.total = data.total;
  }
  loading.value = false;
}

// 搜索处理函数
function handleSearch(searchParams) {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1);
}

// 重置搜索参数处理函数
function handleReset() {
  // 手动清空搜索参数
  currentSearchParams.value = {};
  // 传递空参数重新请求数据
  getData(1, {});
}
// table 字段排序
function fieldFilter({ prop, order }) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;
  getData();
}
//table批量选择
function changeSelection(row) {
  table.selected = row;
}
// 分页/批量操作
const batchHandleTools = [
  // {
  //   type: 'delete',
  //   label: '删除',
  //   auth: 'shop.admin.category.delete',
  //   class: 'danger',
  // },
];
function addRow() {
  useModal(
    categorytagEdit,
    { title: t('modules.goods.addCategory'), type: 'add' },
    {
      confirm: () => {
        getData();
      },
    },
  );
}
function editRow(row) {
  useModal(
    categorytagEdit,
    {
      title: t('modules.goods.editCategory'),
      type: 'edit',
      id: row.id,
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}
// 删除api 单独批量可以直接调用
async function deleteApi(id) {
  await api.category.delete({ id });
  getData();
}
async function batchHandle(type) {
  let ids = [];
  table.selected.forEach((row) => {
    ids.push(row.id);
  });
  switch (type) {
    case 'delete':
      ElMessageBox.confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteApi(ids.join(','));
      });
      break;
    default:
      await api.category.edit(ids.join(','), {
        status: type,
      });
      getData();
  }
}

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
.category-view {
  .el-header {
    height: auto;
  }

  .el-main {
    .sa-table-wrap {
      height: 100%;
    }
  }
}
</style>
