<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';
import { onMounted, ref } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { ElMessageBox } from 'element-plus';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { queryFormSchema, tableColumns } from './labelManage-data';
import LabelManageDrawerComp from './labelManage-drawer.vue';
import {
  querytagbaseApilist,
  addTagApi,
  editTagApi,
  deleteTagApi,
} from '#/api/system/tasksettings/checktheform';
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

// 模拟数据
// const mockData

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const res = await querytagbaseApilist({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return {
          items: res.rows || [],
          total: res.total || 0,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-checklis-labelManage-index',
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [LabelManageDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: LabelManageDrawerComp,
});

// 新增标签
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑标签
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除标签
async function confirmEvent(row: any) {
  try {
    await deleteTagApi(row.id);
    await basicTableApi.reload();
  } catch (error) {
    console.error('删除标签失败:', error);
    return;
  }
}

// 批量删除标签
function deleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteTagApi(ids);
      await basicTableApi.reload();
    } catch (error) {
      console.error('批量删除标签失败:', error);
      return;
    }
  });
}
const handleConfirm = async (data: any) => {
  drawerApi.drawerLoading(true);
  try {
    // 根据是否包含 id 来决定调用新增接口还是编辑接口
    if (data.id) {
      // 编辑操作
      await editTagApi(data);
    } else {
      // 新增操作
      await addTagApi({ tagName: data.tagName });
    }
    await basicTableApi.reload();
    drawerApi.close();
    // 刷新表格数据
  } catch (error) {
    console.error('保存标签信息失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
};
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="标签管理列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
          >
            批量删除
          </ElButton>
          <ElButton type="primary" @click="openDrawer"> 新增标签 </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton size="small" type="primary" plain @click="handleEdit(row)">
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton size="small" type="danger" plain> 删除 </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <LabelManageDrawer @confirm="handleConfirm" />
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
