<template>
  <div class="empty-container" v-if="!disasterLossDetailList?.reportTaskList.length">
    <img :src="Empty" alt="暂无数据" />
    <span>暂无上报数据</span>
  </div>
  <div class="info-container" v-else>
    <template v-for="reportTask in disasterLossDetailList?.reportTaskList" :key="reportTask.reportDeptId">
      <CollapseItem
        v-if="reportTask.lossRecordList.length"
        :name="`上报单位：${reportTask.reportDeptName}`"
        :isActive="activeId === reportTask.reportDeptId"
        opacityIcon
        @toggle="handleCollapseToggle(reportTask.reportDeptId)"
      >
        <template #view-operation>
          <div class="rectification-info">
            <span class="num">{{ reportTask.lossRecordCount }}</span>
            <span class="info-text">条，整改完成{{ reportTask.fixFinishCount }}条</span>
          </div>
        </template>
        <template #right-header>
          <span class="collapse-item__header--right">
            {{ activeId === reportTask.reportDeptId ? '收起' : '展开' }}
          </span>
        </template>
        <template #main-table>
          <div class="rectification-table">
            <section class="damaged-list-container">
              <DamagedList
                :damagedList="reportTask.lossRecordList"
                :active-id="activeTaskId || reportTask.lossRecordList[0].fixTaskId"
                @update:activeId="handleActiveTask"
              />
            </section>
            <section class="disaster-info-container">
              <DisasterInfo :LossReportItemFormData="lossRecordListInfo" rectification v-if="lossRecordListInfo" />
              <Rectification
                v-if="lossRecordListInfo?.fixRecordList"
                :rectification-list="lossRecordListInfo?.fixRecordList"
                :rectification-dept-name="lossRecordListInfo?.responsibleDeptName"
                :rectification-responsible-user-list="rectificationResponsibleUserList"
                :rectification-priority="lossRecordListInfo?.priority"
              />
            </section>
          </div>
        </template>
      </CollapseItem>
      <NoCollapseItem v-else :name="`上报单位：${reportTask.reportDeptName}`">
        <template #view-operation>
          <div class="rectification-info">
            <span class="num">{{ reportTask.lossRecordCount }}</span>
            <span class="info-text">条，上报时间：{{ reportTask.reportTime }}</span>
          </div>
        </template>
      </NoCollapseItem>
    </template>
  </div>
</template>

