<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">
          <el-button
            type="primary"
            class="disaster-precaution__header--button"
            :icon="Plus"
            v-if="disposalManagementPermissions"
            @click="handleCreateDisposalManagement"
          >
            创建灾害处置任务
          </el-button>
          <Search
            :searchConfig="DISPOSAL_MANAGEMENT_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #reportDeptIds>
              <el-select
                v-model="searchData.reportDeptIds"
                multiple
                placeholder="请选择上报单位"
                filterable
                class="custom-select"
                @change="handleChangeReportDeptIds"
              >
                <el-option v-for="item in firstLevelDepts" :key="item.id" :label="item.deptName" :value="item.id" />
              </el-select>
            </template>
          </Search>
        </header>
        <section class="disaster-precaution__section">
          <div
            class="collapse-container"
            v-loading="collapseLoading"
            :class="disposalManagementPermissions ? 'collapse-container--permission' : 'collapse-container--default'"
          >
            <div class="empty-container" v-if="collapseList.length === 0">
              <img :src="Empty" />
              <span>暂无数据</span>
            </div>
            <template v-else>
              <CollapseItem
                ref="collapseItemRef"
                v-for="item in collapseList"
                :key="item.id"
                :name="item.taskName"
                :defaultOpen="item.id === collapseList[0].id"
              >
                <template #viewOperation>
                  <el-tooltip
                    :content="isViewTask(item.tableData[0].disasterReportTaskInfoList) ? '查看' : '任务尚未发布'"
                    placement="top"
                    effect="light"
                  >
                    <img
                      :src="ViewDocument"
                      :class="[
                        'collapse-item__icon',
                        { 'collapse-item__icon--disabled': !isViewTask(item.tableData[0].disasterReportTaskInfoList) },
                      ]"
                      @click.stop="isViewTask(item.tableData[0].disasterReportTaskInfoList) && handleViewTask(item.id)"
                    />
                  </el-tooltip>
                </template>
                <template #batchOperation v-if="disposalManagementPermissions">
                  <el-button
                    type="primary"
                    v-if="isBatchRelease(item.tableData[0].disasterReportTaskInfoList)"
                    @click.stop="handleBatchRelease(item.id)"
                    >发布
                  </el-button>
                  <el-button
                    type="primary"
                    v-if="isBatchWithdraw(item.tableData[0].disasterReportTaskInfoList)"
                    @click.stop="handleBatchWithdraw(item.id)"
                    >撤回
                  </el-button>
                  <el-button
                    type="primary"
                    v-if="isBatchDelete(item.tableData[0].disasterReportTaskInfoList)"
                    @click.stop="handleBatchDelete(item.id)"
                    >删除
                  </el-button>
                </template>
                <template #main-table>
                  <el-button
                    type="primary"
                    :icon="Plus"
                    class="main-table__button"
                    @click="handleCreateReportTask(item.id, item.taskName)"
                    >新增</el-button
                  >
                  <BasicTable :tableData="item.tableData[0].disasterReportTaskInfoList" :tableConfig="tableConfig">
                    <template #status="scope">
                      <div class="active-status--div">
                        <div
                          class="dot"
                          :style="{ backgroundColor: ACTIVE_STATUS_COLOR[scope.row.status as ACTIVE_STATUS] }"
                        />
                        <span>{{ ACTIVE_STATUS_MAP[scope.row.status] }}</span>
                      </div>
                    </template>
                    <template #taskStage="scope">
                      <span>{{ getTaskStage(scope.row.taskStage) }}</span>
                    </template>
                    <template #reportPrincipals="scope">
                      <p v-for="user in scope.row.reportPrincipalInfoList" :key="user.reportPrincipalId">
                        {{ user.reportPrincipalName }}（{{ user.reportPrincipalStaffNo }}）
                      </p>
                    </template>
                    <template #action="scope">
                      <ActionButton
                        text="编辑"
                        v-if="disposalManagementPermissions && scope.row.status === ACTIVE_STATUS.NOT_EFFECTIVE"
                        @click="handleEditReportTask(item.id, scope.row.id)"
                      />
                      <ActionButton
                        text="发布"
                        :popconfirm="{
                          title: '确定发布吗？',
                        }"
                        @confirm="handlePublishReportTask(scope.row.id, item.id)"
                        v-if="disposalManagementPermissions && scope.row.status === ACTIVE_STATUS.NOT_EFFECTIVE"
                      />
                      <ActionButton
                        text="撤回"
                        :popconfirm="{
                          title: '确定撤回吗？',
                        }"
                        @confirm="handleWithdrawReportTask(scope.row.id, item.id)"
                        v-if="
                          disposalManagementPermissions &&
                          (scope.row.taskStage === TASK_STAGE.TO_BE_REPORTED ||
                            scope.row.taskStage === TASK_STAGE.OVERDUE)
                        "
                      />
                      <ActionButton
                        text="删除"
                        :popconfirm="{
                          title: '确定删除吗？',
                        }"
                        @confirm="handleDeleteReportTask(scope.row.id)"
                        v-if="disposalManagementPermissions && scope.row.status === ACTIVE_STATUS.NOT_EFFECTIVE"
                      />
                      <ActionButton text="查看" v-if="scope.row.status === ACTIVE_STATUS.ACTIVE" />
                    </template>
                  </BasicTable>
                </template>
              </CollapseItem>
            </template>
          </div>
          <div class="pagination-container" v-if="collapseList.length > 0">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="DISASTER_CONTROL_PAGE_SIZE_CONFIG"
              layout="prev, pager, next, jumper, sizes, total"
              background
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </section>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { Plus } from '@element-plus/icons-vue';
  import Search from '@/views/disaster/components/Search.vue';
  import CollapseItem from './src/components/CollapseItem.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import { getAllDepartments } from '@/api/auth/dept';
  import { onMounted, reactive, ref, nextTick } from 'vue';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import type { DeptTreeItem } from '@/types/dept/type';
  import {
    getDisasterControlCollapseData,
    getDisasterControlTableData,
    publishDisasterHandleTask,
    withdrawDisasterHandleTask,
    deleteDisasterHandleTask,
    deleteDisasterReportTask,
    editDisasterReportTask,
  } from '@/api/disaster-control';
  import type { disasterReportTaskInfoListResponse } from '@/types/disaster-control';
  import { DEFAULT_PAGE_SIZE, DISASTER_CONTROL_PAGE_SIZE_CONFIG, TASK_STAGE } from './src/constant';
  import type {
    DisposalManagementCollapseListResponse,
    DisposalManagementTableResponse,
  } from '@/types/disaster-control';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import {
    DISPOSAL_MANAGEMENT_SEARCH_CONFIG,
    DISPOSAL_MANAGEMENT_TABLE_COLUMNS,
    DISPOSAL_MANAGEMENT_TABLE_OPTIONS,
  } from './src/config';
  import { getTaskStage } from './src/util';
  import {
    ACTIVE_STATUS,
    ACTIVE_STATUS_COLOR,
    ACTIVE_STATUS_MAP,
    DISASTER_PERMISSIONS,
  } from '@/views/disaster/constant';
  import ActionButton from '@/components/ActionButton.vue';
  import { useRouter } from 'vue-router';
  import Empty from 'assets/images/empty@1X.png';
  import ViewDocument from './src/svg/view-document.svg';
  import { useUserInfoHook } from '@/views/disaster/hooks/userInfo';
  import { openMessageBox } from '@/utils/element-plus/messageBox';
  import { ElMessage } from 'element-plus';

  const { permissions } = useUserInfoHook();
  const firstLevelDepts = ref<DeptTreeItem[]>([]);
  const searchData = reactive({
    reportDeptIds: null,
    status: null,
    taskStage: null,
  });

  const currentPage = ref(1);
  const pageSize = ref(DEFAULT_PAGE_SIZE);
  const total = ref(0);

  const collapseLoading = ref(false);
  const collapseItemRef = ref<InstanceType<typeof CollapseItem>[]>([]);
  const collapseList = ref<DisposalManagementCollapseListResponse<DisposalManagementTableResponse>[]>([]);
  const disposalManagementPermissions = ref(false);

  const { tableConfig } = useTableConfig(DISPOSAL_MANAGEMENT_TABLE_COLUMNS, DISPOSAL_MANAGEMENT_TABLE_OPTIONS, 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 handleSearch = () => {
    getDisposalTableData();
  };

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

  const taskIds = ref<number[]>([]);
  const router = useRouter();
  const Task_RouterName = 'disaster-control-disposal-management-task-item';
  const Table_RouterName = 'disaster-control-disposal-management-item';
  const handleCreateDisposalManagement = () => {
    router.push({
      name: Task_RouterName,
      query: {
        operate: 'create',
      },
    });
  };
  const handleCreateReportTask = (id: number, taskName: string) => {
    router.push({
      name: Table_RouterName,
      params: {
        id,
      },
      query: {
        operate: 'create',
        taskName,
      },
    });
  };
  const handleEditReportTask = (id: number, reportTaskId: number) => {
    router.push({
      name: Table_RouterName,
      params: {
        id,
      },
      query: {
        reportTaskId,
        operate: 'edit',
      },
    });
  };
  const handlePublishReportTask = async (id: number, handleTaskId: number) => {
    await editDisasterReportTask({
      id,
      handleTaskId,
      taskStage: TASK_STAGE.TO_BE_REPORTED,
      status: ACTIVE_STATUS.ACTIVE,
    });
    ElMessage.success('发布成功');
    await getDisposalTableData();
  };
  const handleWithdrawReportTask = async (id: number, handleTaskId: number) => {
    await editDisasterReportTask({
      id,
      handleTaskId,
      taskStage: TASK_STAGE.TO_BE_RELEASED,
      status: ACTIVE_STATUS.NOT_EFFECTIVE,
    });
    ElMessage.success('已取消发布');
    await getDisposalTableData();
  };
  const handleDeleteReportTask = async (id: number) => {
    await deleteDisasterReportTask(id);
    await getDisposalTableData();
    ElMessage.success('删除成功');
  };

  const getDisposalData = async () => {
    collapseLoading.value = true;
    const res = await getDisasterControlCollapseData({
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      queryParam: {},
    });
    collapseList.value = res.records.map((item) => ({
      ...item,
      tableData: [
        {
          handleTaskId: item.id,
          disasterReportTaskInfoList: [],
        },
      ],
    }));
    taskIds.value = collapseList.value.map((item) => item.id);
    total.value = res.totalRow;
    collapseLoading.value = false;
    nextTick(() => {
      collapseItemRef.value[0]?.openFirstCollapseItem();
    });
  };

  const getDisposalTableData = async () => {
    tableConfig.loading = true;

    const params = {
      handleTaskIds: taskIds.value,
      ...searchData,
    };

    const res = await getDisasterControlTableData(params);
    collapseList.value.forEach((item) => {
      item.tableData = res.filter((tableItem) => tableItem.handleTaskId === item.id);
    });
    tableConfig.loading = false;
  };

  const isViewTask = (disasterReportTaskInfoList: disasterReportTaskInfoListResponse[]) => {
    return disasterReportTaskInfoList.some((item) => item.status === ACTIVE_STATUS.ACTIVE);
  };

  const isBatchRelease = (disasterReportTaskInfoList: disasterReportTaskInfoListResponse[]) => {
    return disasterReportTaskInfoList.some((item) => item.status === ACTIVE_STATUS.NOT_EFFECTIVE);
  };

  const isBatchWithdraw = (disasterReportTaskInfoList: disasterReportTaskInfoListResponse[]) => {
    return disasterReportTaskInfoList.some((item) => item.status === ACTIVE_STATUS.ACTIVE);
  };

  const isBatchDelete = (disasterReportTaskInfoList: disasterReportTaskInfoListResponse[]) => {
    return disasterReportTaskInfoList.every((item) => item.status === ACTIVE_STATUS.NOT_EFFECTIVE);
  };

  const handleViewTask = (id: number) => {
    console.log('查看任务ID' + id);
  };

  const handleBatchRelease = async (id: number) => {
    const confirmed = await openMessageBox('', '确定发布吗？', 'warning');
    if (!confirmed) return;
    await publishDisasterHandleTask(id);
    ElMessage.success('发布成功');
    await getDisposalTableData();
  };

  const handleBatchWithdraw = async (id: number) => {
    const confirmed = await openMessageBox('', '确定撤回吗？', 'warning');
    if (!confirmed) return;
    await withdrawDisasterHandleTask(id);
    ElMessage.success('撤回成功');
    await getDisposalTableData();
  };

  const handleBatchDelete = async (id: number) => {
    const confirmed = await openMessageBox('', '确定删除吗？', 'warning');
    if (!confirmed) return;
    await deleteDisasterHandleTask(id);
    ElMessage.success('删除成功');
    await getDisposalData();
    await getDisposalTableData();
  };

  onMounted(async () => {
    const result = await getAllDepartments();
    await getDisposalData();
    await getDisposalTableData();
    disposalManagementPermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.DISPOSAL_MANAGEMENT),
    );
    firstLevelDepts.value = formatDeptTree(result);
  });
</script>

<style scoped lang="scss">
  @use '../style/disaster.scss' as *;
  @use './src/style/collapse.scss' as *;
  @use './src/style/common.scss' as *;
  $collapse-container-height-default: calc(68vh - 43px);
  $collapse-container-height-permission: calc(63vh - 45px);
  .collapse-container {
    &--permission {
      height: $collapse-container-height-permission;
      max-height: $collapse-container-height-permission;
    }
    &--default {
      height: $collapse-container-height-default;
      max-height: $collapse-container-height-default;
    }
  }
  .collapse-item__icon {
    width: 20px;
    &--disabled {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }
</style>
