<template>
  <div class="search-table-container">
    <header class="disaster-precaution__header">
      <BasicSearch
        :searchConfig="LOSS_REPORT_REPORT_TASK_SEARCH_CONFIG"
        :searchData="searchData"
        @update:searchData="handleSearch"
      >
      </BasicSearch>
    </header>
    <BasicTable
      :tableConfig="tableConfig"
      :tableData="tableData"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <template #taskStage="scope">
        <span>{{ getTaskStage(scope.row.taskStage) }}</span>
      </template>
      <template #action="scope">
        <!-- 待上报任务阶段 -->
        <div class="action-container--div" v-if="scope.row.taskStage === TASK_STAGE.TO_BE_REPORTED">
          <ActionButton
            text="去上报"
            v-if="isOverdue(scope.row.dueCompleteTime)"
            @click="handleReport(scope.row.id, scope.row.taskName)"
          />
          <ActionButton
            text="添加上报人"
            v-if="isOverdue(scope.row.dueCompleteTime) && scope.row.isReportPrincipal"
            @click="handleAddReporter(scope.row.id, scope.row.reporterList)"
          />
        </div>
        <div
          class="action-container--div"
          v-else-if="
            scope.row.taskStage === TASK_STAGE.REPORTED_LOSS || scope.row.taskStage === TASK_STAGE.REPORTED_NO_LOSS
          "
        >
          <ActionButton
            text="去上报"
            v-if="isOverdue(scope.row.dueCompleteTime)"
            @click="handleReport(scope.row.id, scope.row.taskName)"
          />
          <ActionButton
            text="添加上报人"
            v-if="isOverdue(scope.row.dueCompleteTime) && scope.row.isReportPrincipal"
            @click="handleAddReporter(scope.row.id, scope.row.reporterList)"
          />
          <ActionButton
            text="查看记录"
            @click="handleView(scope.row.handleTaskId, scope.row.taskName, scope.row.deptId)"
          />
        </div>
        <div class="action-container--div" v-else>
          <span>--</span>
        </div>
      </template>
    </BasicTable>
    <el-dialog v-model="userInfo" title="添加上报人" destroy-on-close>
      <InspectorSelect
        :customUserList="currentTaskInspectorList"
        @cancel="userInfo = false"
        @submit="handleSubmitReporter"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, reactive, onMounted, onUnmounted } from '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 InspectorSelect from '@/views/disaster/components/InspectorSelect.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { getTaskStage } from '../util';
  import type { LossReportReportTaskQuery, LossReportReportTaskResponse } from '@/types/disaster-control';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { getReportTaskList, addReporter } from '@/api/disaster-control';
  import {
    LOSS_REPORT_REPORT_TASK_SEARCH_CONFIG,
    LOSS_REPORT_REPORT_TASK_TABLE_OPTIONS,
    LOSS_REPORT_REPORT_TASK_TABLE_COLUMNS,
  } from '../config';
  import { TASK_STAGE } from '../constant';
  import type { PersonGroupItem } from '@/types/person-group/type';
  import { queryUserInfoByIds } from '@/api/system/person-group';

  const router = useRouter();
  const searchData = reactive({
    taskStage: null,
  });
  const tableData = ref<LossReportReportTaskResponse[]>([]);
  const { tableConfig, pagination } = useTableConfig(
    LOSS_REPORT_REPORT_TASK_TABLE_COLUMNS,
    LOSS_REPORT_REPORT_TASK_TABLE_OPTIONS,
  );
  let ReportTaskListQuery: QueryPageRequest<LossReportReportTaskQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getReportTaskList(ReportTaskListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size;
    ReportTaskListQuery.pageSize = size;
    getTableData();
  };
  const handleCurrentChange = (current: number) => {
    pagination.pageNumber = current;
    ReportTaskListQuery.pageNumber = current;
    getTableData();
  };
  const handleSearch = () => {
    ReportTaskListQuery.queryParam = {};
    if (searchData.taskStage !== '') {
      ReportTaskListQuery.queryParam.taskStage = searchData.taskStage;
    }
    if (Object.keys(ReportTaskListQuery.queryParam).length > 0) {
      pagination.pageNumber = 1;
      ReportTaskListQuery.pageNumber = 1;
    }
    getTableData();
  };
  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 handleView = (id: number, taskName: string, deptId: number) => {
    router.push({
      name: defaultName,
      params: { id },
      query: { taskName, deptId },
    });
  };
  const userInfo = ref(false);
  const currentTaskId = ref<number>();
  const currentTaskInspectorList = ref<PersonGroupItem[]>([]);
  const handleAddReporter = async (id: number, userList: string) => {
    currentTaskId.value = id;
    const userIds = JSON.parse(userList) || [];
    if (!userIds.length) return;
    const res = await queryUserInfoByIds(userIds);
    currentTaskInspectorList.value = res.map((user) => {
      return {
        ...user,
        checked: true,
      };
    });
    userInfo.value = true;
  };
  const handleSubmitReporter = async (ids: number[]) => {
    if (!currentTaskId.value) return;
    await addReporter(currentTaskId.value, ids);
    ElMessage.success('添加上报责任人成功');
    userInfo.value = false;
    getTableData();
  };
  // 添加刷新时间变量，用于触发视图更新
  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(() => {
    getTableData();

    // 设置定时器，每秒更新一次时间
    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 '@/views/disaster/style/disaster.scss' as *;
</style>