<script setup lang="ts">
  import { useRoute } from 'vue-router';
  import { onMounted, ref } from 'vue';
  import CollapseItem from './CollapseItem.vue';
  import NoCollapseItem from './NoCollapseItem.vue';
  import DamagedList from './DamagedList.vue';
  import DisasterInfo from './DisasterInfo.vue';
  import Rectification from './Rectification.vue';
  import { useDisasterControlHook } from '../hook';
  import type { PersonGroupItem } from '@/types/person-group/type';
  import type { ReportTaskListDetail, LossRecordListDetail, OverviewLossRecordInfo } from '@/types/disaster-control';
  import { queryUserInfoByIds } from '@/api/system/person-group';
  import Empty from '@/assets/images/empty@1X.png';

  const route = useRoute();
  const handleTaskId = Number(route.query.id);
  const { getDisasterLossDetailList, disasterLossDetailList } = useDisasterControlHook();
  const activeId = ref<number | null>(null);
  const activeTaskId = ref<number | null>(null);
  const handleCollapseToggle = (itemId: number) => {
    if (activeId.value === itemId) {
      activeId.value = null;
    } else {
      activeId.value = itemId;
      reportTaskListInfo.value = reportTaskList.value.find((item) => item.reportDeptId === activeId.value);
      if (!reportTaskListInfo.value) return;
      lossRecordList.value = reportTaskListInfo.value?.lossRecordList;
      activeTaskId.value = lossRecordList.value[0].fixTaskId;
      lossRecordListInfo.value = lossRecordList.value.find((item) => item.fixTaskId === activeTaskId.value);
      getFixUserList(lossRecordListInfo.value?.fixPrincipals);
      getFixRecordUser();
    }
  };
  const handleActiveTask = (fixTaskId: number) => {
    activeTaskId.value = fixTaskId;
    if (!lossRecordList.value.length) return;
    lossRecordListInfo.value = lossRecordList.value.find((item) => item.fixTaskId === activeTaskId.value);
    getFixUserList(lossRecordListInfo.value?.fixPrincipals);
    getFixRecordUser();
  };
  const reportTaskList = ref<ReportTaskListDetail[]>([]);
  const lossRecordList = ref<LossRecordListDetail[]>([]);
  const reportTaskListInfo = ref<ReportTaskListDetail>();
  const lossRecordListInfo = ref<LossRecordListDetail>();
  const rectificationResponsibleUserList = ref<PersonGroupItem[]>([]);
  const getFixUserList = async (userIds: string | undefined) => {
    if (!userIds) return;
    const ids = JSON.parse(userIds);
    const res = await queryUserInfoByIds(ids);
    rectificationResponsibleUserList.value = res;
  };
  const getFixRecordUser = () => {
    const fixRecordList = lossRecordListInfo.value?.fixRecordList;
    if (fixRecordList?.length) {
      const updatedList = Promise.all(
        fixRecordList.map(async (item) => {
          if (!item.createdBy) return item;
          const res = await queryUserInfoByIds([item.createdBy]);
          return {
            ...item,
            createdByName: `${res[0].realname}（${res[0].staffNo}）`,
          };
        }),
      );
      updatedList.then((result) => {
        if (lossRecordListInfo.value) {
          lossRecordListInfo.value.fixRecordList = result;
        }
      });
    }
  };
  const overviewLossRecordInfo = () => {
    return {
      needToReportDeptCount: disasterLossDetailList.value?.needToReportDeptCount,
      reportedDeptCount: disasterLossDetailList.value?.reportedDeptCount,
      waitToReportDeptCount: disasterLossDetailList.value?.waitToReportDeptCount,
      overdueReportedDeptCount: disasterLossDetailList.value?.overdueReportedDeptCount,
      lossRecordCount: disasterLossDetailList.value?.lossRecordCount,
      fixedLossCount: disasterLossDetailList.value?.fixedLossCount,
      fixingLossCount: disasterLossDetailList.value?.fixingLossCount,
      waitToFixLossCount: disasterLossDetailList.value?.waitToFixLossCount,
    };
  };
  const emit = defineEmits<{
    (e: 'overviewLossRecordInfo', info: OverviewLossRecordInfo): void;
  }>();
  onMounted(async () => {
    await getDisasterLossDetailList({ handleTaskId });
    emit('overviewLossRecordInfo', overviewLossRecordInfo());
    if (!disasterLossDetailList.value?.reportTaskList.length) return;
    reportTaskList.value = disasterLossDetailList.value?.reportTaskList;
    activeId.value = reportTaskList.value[0].reportDeptId;
    reportTaskListInfo.value = reportTaskList.value.find((item) => item.reportDeptId === activeId.value);
    if (!reportTaskListInfo.value) return;
    lossRecordList.value = reportTaskListInfo.value?.lossRecordList;
    if (!lossRecordList.value.length) return;
    let index = 0;
    while (index < lossRecordList.value.length && !activeTaskId.value) {
      if (lossRecordList.value[index].fixTaskId) {
        activeTaskId.value = lossRecordList.value[index].fixTaskId;
      }
      index++;
    }
    lossRecordListInfo.value = lossRecordList.value.find((item) => item.fixTaskId === activeTaskId.value);
    getFixUserList(lossRecordListInfo.value?.fixPrincipals);
    getFixRecordUser();
  });
</script>

<style lang="scss" scoped>
  @use '../style/common.scss' as *;
  .empty-container {
    @include flex-center;
    flex-direction: column;
    gap: 8px;
    width: 100%;
    height: 100%;
  }
</style>
