<template>
  <div class="search-table-container">
    <header class="disaster-precaution__header">
      <BasicSearch
        :searchConfig="LOSS_RECORD_LOSS_RECORD_SEARCH_CONFIG"
        :searchData="searchData"
        @update:searchData="handleSearch"
      >
        <template #handleDeptIds>
          <el-select
            v-model="searchData.handleDeptIds"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="1"
            placeholder="请选择整改部门"
            filterable
            class="custom-select"
            @change="handleChangeHandleDeptIds"
          >
            <el-option v-for="item in firstLevelDepts" :key="item.id" :label="item.deptName" :value="item.id" />
          </el-select>
        </template>
      </BasicSearch>
    </header>
    <section class="disaster-precaution__section">
      <div class="collapse-container" v-loading="collapseLoading">
        <div class="empty-container" v-if="collapseList.length === 0 || isEmpty">
          <img :src="Empty" />
          <span>暂无数据</span>
        </div>
        <template v-else>
          <CollapseItem
            v-for="item in collapseList"
            :key="item.id"
            :name="item.taskName"
            :isActive="activeId === item.id"
            @toggle="handleCollapseToggle(item.id)"
          >
            <template #view-operation>
              <el-tooltip
                :content="item.tableData[0].disasterReportRecordDetailList.length ? '' : '暂无损失记录'"
                placement="top"
                effect="light"
                :popper-class="
                  item.tableData[0].disasterReportRecordDetailList.length ? 'custom-tooltip--opacity0' : ''
                "
              >
                <img
                  :src="ViewDocument"
                  :class="[
                    'collapse-item__icon',
                    { 'collapse-item__icon--disabled': !item.tableData[0].disasterReportRecordDetailList.length },
                  ]"
                  @click.stop="
                    item.tableData[0].disasterReportRecordDetailList.length &&
                      handleView(item.handleTaskId, item.taskName, item.deptId)
                  "
                />
              </el-tooltip>
            </template>
            <template #main-table>
              <div class="mian-table-container">
                <el-button
                  type="primary"
                  :icon="Plus"
                  class="main-table__button"
                  v-if="isOverdue(item.dueCompleteTime)"
                  @click="handleReport(item.id, item.taskName)"
                  >新增</el-button
                >
                <BasicTable :tableData="item.tableData[0]?.disasterReportRecordDetailList" :tableConfig="tableConfig">
                  <template #affectedArea="scope">
                    <div class="affected-area-container">
                      <span>{{ scope.row.buildingNo }}-{{ scope.row.floorNo }}-{{ scope.row.roomNo }}</span>
                    </div>
                  </template>
                  <template #affectedItems="scope">
                    <el-tooltip
                      :content="scope.row.affectedItems"
                      placement="top-start"
                      effect="light"
                      v-if="scope.row.isLoss"
                      :popper-class="isToolTip(scope.row.affectedItems) ? '' : 'custom-tooltip--opacity0'"
                    >
                      <div class="affected-items-container">
                        <span>{{ scope.row.affectedItems }}</span>
                      </div>
                    </el-tooltip>
                    <span v-else>无损失</span>
                  </template>
                  <template #responsibleDeptName="scope">
                    <span v-if="scope.row.isLoss">{{ scope.row.responsibleDeptName }}</span>
                    <span v-else>--</span>
                  </template>
                  <template #priority="scope">
                    <span v-if="scope.row.isLoss">{{ getPriority(scope.row.priority) }}</span>
                    <span v-else>--</span>
                  </template>
                  <template #fixStatus="scope">
                    <div class="fix-status-container">
                      <span v-if="scope.row.isLoss">{{ getfixStatus(scope.row.fixStatus) }}</span>
                      <span v-else>--</span>
                    </div>
                  </template>
                  <template #action="scope">
                    <div class="action-container--div" v-if="scope.row.isLoss">
                      <ActionButton
                        text="编辑"
                        v-if="isOverdue(item.dueCompleteTime) && scope.row.fixStatus === FIX_STATUS.TO_BE_RECTIFIED"
                        @click="handleEdit(item.handleTaskId, scope.row.reportTaskId, scope.row.id)"
                      />
                      <ActionButton
                        text="查看"
                        @click="handleView(item.handleTaskId, item.taskName, item.deptId, scope.row.fixTaskId)"
                      />
                      <ActionButton
                        text="删除"
                        v-if="scope.row.fixStatus === FIX_STATUS.TO_BE_RECTIFIED"
                        :popconfirm="{
                          title: '确定删除吗？',
                        }"
                        @confirm="handleDelete(scope.row.id)"
                      />
                    </div>
                    <div class="action-container--div" v-else>
                      <ActionButton
                        text="查看"
                        v-if="scope.row.fixStatus === FIX_STATUS.TEMPORARY_CLOSED"
                        @click="handleView(item.handleTaskId, item.taskName, item.deptId, scope.row.fixTaskId)"
                      />
                      <ActionButton
                        text="编辑"
                        @click="handleEdit(item.handleTaskId, scope.row.reportTaskId, scope.row.id)"
                        v-if="isOverdue(item.dueCompleteTime) && scope.row.fixStatus !== FIX_STATUS.TEMPORARY_CLOSED"
                      />
                      <ActionButton
                        text="删除"
                        :popconfirm="{
                          title: '确定删除吗？',
                        }"
                        @confirm="handleDelete(scope.row.id)"
                        v-if="scope.row.fixStatus !== FIX_STATUS.TEMPORARY_CLOSED"
                      />
                    </div>
                  </template>
                </BasicTable>
              </div>
            </template>
          </CollapseItem>
        </template>
      </div>
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="DISASTER_CONTROL_PAGE_SIZE_CONFIG"
          :layout="DEFAULT_PAGINATION_LAYOUT"
          background
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </section>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import CollapseItem from './CollapseItem.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useDisasterControlHook } from '../hook';
  import { useDeptInfoHook, useUserInfoHook } from '@/views/disaster/hooks';
  import { getfixStatus, isToolTip } from '../util';
  import type { DisposalManagementCollapseListResponse, LossRecordTableResponse } from '@/types/disaster-control';
  import { getReportTaskList, getLossRecordTableData, deleteLossRecord } from '@/api/disaster-control';
  import {
    LOSS_RECORD_LOSS_RECORD_SEARCH_CONFIG,
    LOSS_RECORD_TABLE_COLUMNS,
    DISPOSAL_MANAGEMENT_TABLE_OPTIONS,
  } from '../config';
  import { DEFAULT_PAGE_SIZE, DISASTER_CONTROL_PAGE_SIZE_CONFIG, FIX_STATUS } from '../constant';
  import { DEFAULT_PAGINATION_LAYOUT } from '@/constant/pagination';
  import Empty from 'assets/images/empty@1X.png';
  import ViewDocument from '../svg/view-document.svg';

  const { getPriority, getPriorityDict } = useDisasterControlHook();
  const { getFirstLevelDepts, firstLevelDepts } = useDeptInfoHook();
  const { id: reporterId } = useUserInfoHook();

  const router = useRouter();
  const currentPage = ref(1);
  const pageSize = ref(DEFAULT_PAGE_SIZE);
  const total = ref(0);
  const collapseLoading = ref(false);
  const activeId = ref<number | null>(null);
  const { tableConfig } = useTableConfig(LOSS_RECORD_TABLE_COLUMNS, DISPOSAL_MANAGEMENT_TABLE_OPTIONS, false);
  const searchData = reactive({
    handleDeptIds: null,
    fixStatus: null,
  });
  const handleSearch = () => {
    getDisposalTableData();
  };

  const handleChangeHandleDeptIds = (value: number[]) => {
    if (!value) return;
    if (value.length === 0) {
      searchData.handleDeptIds = null;
    }
  };

  const taskIds = ref<number[]>([]);
  const collapseList = ref<DisposalManagementCollapseListResponse<LossRecordTableResponse>[]>([]);
  const isEmpty = computed(() => {
    return collapseList.value.every((item) => item.tableData[0].disasterReportRecordDetailList.length === 0);
  });
  const handleCollapseToggle = (itemId: number) => {
    if (activeId.value === itemId) {
      activeId.value = null;
    } else {
      activeId.value = itemId;
    }
  };
  const getDisposalData = async () => {
    collapseLoading.value = true;
    const res = await getReportTaskList({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      queryParam: {},
    });
    collapseList.value = res.records.map((item) => ({
      id: item.id,
      handleTaskId: item.handleTaskId,
      taskName: item.taskName,
      updatedAt: item.updatedAt,
      dueCompleteTime: item.dueCompleteTime,
      deptId: item.deptId,
      tableData: [
        {
          handleTaskId: item.handleTaskId,
          disasterReportRecordDetailList: [],
        },
      ],
    }));
    taskIds.value = res.records.map((item) => item.handleTaskId);
    total.value = res.totalRow;
    collapseLoading.value = false;
    if (collapseList.value.length > 0) {
      activeId.value = collapseList.value[0].id;
    } else {
      activeId.value = null;
    }
  };

  const getDisposalTableData = async () => {
    tableConfig.loading = true;
    const res = await getLossRecordTableData({
      handleTaskIds: taskIds.value,
      reporterId,
      ...searchData,
    });
    collapseList.value.forEach((item) => {
      item.tableData = res.filter((tableItem) => tableItem.handleTaskId === item.handleTaskId);
    });
    tableConfig.loading = false;
  };
  const handleSizeChange = async (size: number) => {
    pageSize.value = size;
    await getDisposalData();
    await getDisposalTableData();
  };

  const handleCurrentChange = async (page: number) => {
    currentPage.value = page;
    await getDisposalData();
    await getDisposalTableData();
  };

  const defaultName = 'disaster-control-loss-report-item';

  const handleReport = (handleTaskId: number, taskName: string) => {
    router.push({
      name: defaultName,
      params: {
        id: handleTaskId,
      },
      query: { taskName, operation: 'create' },
    });
  };

  const handleEdit = (handleTaskId: number, reportTaskId: number, id: number) => {
    router.push({
      name: defaultName,
      params: {
        id: reportTaskId,
      },
      query: {
        id,
        handleTaskId,
        operation: 'edit',
      },
    });
  };

  const handleView = (id: number, taskName: string, deptId: number, fixTaskId?: number) => {
    router.push({
      name: defaultName,
      params: { id },
      query: { taskName, fixTaskId, deptId },
    });
  };

  const handleDelete = async (id: number) => {
    await deleteLossRecord(id);
    await getDisposalTableData();
    ElMessage.success('删除成功');
  };
  // 添加刷新时间变量，用于触发视图更新
  const refreshTime = ref(Date.now());
  let refreshTimer: number | null = null;
  // 判断是否超过应完成时间
  const isOverdue = (dueCompleteTime: string) => {
    if (!dueCompleteTime) return false;

    const dueTime = new Date(dueCompleteTime).getTime();
    const currentTime = refreshTime.value;

    return currentTime < dueTime;
  };

  onMounted(async () => {
    getFirstLevelDepts();
    getPriorityDict();
    await getDisposalData();
    await getDisposalTableData();
    // 设置定时器，每秒更新一次时间
    refreshTimer = window.setInterval(() => {
      refreshTime.value = Date.now();
    }, 1000);
  });

  onUnmounted(() => {
    if (refreshTimer !== null) {
      clearInterval(refreshTimer);
      refreshTimer = null;
    }
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '../style/collapse.scss' as *;
  @use '../style/common.scss' as *;
  @use '@/views/disaster/style/disaster.scss' as *;
  $collapse-container-height: calc(68vh - 43px);
  .collapse-container {
    height: $collapse-container-height;
    max-height: $collapse-container-height;
  }
  .update-time-container {
    font-size: 14px;
    color: #999;
    font-weight: 400;
  }
</style>
