<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">
          <BasicSearch
            :searchConfig="DISPOSAL_RECTIFICATION_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #priority>
              <el-select v-model="searchData.priority" placeholder="请选择优先级" class="custom-select">
                <el-option
                  v-for="item in priorityDice"
                  :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">
            <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="item.tableData[0].disasterReportRecordDetailList.length ? '' : '暂无损失记录'"
                    placement="top"
                    effect="light"
                    :popper-class="
                      item.tableData[0].disasterReportRecordDetailList.length ? 'custom-tooltip--opacity0' : ''
                    "
                  >
                    <img
                      :src="ViewDocument"
                      :class="[
                        'collapse-item__icon',
                        { 'collapse-item__icon--disabled': !item.tableData[0].disasterReportRecordDetailList.length },
                      ]"
                      @click="handleViewTask(item.id, 'task')"
                    />
                  </el-tooltip>
                </template>
                <template #main-table>
                  <div class="mian-table-container">
                    <BasicTable
                      :tableData="item.tableData[0].disasterReportRecordDetailList"
                      :tableConfig="tableConfig"
                    >
                      <template #affectedArea="scope">
                        <div class="affected-area-container">
                          <span>{{ scope.row.buildingNo }}-{{ scope.row.floorNo }}-{{ scope.row.roomNo }}</span>
                        </div>
                      </template>
                      <template #affectedItems="scope">
                        <el-tooltip
                          :content="scope.row.affectedItems"
                          placement="top-start"
                          effect="light"
                          v-if="scope.row.affectedItems"
                        >
                          <div class="affected-items-container">
                            <span>{{ scope.row.affectedItems }}</span>
                          </div>
                        </el-tooltip>
                        <span v-else>--</span>
                      </template>
                      <template #responsibleDeptName="scope">
                        <span v-if="scope.row.responsibleDeptName">{{ scope.row.responsibleDeptName }}</span>
                        <span v-else>--</span>
                      </template>
                      <template #priority="scope">
                        <span v-if="scope.row.priority">{{ getPriority(scope.row.priority) }}</span>
                        <span v-else>--</span>
                      </template>
                      <template #fixStatus="scope">
                        <span v-if="scope.row.fixStatus">{{ getfixStatus(scope.row.fixStatus) }}</span>
                        <span v-else>--</span>
                      </template>
                      <template #action="scope">
                        <div class="action-container--div">
                          <ActionButton
                            text="查看"
                            @click="
                              handleViewTask(item.id, 'item', scope.row.fixTaskId, scope.row.deptId, scope.row.id)
                            "
                          />
                          <ActionButton
                            text="去整改"
                            @click="
                              handleRectification(
                                scope.row.id,
                                item.id,
                                scope.row.fixTaskId,
                                item.tableData[0].disasterReportRecordDetailList,
                              )
                            "
                          />
                          <ActionButton
                            text="添加整改人"
                            v-if="scope.row.isFixPrincipal"
                            @click="handleAddFixer(scope.row.id, scope.row.fixerList)"
                          />
                        </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>
    <el-dialog v-model="userInfo" title="添加整改人" destroy-on-close>
      <InspectorSelect
        :customUserList="currentTaskInspectorList"
        @cancel="userInfo = false"
        @submit="handleAddFixerSubmit"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { onMounted, reactive, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import BasicSearch from '@/components/BasicSearch.vue';
  import CollapseItem from './src/components/CollapseItem.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import InspectorSelect from '@/views/disaster/components/InspectorSelect.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useDisasterControlHook } from './src/hook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { getfixStatus } from './src/util';
  import type { PersonGroupItem } from '@/types/person-group/type';
  import type {
    DisposalManagementCollapseListResponse,
    LossRecordTableResponse,
    disasterReportRecordDetailListResponse,
  } from '@/types/disaster-control';
  import { getDisasterControlCollapseData, getLossRecordTableData, addFixer } from '@/api/disaster-control';
  import { queryUserInfoByIds } from '@/api/system/person-group';
  import {
    DISPOSAL_RECTIFICATION_SEARCH_CONFIG,
    LOSS_RECORD_TABLE_COLUMNS,
    DISPOSAL_MANAGEMENT_TABLE_OPTIONS,
  } from './src/config';
  import { DEFAULT_PAGE_SIZE, DISASTER_CONTROL_PAGE_SIZE_CONFIG, FIX_STATUS } from './src/constant';
  import { DEFAULT_PAGINATION_LAYOUT } from '@/constant/pagination';
  import Empty from 'assets/images/empty@1X.png';
  import ViewDocument from './src/svg/view-document.svg';

  const { id: userId } = useUserInfoHook();

  const { getPriority, getPriorityDict, priorityDice } = useDisasterControlHook();

  const searchData = reactive({
    priority: null,
    fixStatus: null,
    isLoss: 1,
  });

  const userInfo = ref(false);
  const currentTaskInspectorList = ref<PersonGroupItem[]>([]);

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

  const collapseLoading = ref(false);
  const collapseList = ref<DisposalManagementCollapseListResponse<LossRecordTableResponse>[]>([]);

  const activeId = ref<number | null>(null);
  const { tableConfig } = useTableConfig(LOSS_RECORD_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 = () => {
    searchData.isLoss = 1;
    getDisposalTableData();
  };

  const taskIds = ref<number[]>([]);
  const router = useRouter();

  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: {
        fixerId: userId,
      },
    });
    collapseList.value = res.records.map((item) => ({
      ...item,
      tableData: [
        {
          handleTaskId: item.id,
          disasterReportRecordDetailList: [],
        },
      ],
    }));
    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 res = await getLossRecordTableData({
      handleTaskIds: taskIds.value,
      fixerId: userId,
      ...searchData,
    });
    collapseList.value.forEach((item) => {
      item.tableData = res.filter((tableItem) => tableItem.handleTaskId === item.id);
    });
    tableConfig.loading = false;
  };

  const currentTaskId = ref<number>();
  const handleAddFixer = async (id: number, fixerList: string) => {
    currentTaskId.value = id;
    const userIds = JSON.parse(fixerList) || [];
    if (!userIds.length) return;
    const res = await queryUserInfoByIds(userIds);
    currentTaskInspectorList.value = res.map((user) => {
      return {
        ...user,
        checked: true,
      };
    });
    userInfo.value = true;
  };

  const handleAddFixerSubmit = async (ids: number[]) => {
    if (!currentTaskId.value) return;
    await addFixer(currentTaskId.value, ids);
    ElMessage.success('添加整改人成功');
    userInfo.value = false;
    getDisposalTableData();
  };

  const defaultRouterName = 'disaster-control-disposal-rectification-item';
  const handleRectification = (
    id: number,
    handleTaskId: number,
    fixTaskId: number,
    detailList: disasterReportRecordDetailListResponse[],
  ) => {
    const rectificationIds = detailList
      .filter((item) => item.fixStatus === FIX_STATUS.TO_BE_RECTIFIED)
      .map((item) => ({ id: item.id, fixTaskId: item.fixTaskId }));
    sessionStorage.setItem('rectificationIds', JSON.stringify(rectificationIds));
    router.push({
      name: defaultRouterName,
      params: {
        id,
      },
      query: {
        handleTaskId,
        fixTaskId,
      },
    });
  };

  const handleViewTask = (
    handleTaskId: number,
    type: 'task' | 'item',
    fixTaskId?: number,
    deptId?: number,
    reportRecordId?: number,
  ) => {
    router.push({
      name: 'disaster-control-disposal-rectification-item-detail',
      params: {
        id: handleTaskId,
      },
      query: {
        fixTaskId,
        deptId,
        reportRecordId,
        type,
      },
    });
  };

  onMounted(async () => {
    getPriorityDict();
    await getDisposalData();
    await getDisposalTableData();
  });
</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 './src/style/collapse.scss' as *;
  @use './src/style/common.scss' as *;
  @use '@/views/disaster/style/disaster.scss' as *;
  $collapse-container-height-default: calc(68vh - 43px);
  .collapse-container {
    height: $collapse-container-height-default;
    max-height: $collapse-container-height-default;
  }
</style>
