<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <span class="breadcrumb-title">检查任务管理</span>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <el-button
            type="primary"
            class="search-table-container--button"
            :icon="Plus"
            @click="handleCreateTask"
            v-if="taskManagementPermissions"
          >
            创建检查任务单
          </el-button>
          <BasicSearch
            :searchConfig="TASK_MANAGEMENT_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          />
        </header>
        <div class="batch-table">
          <div class="batch-operation--div" v-show="taskManagementPermissions && selectionItems.length > 0">
            <span>已选{{ selectionItems.length }}项</span>
            <div class="batch-operation--div--close">
              <div class="batch-operation--div--button">
                <el-button class="custom-el-button" v-show="isBatchPublish" @click="handleBatchPublish"
                  >批量发布</el-button
                >
                <el-button class="custom-el-button" v-show="isBatchWithdraw" @click="handleBatchWithdraw"
                  >批量撤回</el-button
                >
                <el-button class="custom-el-button" v-show="isBatchDelete" @click="handleBatchDelete"
                  >批量删除</el-button
                >
              </div>
              <el-icon class="close-icon" @click="handleCloseBatchOperation"><Close /></el-icon>
            </div>
          </div>
          <BasicTable
            ref="basicTableRef"
            :table-config="tableConfig"
            :table-data="tableData"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
            @update:selection="handleSelectionChange"
          >
            <template #taskName="scope">
              <div class="task-name--div">
                <el-tooltip
                  :content="scope.row.name"
                  placement="top"
                  effect="light"
                  v-if="isToolTip(scope.row.overdue, scope.row.name)"
                >
                  <span>{{ scope.row.name }}</span>
                </el-tooltip>
                <span v-else>{{ scope.row.name }}</span>
                <div class="overdue-icon">
                  <img :src="OverdueIcon" alt="overdue" v-if="scope.row.overdue" />
                </div>
              </div>
            </template>
            <template #inspectType="scope">
              <span>{{ INSPECT_TYPE_MAP[scope.row.inspectType] }}</span>
            </template>
            <template #effectStatus="scope">
              <div class="active-status--div">
                <div
                  class="dot"
                  :style="{ backgroundColor: ACTIVE_STATUS_COLOR[scope.row.effectStatus as ACTIVE_STATUS] }"
                ></div>
                <span>{{ ACTIVE_STATUS_MAP[scope.row.effectStatus] }}</span>
              </div>
            </template>
            <template #taskStage="scope">
              <span>{{ TASK_STAGE_MAP[scope.row.taskState] }}</span>
            </template>
            <template #executive="scope">
              <div class="executive-container">
                <p v-for="person in scope.row.executive" :key="person.id">
                  {{ person.realname }}（{{person.staffNo}}）
                </p>
              </div>
            </template>
            <template #action="scope">
              <div class="action-container--div">
                <ActionButton
                  text="编辑"
                  v-if="taskManagementPermissions && scope.row.effectStatus === ACTIVE_STATUS.NOT_EFFECTIVE"
                  @click="handleEditTask(scope.row.id)"
                />
                <ActionButton
                  text="查看"
                  @click="
                    handleViewTask(
                      scope.row.id,
                      scope.row.name,
                      scope.row.deptName,
                      scope.row.taskState,
                      scope.row.inspectType,
                    )
                  "
                />
                <ActionButton
                  text="发布"
                  :popconfirm="{
                    title: '确定要发布?',
                  }"
                  v-if="taskManagementPermissions && scope.row.effectStatus === ACTIVE_STATUS.NOT_EFFECTIVE"
                  @confirm="handlePublishTask(scope.row.id)"
                />
                <ActionButton
                  text="撤回"
                  :popconfirm="{
                    title: '确定要撤回?',
                  }"
                  v-else-if="
                    taskManagementPermissions &&
                    scope.row.taskState !== TASK_STAGE.COMPLETED &&
                    scope.row.effectStatus === ACTIVE_STATUS.ACTIVE
                  "
                  @confirm="handleWithdrawTask(scope.row.id)"
                />
                <ActionButton
                  text="删除"
                  :popconfirm="{
                    title: '确定要删除?',
                  }"
                  v-if="taskManagementPermissions && scope.row.effectStatus === ACTIVE_STATUS.NOT_EFFECTIVE"
                  @confirm="handleDeleteTask(scope.row.id)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, onMounted, reactive } from 'vue';
  import { Plus, Close } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import BasicSearch from '@/components/BasicSearch.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { openMessageBox } from '@/utils/element-plus/messageBox';
  import { isToolTip } from './src/utils';
  import type { TaskManagementListQuery, TaskManagementListResponse } from '@/types/disaster-precaution';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    getTaskManagementList,
    deleteTaskManagementItem,
    withdrawTaskManagementItem,
    publishTaskManagementItem,
  } from '@/api/disaster-precaution';
  import OverdueIcon from '@/assets/svg/overdue.svg';
  import { INSPECT_TYPE_MAP, TASK_STAGE_MAP, TASK_STAGE } from './src/constants/task-execution';
  import {
    ACTIVE_STATUS,
    ACTIVE_STATUS_COLOR,
    ACTIVE_STATUS_MAP,
    DISASTER_PERMISSIONS,
  } from '@/views/disaster/constant';
  import {
    TABLE_OPTIONS_MANAGEMENT,
    TASK_MANAGEMENT_TABLE_COLUMNS,
    TASK_MANAGEMENT_SEARCH_CONFIG,
    TABLE_MANAGEMENT_HEIGHT_DEFAULT,
    TABLE_MANAGEMENT_HEIGHT_NOT_PERMISSION,
  } from './src/config';

  const { permissions } = useUserInfoHook();
  const router = useRouter();
  const searchData = reactive({
    inspectType: null,
    effectStatus: null,
    taskState: null,
  });
  const { tableConfig, pagination } = useTableConfig(TASK_MANAGEMENT_TABLE_COLUMNS, TABLE_OPTIONS_MANAGEMENT);
  let taskManagementListQuery: QueryPageRequest<TaskManagementListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const handleSearch = () => {
    taskManagementListQuery.queryParam = {};
    if (searchData.inspectType) {
      taskManagementListQuery.queryParam.inspectType = searchData.inspectType;
    }
    if (searchData.effectStatus) {
      taskManagementListQuery.queryParam.effectStatus = searchData.effectStatus;
    }
    if (searchData.taskState) {
      taskManagementListQuery.queryParam.taskState = searchData.taskState;
    }
    getTableData();
  };
  const selectionItems = ref<any[]>([]);
  const isBatchPublish = ref(false);
  const isBatchWithdraw = ref(false);
  const isBatchDelete = ref(false);
  const getSelectionIds = (option: ACTIVE_STATUS) => {
    return selectionItems.value.filter((item) => item.effectStatus === option).map((item) => item.id);
  };
  const handleSelectionChange = (selection: any[]) => {
    selectionItems.value = selection;
    const publishIds = getSelectionIds(ACTIVE_STATUS.NOT_EFFECTIVE);
    isBatchPublish.value = Boolean(publishIds.length);
    const withdrawIds = getSelectionIds(ACTIVE_STATUS.ACTIVE);
    isBatchWithdraw.value = Boolean(withdrawIds.length);
    isBatchDelete.value = Boolean(selectionItems.value.length === publishIds.length);
  };
  const handleBatchPublish = async () => {
    const confirmed = await openMessageBox('', '确认发布任务吗？', 'warning');
    if (!confirmed) return;
    const publishIds = getSelectionIds(ACTIVE_STATUS.NOT_EFFECTIVE);
    try {
      await publishTaskManagementItem(publishIds);
      ElMessage.success('批量发布成功');
    } finally {
      getTableData();
    }
  };
  const handleBatchWithdraw = async () => {
    const confirmed = await openMessageBox('', '确认撤回已发布任务吗？', 'warning');
    if (!confirmed) return;
    const withdrawIds = getSelectionIds(ACTIVE_STATUS.ACTIVE);
    try {
      await withdrawTaskManagementItem(withdrawIds);
      ElMessage.success('批量撤回成功');
    } finally {
      getTableData();
    }
  };
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const handleCloseBatchOperation = () => {
    if (!basicTableRef.value) return;
    basicTableRef.value.clearSelection();
  };
  const handleBatchDelete = async () => {
    const confirmed = await openMessageBox('', '删除后任务不可恢复，确认删除吗？', 'warning');
    if (!confirmed) return;
    const deleteIds = getSelectionIds(ACTIVE_STATUS.NOT_EFFECTIVE);
    await deleteTaskManagementItem(deleteIds);
    ElMessage.success('批量删除成功');
    getTableData();
  };

  const handlePublishTask = async (id: number) => {
    await publishTaskManagementItem(id);
    getTableData();
    ElMessage.success('发布成功');
  };

  const handleWithdrawTask = async (id: number) => {
    await withdrawTaskManagementItem(id);
    getTableData();
    ElMessage.success('已取消发布');
  };

  const handleDeleteTask = async (id: number) => {
    await deleteTaskManagementItem(id);
    getTableData();
    ElMessage.success('删除成功');
  };

  const defaultName = 'disaster-precaution-task-item';
  const handleCreateTask = () => {
    router.push({
      name: defaultName,
      query: {
        operate: 'create',
      },
    });
  };
  const handleEditTask = (id: number) => {
    router.push({
      name: defaultName,
      query: { operate: 'edit', id },
    });
  };
  const handleViewTask = (id: number, name: string, deptName: string, taskState: string, inspectType: string) => {
    router.push({
      name: defaultName,
      query: { id, name, deptName, taskState, inspectType },
    });
  };
  const tableData = ref<TaskManagementListResponse[]>([]);
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    taskManagementListQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    taskManagementListQuery.pageNumber = value;
    getTableData();
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getTaskManagementList(taskManagementListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  const taskManagementPermissions = ref<Boolean>(false);
  onMounted(() => {
    getTableData();
    taskManagementPermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.TASK_MANAGEMENT),
    );
    tableConfig.maxHeight = taskManagementPermissions.value
      ? TABLE_MANAGEMENT_HEIGHT_DEFAULT
      : TABLE_MANAGEMENT_HEIGHT_NOT_PERMISSION;
  });
</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 './src/style/task-execution.scss' as *;
  @use '@/views/disaster/style/disaster.scss' as *;
  .batch-table {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .batch-operation--div {
    @include flex-center;
    justify-content: flex-start;
    position: absolute;
    top: 0;
    left: 0;
    gap: 60px;
    width: 100%;
    height: 48px;
    border: 4px;
    padding: 16px 25px;
    background-color: #ddefff;
    z-index: 100;
    &--close {
      @include flex-center;
      justify-content: space-between;
      flex: 1;
    }
    .close-icon {
      font-size: 20px;
      color: #ff4d4f;
      cursor: pointer;
    }
  }
</style>
