<script lang="ts" setup>
// 导入部分
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page, useVbenDrawer } from '@vben/common-ui';

import { ElButton, ElSpace } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getTaskEventReportList } from '#/api/archive/HSSE/HSSE';

import {
  mapApiToView,
  queryFormSchema,
  tableColumns,
} from './eventReport-data';
import eventReportDrawerComp from './eventReport-drawer.vue';

const router = useRouter();
// 响应式变量
const isLoading = ref(false);

// 表单配置
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: { allowClear: true },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
  fieldMappingTime: [
    [
      'occurrenceTime',
      ['occurrenceStartTime', 'occurrenceEndTime'],
      ['YYYY-MM-DD HH:mm:ss', 'YYYY-MM-DD HH:mm:ss'],
    ],
  ],
};

// 报工数据统计表格配置
const workReportGridOptions: VxeGridProps = {
  columns: tableColumns,
  height: '800px',
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query: async (params, formValues = {}) => {
        try {
          isLoading.value = true;
          // 映射表单数据到API参数
          console.log('params:', params);
          console.log('formValues:', formValues);
          formValues.pageNum = params.page.currentPage;
          formValues.pageSize = params.page.pageSize;
          // 调用API获取真实数据
          const resp = await getTaskEventReportList(formValues);
          // 映射API返回数据到表格显示
          const items = mapApiToView(resp?.rows || []);
          return {
            items,
            total: resp?.total || 0,
          };
        } catch (error) {
          console.error('获取事件报告列表失败:', error);
          return {
            items: [],
            total: 0,
          };
        } finally {
          isLoading.value = false;
        }
      },
    },
  },
  rowConfig: { keyField: 'id' },
  pagerConfig: { enabled: true, pageSize: 100, pageSizes: [10, 20, 50, 100] },
};

// 创建表格实例
const [WorkReportTable, workReportTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: workReportGridOptions,
});

// 初始化抽屉
const [eventReportDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: eventReportDrawerComp,
});

// 导出按钮点击事件
const handleExport = () => {
  console.log('导出数据');
  // TODO: 添加导出逻辑
};

// 新增按钮点击事件
const handleAdd = () => {
  drawerApi.setData({ isUpdate: false }).open();
};

// 查看按钮点击事件
const handleView = async (row: any) => {
  try {
    // isLoading.value = true;
    // 这里可以添加查看逻辑
    // console.log('查看事件报告:', row);
    // 例如：获取详细信息并显示
    // const detail = await getTaskEventReportDetail(row.id);
    // console.log('事件报告详情:', detail);
    router.push({
      name: 'EventReportDetail',
      params: { id: row.id },
    });
  } catch (error) {
    console.error('获取事件报告详情失败:', error);
  } finally {
    isLoading.value = false;
  }
};

// 编辑按钮点击事件
const handleEdit = (row: any) => {
  // 如果已经提交，则不能编辑
  if (row.processStage) {
    return;
  }
  drawerApi.setData({ ...row, isUpdate: true }).open();
};

// 重载表格数据
const handleReload = () => {
  workReportTableApi?.reload();
};
</script>

<template>
  <Page :auto-content-height="true">
    <div class="task-report-container">
      <!-- 报工数据统计表格 -->
      <div class="table-container">
        <WorkReportTable table-title="事件报告列表">
          <template #toolbar-tools>
            <ElSpace>
              <ElButton
                type="primary"
                @click="handleAdd"
                v-access:code="['system:taskEventReport:add']"
              >
                新增
              </ElButton>
              <ElButton
                @click="handleExport"
                v-access:code="['system:taskEventReport:export']"
              >
                导出
              </ElButton>
            </ElSpace>
          </template>
          <template #action="{ row }">
            <ElSpace>
              <ElButton size="small" type="primary" @click="handleView(row)">
                查看
              </ElButton>
              <ElButton
                size="small"
                @click="handleEdit(row)"
                :disabled="row.processStage"
              >
                编辑
              </ElButton>
            </ElSpace>
          </template>
        </WorkReportTable>
      </div>
    </div>
    <!-- 事件报告抽屉 -->
    <eventReportDrawer @reload="handleReload" />
  </Page>
</template>

<style scoped lang="scss">
.task-report-container {
  min-height: calc(100vh - 120px);
  padding: 16px;
  background-color: #fff;
}
</style>
