<template>
  <div class="disaster-precaution-container">
    <header class="disaster-precaution-container__header">
      <span class="disaster-precaution-container__title">灾害预防检查任务</span>
    </header>
    <main class="disaster-precaution-container__main">
      <div class="disaster-precaution">
        <header class="disaster-precaution__header">
          <Search
            :searchConfig="TASK_EXECUTION_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          />
        </header>
        <BasicTable
          :table-config="tableConfig"
          :table-data="tableData"
          @update:pageSize="handleSizeChange"
          @update:pageNumber="handleCurrentChange"
        >
          <template #taskName="scope">
            <div class="task-name--div">
              <el-tooltip :content="scope.row.name" placement="top" effect="light">
                <span>{{ scope.row.name }}</span>
              </el-tooltip>
              <img :src="OverdueIcon" v-if="scope.row.overdue" />
            </div>
          </template>
          <template #inspectType="scope">
            <span>{{ INSPECT_TYPE_MAP[scope.row.inspectType] }}</span>
          </template>
          <template #taskStage="scope">
            <span>{{ TASK_STAGE_MAP[scope.row.taskState] }}</span>
          </template>
          <!-- action button 不仅分任务情况 还要分 人物权限 -->
          <template #action="scope">
            <!-- 检查任务操作入口 -->
            <div class="action-container" v-if="scope.row.taskState === TASK_STAGE.PENDING_CHECK">
              <ActionButton text="去检查" @click="handleCheckItem(scope.row.id, 'check')" />
              <!-- 仅检查责任人可以看到 -->
              <ActionButton
                text="添加检查人"
                @click="handleAddCheckUser(scope.row.id)"
                v-if="scope.row.userTypeList.includes(USER_TYPE.CHECK_RESPONSIBLE)"
              />
            </div>
            <!-- 审批任务操作入口 -->
            <div class="action-container" v-else-if="scope.row.taskState === TASK_STAGE.PENDING_APPROVAL">
              <!-- 审批人员可以看到 -->
              <ActionButton
                text="去审批"
                v-if="scope.row.userTypeList.includes(USER_TYPE.APPROVER)"
                @click="handleCheckItem(scope.row.id, 'approve')"
              />
              <!-- 检查责任人、检查执行人员可以看到 -->
              <ActionButton
                v-else
                text="撤回"
                :popconfirm="{
                  title: '确定撤回吗？',
                }"
                @confirm="handleWithdrawTask(scope.row.id, scope.row.taskState)"
              />
            </div>
            <!-- 完成任务操作入口 -->
            <div class="action-container" v-else-if="scope.row.taskState === TASK_STAGE.COMPLETED">
              <ActionButton text="查看" @click="handleCheckItem(scope.row.id, 'view')" />
              <!-- 仅审批人员可以看到 -->
              <ActionButton
                v-if="
                  scope.row.userTypeList.includes(USER_TYPE.APPROVER) && !isOverdue24Hours(scope.row.dueCompleteTime)
                "
                text="撤回"
                :popconfirm="{
                  title: '确定撤回吗？',
                }"
                @confirm="handleWithdrawTask(scope.row.id, scope.row.taskState)"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </main>
    <el-dialog v-model="userInfo" title="添加检查人" destroy-on-close>
      <InspectorSelect
        :customUserList="currentTaskInspectorList"
        :currentTaskId="currentTaskId"
        @cancel="userInfo = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, onUnmounted } from 'vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import Search from '@/views/disaster/components/Search.vue';
  import InspectorSelect from '@/views/disaster/components/InspectorSelect.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import {
    getTaskExecutionList,
    getTaskInspectorList,
    withdrawTaskInspect,
    withdrawTaskApproval,
  } from '@/api/disaster-precaution';
  import type { TaskExecutionListResponse } from '@/types/disaster-precaution';
  import OverdueIcon from '@/assets/svg/overdue.svg';
  import { TASK_STAGE } from './src/constants/task-execution';
  import { INSPECT_TYPE_MAP, TASK_STAGE_MAP } from './src/constants/task-execution';
  import { TABLE_OPTIONS_EXECUTION, TASK_EXECUTION_TABLE_COLUMNS, TASK_EXECUTION_SEARCH_CONFIG } from './src/config';
  import type { TaskExecutionListQuery } from '@/types/disaster-precaution';
  import type { QueryPageRequest } from '@/types/disaster';
  import { USER_TYPE } from './src/constants/task-execution';
  import type { PersonGroupItem } from '@/types/person-group/type';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';

  const router = useRouter();
  const userInfo = ref(false);
  const searchData = reactive({
    inspectType: '',
    taskState: '',
  });

  const tableData = ref<TaskExecutionListResponse[]>([]);
  const { tableConfig, pagination } = useTableConfig(TASK_EXECUTION_TABLE_COLUMNS, TABLE_OPTIONS_EXECUTION);
  // 添加刷新时间变量，用于触发视图更新
  const refreshTime = ref(Date.now());
  let refreshTimer: number | null = null;

  let taskManagementListQuery: QueryPageRequest<TaskExecutionListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const handleSearch = () => {
    taskManagementListQuery.queryParam = {};
    if (searchData.inspectType !== '') {
      taskManagementListQuery.queryParam.inspectType = searchData.inspectType;
    }
    if (searchData.taskState !== '') {
      taskManagementListQuery.queryParam.taskState = searchData.taskState;
    }
    if (Object.keys(taskManagementListQuery.queryParam).length > 0) {
      pagination.pageNumber = 1;
      taskManagementListQuery.pageNumber = 1;
    }
    getTableData();
  };
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    taskManagementListQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    taskManagementListQuery.pageNumber = value;
    getTableData();
  };
  const currentTaskId = ref<number>();
  const currentTaskInspectorList = ref<PersonGroupItem[]>([]);
  const handleAddCheckUser = async (id: number) => {
    currentTaskId.value = id;
    const res = await getTaskInspectorList(currentTaskId.value);
    currentTaskInspectorList.value = res.map((item) => {
      return {
        ...item,
        checked: true,
      };
    });
    userInfo.value = true;
  };
  const defaultRouterName = 'disaster-precaution-task-execution-detail';
  const handleCheckItem = (id: number, operationType: 'check' | 'approve' | 'view') => {
    router.push({
      name: defaultRouterName,
      params: {
        id,
      },
      query: {
        operationType,
      },
    });
  };
  const handleWithdrawTask = async (id: number, state: number) => {
    if (state === TASK_STAGE.PENDING_APPROVAL) {
      await withdrawTaskInspect(id);
    } else if (state === TASK_STAGE.COMPLETED) {
      await withdrawTaskApproval(id);
    }
    ElMessage.success('已取消发布');
    getTableData();
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getTaskExecutionList(taskManagementListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  // 判断是否超过应完成时间24小时
  const isOverdue24Hours = (dueCompleteTime: string) => {
    if (!dueCompleteTime) return false;

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

    // 计算24小时的毫秒数: 24 * 60 * 60 * 1000 = 86400000
    return currentTime > dueTime + 86400000;
  };
  onMounted(() => {
    getTableData();

    // 设置定时器，每分钟更新一次时间
    refreshTimer = window.setInterval(() => {
      refreshTime.value = Date.now();
    }, 1000);
  });

  // 组件销毁时清除定时器
  onUnmounted(() => {
    if (refreshTimer !== null) {
      clearInterval(refreshTimer);
      refreshTimer = null;
    }
  });
</script>

<style scoped lang="scss">
  @use '../style/disaster.scss' as *;
  @use './src/style/task-execution.scss' as *;
</style>
