<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 class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>检查场所/检查人员：</span>
                <el-input
                  v-model="tableQuery.queryParam.searchKey"
                  placeholder="搜索检查场所或检查人员"
                  class="act-search-input"
                  style="min-width: 200px;"
                  clearable
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select v-model="tableQuery.queryParam.status" placeholder="请选择状态" clearable>
                  <el-option
                    v-for="item in AREA_CHECK_PLAN_STATUS_OPTIONS"
                    :key="String(item.value)"
                    :label="item.label"
                    :value="item.value"
                  />
                </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>
              <el-button plain @click="handleDownload"> 导出 </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>{{ AREA_CHECK_PLAN_STATUS_LABEL[String(scope.row.status)] ?? '-' }}</span>
            </template>
            <template #frequency="scope">
              <span>{{ FREQUENCY_TO_LABEL[scope.row.frequency] ?? '-' }}</span>
            </template>
            <template #sign="scope">
            <div class="file-list">
                  <div class="file-item" v-for="item in scope.row.checkedPersonSign" :key="item.fileId">
                    <span class="file-item--name">{{ item.fileName }}</span>
                    <div class="file-item--footer">
                      <el-button link type="primary" @click="previewOnline(item.fileUrl, item.fileType)"
                        >预览</el-button
                      >
                      <el-button link type="primary" @click.stop="downloadFile(item.fileUrl, item.fileName)"
                        >下载</el-button
                      >
                    </div>
                  </div>
                </div>
            </template>
            <template #checkItemTotal="scope">
              <span>{{
                scope.row.checkItemTotal ? scope.row.checkItemTotal+'项' : '-'
              }}</span>
            </template>
            <template #qualifiedItemNum="scope">
              <span>{{ scope.row.qualifiedItemNum ? scope.row.qualifiedItemNum+'项' : '-' }}</span>
            </template>
            <template #unqualifiedItemNum="scope">
              <span>{{ scope.row.unqualifiedItemNum ? scope.row.unqualifiedItemNum+'项' : '-' }}</span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                 <template v-if="Number(scope.row.status) === 1">
                  <ActionButton text="检查" @click="handleCheck(scope.row)" />
                </template>
                <template v-else>
                  <ActionButton text="查看" @click="handleView(scope.row)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
      <PreviewOnline ref="previewOnlineRef" />
  </div>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { Plus } from '@element-plus/icons-vue';
  import {
    TABLE_OPTIONS,
    AREA_CHECK_PLAN_TABLE_COLUMNS,
    AREA_CHECK_PLAN_STATUS_OPTIONS,
    AREA_CHECK_PLAN_STATUS_LABEL,
  } from './configs/tables';
  import { FREQUENCY_TO_LABEL } from './configs/form';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { AreaCheckPlanQuery, AreaCheckPlanRecord } from './configs/types';
  import {
    queryAreaCheckPlanDetailPage,
    queryAreaInspectionPlanTask,
    mapAreaCheckPlanApiRecordToUi,
    exportAreaCheckPlanAdministration,
    exportRegionalInspectionPlanTaskDepartmentData,
  } from '@/api/production-safety-system';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';
  import { queryUserGroupPage } from '@/api/system/person-group';
  import type { PersonGroupListItem } from '@/types/person-group/type';
  import BatchImport from '@/components/batch-import/BatchImport.vue';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { downloadByData } from '@/utils/file/download';
  import { downloadFile } from '@/views/disaster/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
