<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"
            v-if="disposalManagementPermissions"
            @click="handleCreateDisposalManagement"
          >
            创建灾害处置任务
          </el-button>
          <BasicSearch
            :searchConfig="DISPOSAL_MANAGEMENT_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #reportDeptIds>
              <el-select
                v-model="searchData.reportDeptIds"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="1"
                placeholder="请选择上报单位"
                filterable
                @change="handleChangeReportDeptIds"
                class="custom-select"
              >
                <el-option
                  v-for="item in originalDisasterLevelDepts"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
          </BasicSearch>
        </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
                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="isViewTask(item.tableData[0].disasterReportTaskInfoList) ? '' : '任务尚未发布'"
                    placement="top"
                    effect="light"
                    :popper-class="
                      isViewTask(item.tableData[0].disasterReportTaskInfoList) ? 'custom-tooltip--opacity0' : ''
                    "
                  >
                    <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, item.taskName)
                      "
                    />
                  </el-tooltip>
                </template>
                <template #right-header v-if="disposalManagementPermissions">
                  <el-button
                    class="custom-el-button"
                    v-if="isBatchRelease(item.tableData[0].disasterReportTaskInfoList)"
                    @click.stop="handleBatchRelease(item.id)"
                    >发布
                  </el-button>
                  <el-button
                    class="custom-el-button"
                    v-if="isBatchWithdraw(item.tableData[0].disasterReportTaskInfoList)"
                    @click.stop="handleBatchWithdraw(item.id)"
                    >撤回
                  </el-button>
                  <el-button
                    class="custom-el-button"
                    v-if="isBatchDelete(item.tableData[0].disasterReportTaskInfoList)"
                    @click.stop="handleBatchDelete(item.id)"
                    >删除
                  </el-button>
                </template>
                <template #main-table>
                  <div class="mian-table-container">
                    <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">
                        <div class="principal-container--div">
                          <p v-for="user in scope.row.reportPrincipalInfoList" :key="user.reportPrincipalId">
                            {{ user.reportPrincipalName }}（{{ user.reportPrincipalStaffNo }}）
                          </p>
                        </div>
                      </template>
                      <template #action="scope">
                        <div class="action-container--div">
                          <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"
                            @click="handleViewItem(item.id, scope.row.deptId, item.taskName)"
                          />
                        </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>
    </main>
  </div>
</template>

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

  const { permissions } = useUserInfoHook();
  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 collapseList = ref<DisposalManagementCollapseListResponse<DisposalManagementTableResponse>[]>([]);
  const disposalManagementPermissions = ref(false);

  const { getDisasterLevelDepts, originalDisasterLevelDepts } = useDeptInfoHook();
  const { tableConfig } = useTableConfig(DISPOSAL_MANAGEMENT_TABLE_COLUMNS, DISPOSAL_MANAGEMENT_TABLE_OPTIONS, false);

  const activeId = ref<number | null>(null);

  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 handleCollapseToggle = (itemId: number) => {
    if (activeId.value === itemId) {
      activeId.value = null;
    } else {
      activeId.value = itemId;
    }
  };

  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;

    if (collapseList.value.length > 0) {
      activeId.value = collapseList.value[0].id;
    } else {
      activeId.value = null;
    }
  };

  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.taskStage === TASK_STAGE.TO_BE_REPORTED || item.taskStage === TASK_STAGE.OVERDUE,
      ) && 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, taskName: string) => {
    router.push({
      name: Task_RouterName,
      query: {
        id,
        taskName,
      },
    });
  };

  const handleViewItem = (id: number, deptId: number, taskName: string) => {
    router.push({
      name: Table_RouterName,
      params: {
        id,
      },
      query: {
        deptId,
        taskName,
      },
    });
  };
  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 () => {
    getDisasterLevelDepts();
    await getDisposalData();
    await getDisposalTableData();
    disposalManagementPermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.DISPOSAL_MANAGEMENT),
    );
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/views/disaster/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;
    }
  }
  .principal-container--div {
    display: flex;
    flex-wrap: wrap;
  }
</style>
