<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { ElMessageBox } from 'element-plus';
import { useAccess } from '@vben/access';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteSecurityCamera, exportSecurityCamera, getSecurityCameraList } from '#/api/aiAnalysis/aiAnalysis';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './camera-data';
import CameraDrawerComp from './camera-drawer.vue';

const router = useRouter();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await getSecurityCameraList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'cameraId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'aiAnalysis-camera-index',
};

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

const [CameraDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: CameraDrawerComp,
});

const { hasAccessByCodes } = useAccess();

// 新增摄像头
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

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

// 查看摄像头详情
function handleView(row: any) {
  // 跳转到详情页面
  router.push({
    name: 'CameraDetail',
    params: { cameraId: row.cameraId },
  });
}

// 单个删除摄像头
async function confirmEvent(row: any) {
  await deleteSecurityCamera([row.cameraId]);
  await basicTableApi.reload();
}

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

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteSecurityCamera(ids);
    await basicTableApi.reload();
  });
}

// 导出摄像头数据
async function exportHandle() {
  await commonDownloadExcel(
    exportSecurityCamera,
    '摄像头设备数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
</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"
            v-access:code="['aiAnalysis:camera:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['aiAnalysis:camera:add']"
          >
            新增摄像头
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="info"
            plain
            @click="handleView(row)"
            v-access:code="['aiAnalysis:camera:view']"
          >
            查看
          </ElButton>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['aiAnalysis:camera:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['aiAnalysis:camera:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <CameraDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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