import { useUserInfoHook } from '@/views/disaster/hooks';
import { template } from 'lodash-es';
  const router = useRouter();
  const { id } = useUserInfoHook();
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const { tableConfig, pagination } = useTableConfig(AREA_CHECK_PLAN_TABLE_COLUMNS, TABLE_OPTIONS);
  const tableData = ref<AreaCheckPlanRecord[]>([]);
  const dateRange = ref<[string, string] | null>(null);

  // 场所所属类别选项（示例数据，本页面不调用接口）
  const venueCategoryOptions = ref<Array<{ label: string; value: string }>>([]);

    // 预览
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const previewOnline = (url: string | undefined, type) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };


  const tableQuery = reactive<QueryPageRequest<AreaCheckPlanQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      searchKey: '',
      startDate: '',
      endDate: '',
      status: '' as AreaCheckPlanQuery['status'],
      userId: id // 当前登录人ID
    },
  });

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

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };
  // 判断是否有值, 如果有值就转换成JSON.parse
  const safeJsonParse = (str) => {
  // 判断是否有有效值
  if (str === null || str === undefined || str.trim() === '') {
    return [];
  }

  try {
    return JSON.parse(str);
  } catch (e) {
    console.warn('JSON 解析失败:', e);
    return [];
  }
}

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await queryAreaInspectionPlanTask(tableQuery);
      const list = res?.records ?? [];
      tableData.value = list.map(item=>{
        // 附件转换格式
          item.checkedPersonSign = safeJsonParse(item.checkedPersonSign);
          return item;
      })
      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.searchKey = '';
    tableQuery.queryParam.status = '';
    tableQuery.queryParam.startDate = '';
    tableQuery.queryParam.endDate = '';
    dateRange.value = null;
    handleSearch();
  };



  const handleView = (row) => {
    router.push({
      name: 'areaCheckPlanTaskDeptItem',
      query: { 
        recordId: row.id, 
        planId: row.areaPlanId,
        checkType: row.checkType, 
        operate: 'area-check-plan-view' 
      },
    });
  };

  const handleCheck = (row: any) => {
    router.push({
      name: 'areaCheckPlanTaskDeptItem',
      query: { 
        recordId: row.id,
        planId: row.areaPlanId,
        checkType: row.checkType, // 传递检查类型，后续根据检查类型区分检查项来源
        operate: 'area-check-plan-create' },
    });
  };



  const handleDownload = async () => {
    try {
      const response = await exportRegionalInspectionPlanTaskDepartmentData(tableQuery.queryParam);
      if (response) {
        const fileName = `区域检查计划任务_${new Date().toISOString().split('T')[0]}.xlsx`;
        downloadByData(response, fileName);
        ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出文件失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  onMounted(() => {
    venueCategoryOptions.value = [
      { label: '各级风险点', value: '各级风险点' },
      { label: '关键业务活动', value: '关键业务活动' },
      { label: '日常安全', value: '日常安全' },
      { label: '各级危险点', value: '各级危险点' },
      { label: '试验室及试验过程', value: '试验室及试验过程' },
      {
        label: '办公区域（含地下车库、图书馆、档案库房、仓库等）',
        value: '办公区域（含地下车库、图书馆、档案库房、仓库等）',
      },
      { label: '老旧厂房', value: '老旧厂房' },
      { label: '施工现场', value: '施工现场' },
      { label: '职工食堂', value: '职工食堂' },
      { label: '职工宿舍', value: '职工宿舍' },
      { label: '体育活动场所', value: '体育活动场所' },
      { label: '托育园', value: '托育园' },
      { label: '租、出借房屋', value: '租、出借房屋' },
      { label: '院内经营服务场所', value: '院内经营服务场所' },
      { label: '垃圾房', value: '垃圾房' },
      { label: '院内交通', value: '院内交通' },
      { label: '消防设施设备', value: '消防设施设备' },
      { label: '特种设备', value: '特种设备' },
      { label: '防雷设施', value: '防雷设施' },
      { label: '供、配电设施设备（含弱电）', value: '供、配电设施设备（含弱电）' },
      { label: '公务车辆', value: '公务车辆' },
      { label: '燃气管道设施（含报警装置）', value: '燃气管道设施（含报警装置）' },
      { label: '建筑物外墙标识物、装饰物', value: '建筑物外墙标识物、装饰物' },
      { label: 'UPS电源', value: 'UPS电源' },
      { label: '危险化学品', value: '危险化学品' },
      { label: '设施设备应急操作流程', value: '设施设备应急操作流程' },
      { label: '堆场、物资库房', value: '堆场、物资库房' },
      { label: '室内外停车场', value: '室内外停车场' },
    ];
    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 *;
  :deep(.preview-img){
    img{
        max-width: 100%;
        max-height: 80vh;
    }
  }
</style>
