<template>
  <el-container class="user-tag-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple
          :searchFields="searchFields"
          :defaultValues="defaultSearchValues"
          @search="(val) => getData(1, val)"
          @reset="getData(1)"
        >
        </sa-search-simple>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">标签管理</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button icon="Plus" type="primary" @click="addRow">新建</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-dblclick="editRow"
          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="标签名称" min-width="120">
            <template #default="scope">
              <span class="sa-table-line-1">
                {{ scope.row.name || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="标签颜色" min-width="120">
            <template #default="scope">
              <el-tag :color="scope.row.color">
                {{ scope.row.color || '-' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="描述" min-width="200">
            <template #default="scope">
              <span class="sa-table-line-1">
                {{ scope.row.description || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="排序" min-width="100">
            <template #default="scope">
              {{ scope.row.sort || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" min-width="160">
            <template #default="scope">
              {{ scope.row.create_time || '-' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button class="is-link" type="primary" @click="editRow(scope.row)">编辑</el-button>
              <el-popconfirm
                width="fit-content"
                confirm-button-text="确认"
                cancel-button-text="取消"
                title="确认删除这条记录?"
                @confirm="deleteApi(scope.row.id)"
              >
                <template #reference>
                  <el-button class="is-link" type="danger"> 删除 </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 '../user.service';
  import { ElMessageBox } from 'element-plus';
  import { useModal } from '@/sheep/hooks';
  import { usePagination } from '@/sheep/hooks';
  import tagEdit from './edit.vue';
  const { pageData } = usePagination();

  // 搜索字段配置
  const searchFields = reactive({
    name: {
      type: 'input',
      label: '标签名称',
      placeholder: '请输入标签名称',
      width: 200,
    },
  });
  // 默认搜索值
  const defaultSearchValues = reactive({
    name: '',
  });
  // 列表
  const table = reactive({
    data: [],
    order: '',
    sort: '',
    selected: [],
  });
  const loading = ref(true);
  // 获取
  async function getData(page, searchParams = {}) {
    if (page) pageData.page = page;
    loading.value = true;
    const { error, data } = await api.tag.list({
      page: pageData.page,
      list_rows: pageData.list_rows,
      order: table.order,
      ...searchParams,
      sort: table.sort,
    });
    console.log('API 响应:', error, data);
    if (error === 0) {
      table.data = data.data;
      pageData.page = data.current_page;
      pageData.list_rows = data.per_page;
      pageData.total = data.total;
    }
    loading.value = false;
  }
  // 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.user.tag.delete',
      class: 'danger',
    },
  ];
  function addRow() {
    useModal(
      tagEdit,
      { title: '新建标签', type: 'add' },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }
  function editRow(row) {
    useModal(
      tagEdit,
      {
        title: '编辑标签',
        type: 'edit',
        id: row.id,
      },
      {
        confirm: () => {
          getData();
        },
      },
    );
  }
  // 删除api 单独批量可以直接调用
  async function deleteApi(id) {
    await api.tag.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.tag.edit(ids.join(','), {
          status: type,
        });
        getData();
    }
  }

  onMounted(() => {
    getData();
  });
</script>
<style lang="scss" scoped>
  .user-tag-view {
    .el-header {
      height: auto;
    }
    .el-main {
      .sa-table-wrap {
        height: 100%;
      }
    }
  }
</style>
