<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>
            <el-button plain class="search-table-container--button" @click="handleImport">
              导入
            </el-button>
            <el-button plain class="search-table-container--button" @click="handleDownload">
              导出
            </el-button>
          </div>

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>扣分标题：</span>
                <el-input
                  v-model="tableQuery.queryParam.deductionTitle"
                  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>
            </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.statusName ||
                  (scope.row.status === true ? '启用' : scope.row.status === false ? '禁用' : '-')
                }}
              </span>
            </template>
            <template #deductionReason="scope">
              <span>{{ scope.row.deductionReason || '-' }}</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>
    <BatchImport
      v-if="batchImportVisible"
      :visible="batchImportVisible"
      :import-api-url="importApiUrl"
      :template-url="templateUrl"
      template-name="月度扣分管理导入模版"
      :show-template="true"
      @close="batchImportVisible = false"
      @update="handleUpdate"
    />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, POINT_DEDUCTION_TABLE_COLUMNS } from './configs/tables';
  import { POINT_DEDUCTION_STATUS_OPTIONS } from './configs/status';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { queryMonthlyDeduction, deleteDeduction, exportMonthlyDeduction } from '@/api/pointDeduction';
  import { downloadByData } from '@/utils/file/download';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { ElMessage } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';

  const router = useRouter();

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

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

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

  const tableQuery = reactive<QueryPageRequest<any>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      deductionTitle: '', // 扣分标题
      status: '', // 状态，默认启用
    },
  });

  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 queryMonthlyDeduction(tableQuery);
      if (res) {
        // 映射返回数据字段到表格字段
        tableData.value = res.records.map((item) => ({
          id: item.id,
          deductionTitle: item.deductionTitle,
          deductionDate: item.deductionDate,
          deductionValue: item.deductionScore,
          departmentName: item.departmentName,
          deductionReason: item.deductionReason,
          hiddenDangerId: item.hiddenDangerId,
          status: item.status,
          statusName: item.statusName,
        }));
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取月度扣分列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.deductionTitle = '';
    tableQuery.queryParam.status = true; // 重置为默认启用状态
    handleSearch();
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/monthlyDeduction/importMonthlyDeduction'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/月度扣分管理导入模版.xlsx');

  const handleImport = () => {
    batchImportVisible.value = true;
  };

  const handleUpdate = () => {
    batchImportVisible.value = false;
    getTableData();
  };

  const handleDownload = async () => {
    try {
      const exportParams = {
        deductionTitle: tableQuery.queryParam.deductionTitle || undefined,
        status: tableQuery.queryParam.status,
      };
      const response = await exportMonthlyDeduction(exportParams);
      if (response) {
        const fileName = `月度扣分_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e:any) {
      console.error('导出月度扣分失败:', e);
      ElMessage.error(e?.message || e?.data || '导出失败，请重试');
    }
  };

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

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

  const handleDelete = async (id: number) => {
    try {
      await deleteDeduction(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e:any) {
      console.error('删除月度扣分失败:', e);
      ElMessage.error(e?.message || e?.data || '删除失败，请重试');
    }
  };

  const handleView = (id: number) => {
    router.push({
      name: 'PointDeductionItem',
      query: {
        id,
        operate: 'pointDeduction-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 *;

  .deduction-reason-list {
    width: 100%;
    /* padding: 8px 0; */
  }

  .deduction-reason-item {
    /* padding: 4px 0; */
  }

  .reason-content {
    display: flex;
    align-items: flex-start;
    gap: 4px;
  }

  .reason-serial {
    font-weight: 500;
    color: #606266;
  }

  .reason-text {
    flex: 1;
    color: #303133;
  }

  .reason-score {
    color: #909399;
    font-size: 12px;
  }

  .reason-divider {
    height: 1px;
    width: 100%;
    background-color: #dcdfe6;
    margin: 8px 0;
    display: block;
  }

  .no-reason {
    color: #909399;
  }
</style>
