<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="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>
          </Search>
        </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
                ref="collapseItemRef"
                v-for="item in collapseList"
                :key="item.id"
                :name="item.taskName"
                :defaultOpen="item.id === collapseList[0].id"
              >
                <template #viewOperation> <img :src="ViewDocument" class="collapse-item__icon" /> </template>
                <template #main-table>
                  <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" v-if="scope.row.fixStatus === FIX_STATUS.TO_BE_RECTIFIED">
                        <ActionButton text="查看" />
                        <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>
                      <div class="action-container" v-else>
                        <ActionButton text="查看" />
                        <ActionButton
                          text="去整改"
                          @click="
                            handleRectification(
                              scope.row.id,
                              item.id,
                              scope.row.fixTaskId,
                              item.tableData[0].disasterReportRecordDetailList,
                            )
                          "
                        />
                      </div>
                    </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>
    <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 Search from '@/views/disaster/components/Search.vue';
  import CollapseItem from './src/components/CollapseItem.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import InspectorSelect from '@/views/disaster/components/InspectorSelect.vue';
  import { nextTick, onMounted, reactive, ref } from 'vue';
  import { getDisasterControlCollapseData, getLossRecordTableData, addFixer } from '@/api/disaster-control';
  import type { disasterReportTaskInfoListResponse } from '@/types/disaster-control';
  import { DEFAULT_PAGE_SIZE, DISASTER_CONTROL_PAGE_SIZE_CONFIG, FIX_STATUS } from './src/constant';
  import type {
    DisposalManagementCollapseListResponse,
    LossRecordTableResponse,
    disasterReportRecordDetailListResponse,
  } from '@/types/disaster-control';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import {
    DISPOSAL_RECTIFICATION_SEARCH_CONFIG,
    LOSS_RECORD_TABLE_COLUMNS,
    DISPOSAL_MANAGEMENT_TABLE_OPTIONS,
  } from './src/config';
  import { getfixStatus } from './src/util';
  import { ACTIVE_STATUS } 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 { useDisasterControlHook } from './src/hook';
  import type { PersonGroupItem } from '@/types/person-group/type';
  import { queryUserInfoByIds } from '@/api/system/person-group';
  import { ElMessage } from 'element-plus';

  const { getPriority, getPriorityDict, priorityDice } = useDisasterControlHook();
  const collapseItemRef = ref<InstanceType<typeof CollapseItem>[]>([]);

  const searchData = reactive({
    priority: null,
    fixStatus: '',
    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 { 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 Table_RouterName = 'disaster-control-disposal-management-item';
  const handleEditDisposalManagement = (id: number) => {
    router.push({
      name: Table_RouterName,
      query: {
        id,
        operate: 'edit',
      },
    });
  };

  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,
          disasterReportRecordDetailList: [],
        },
      ],
    }));
    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 res = await getLossRecordTableData({
      handleTaskIds: taskIds.value,
      ...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) => item.id);
    sessionStorage.setItem('rectificationIds', JSON.stringify(rectificationIds));
    router.push({
      name: defaultRouterName,
      params: {
        id,
      },
      query: {
        handleTaskId,
        fixTaskId,
      },
    });
  };

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

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

  onMounted(async () => {
    getPriorityDict();
    await getDisposalData();
    await getDisposalTableData();
  });
</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: $collapse-container-height-default;
    max-height: $collapse-container-height-default;
  }
  .collapse-item__icon {
    width: 20px;
    &--disabled {
      cursor: not-allowed;
      opacity: 0.5;
    }
  }
</style>
