<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title">检查单模版管理</div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div style="position: relative">
            <el-button type="primary" :icon="Plus" class="search-table-container--button" @click="handleCreate">
              添加
            </el-button>
          </div>

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>模版名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.templateName"
                  placeholder="搜索检查单模版名称"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select
                  v-model="tableQuery.queryParam.status"
                  placeholder="请选择状态"
                  clearable
                >
                  <el-option label="启用" :value="true" />
                  <el-option label="禁用" :value="false" />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>日期范围：</span>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #status="scope">
              <span>
                {{ scope.row.status === 1 ? '启用' : scope.row.status === 0 ? '禁用' : scope.row.status === 2 ? '草稿' : '-' }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton text="编辑" @click="handleEdit(scope.row.id)" />
                <ActionButton
                  text="删除"
                  :popconfirm="{
                    title: '确定要删除?',
                  }"
                  @confirm="handleDelete(scope.row.id)"
                />
                <ActionButton text="查看" @click="handleView(scope.row.id)" />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, CHECK_TEMPLATE_TABLE_COLUMNS } from './configs/tables';
  import { useRouter } from 'vue-router';
  import {
    queryChecklistTemplateList,
    deleteChecklistTemplate,
    type ChecklistTemplateQuery,
  } from '@/api/production-safety-system';

  const router = useRouter();

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(CHECK_TEMPLATE_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableData = ref<any[]>([]);

  const tableQuery = reactive<{
    pageNumber: number;
    pageSize: number;
    queryParam: ChecklistTemplateQuery;
  }>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      templateName: '',
      status: undefined,
      startDate: '',
      endDate: '',
    },
  });

  // 日期范围（用于日期选择器）
  const dateRange = ref<[string, string] | null>(null);

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await queryChecklistTemplateList(tableQuery);
      if (res) {
        tableData.value = (res.records || []).map((item) => ({
          id: item.id,
          templateName: item.templateName,
          status: item.status,
          categoryName: item.categoryName,
          useCount: item.useCount ?? 0,
          remark: item.remark,
          updateUserName: item.updateUserName,
          updatedAt: (item as any).updatedAt,
        }));
        pagination.total = res.totalRow ?? 0;
      }
    } catch (e) {
      console.error('获取检查单模版列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      tableQuery.queryParam.startDate = dateRange.value[0];
      tableQuery.queryParam.endDate = dateRange.value[1];
    } else {
      tableQuery.queryParam.startDate = '';
      tableQuery.queryParam.endDate = '';
    }
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.templateName = '';
    tableQuery.queryParam.status = undefined;
    tableQuery.queryParam.startDate = '';
    tableQuery.queryParam.endDate = '';
    dateRange.value = null;
    handleSearch();
  };

  const handleCreate = () => {
    router.push({
      name: 'checkTemplateManagementItem',
      query: {
        operate: 'check-template-create',
      },
    });
  };

  const handleEdit = (id: number) => {
    router.push({
      name: 'checkTemplateManagementItem',
      query: {
        id,
        operate: 'check-template-edit',
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteChecklistTemplate(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e) {
      console.error('删除检查单模版失败:', e);
      ElMessage.error(e?.message || e?.data || '删除失败，请重试');
    }
  };

  const handleView = (id: number) => {
    router.push({
      name: 'checkTemplateManagementItem',
      query: {
        id,
        operate: 'check-template-view',
      },
    });
  };

  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;
</style>
