<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">灾害损失记录明细</span>
    </header>
    <TaskInfoSection :task-name="disasterLossDetailList?.handleTaskName" @export-loss-detail="exportLossDetail" />
    <main class="safety-platform-container__main">
      <CollapseItem
        v-for="reportTask in disasterLossDetailList?.reportTaskList"
        :key="reportTask.reportDeptId"
        :name="`上报单位：${reportTask.reportDeptName}`"
        :isActive="activeId === reportTask.reportDeptId"
        @toggle="handleCollapseToggle(reportTask.reportDeptId)"
        opacityIcon
      >
        <template #view-operation>
          <div class="rectification-info">
            <span class="num">{{ reportTask.lossRecordCount }}</span>
            <span>条，整改完成{{ 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"
                @update:activeId="handleActiveTask"
                @update:activeReportRecordId="handleActiveReportRecordId"
              />
            </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>
    </main>
  </div>
</template>

<script lang="ts" setup>
  import { useRoute, useRouter } from 'vue-router';
  import { onMounted, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import TaskInfoSection from './src/components/TaskInfoSection.vue';
  import CollapseItem from './src/components/CollapseItem.vue';
  import DamagedList from './src/components/DamagedList.vue';
  import DisasterInfo from './src/components/DisasterInfo.vue';
  import Rectification from './src/components/Rectification.vue';
  import { useDisasterControlHook } from './src/hook';
  import { useUserInfoHook } from '../hooks';
  import { exportLossRecord } from './src/util';
  import type { PersonGroupItem } from '@/types/person-group/type';
  import type { ReportTaskListDetail, LossRecordListDetail } from '@/types/disaster-control';
  import { queryUserInfoByIds } from '@/api/system/person-group';

  const router = useRouter();
  const route = useRoute();
  const handleTaskId = Number(route.params.id);
  const {
    fixTaskId,
    deptId,
    reportRecordId,
    type: viewType,
  } = route.query as unknown as {
    fixTaskId: number;
    deptId: number;
    reportRecordId: number;
    type: 'task' | 'item';
  };
  const activeTaskId = ref<number>(Number(fixTaskId));
  const activeReportRecordId = ref<number>(Number(reportRecordId));

  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 handleActiveReportRecordId = (reportRecordId: number) => {
    activeReportRecordId.value = reportRecordId;
  };
  const { id: fixerId } = useUserInfoHook();
  const { getDisasterLossDetailList, disasterLossDetailList } = useDisasterControlHook();

  const exportLossDetail = async () => {
    if (!disasterLossDetailList.value) return;
    const name = disasterLossDetailList.value?.handleTaskName;
    const params = {
      handleTaskId,
      userIdByLossFix: fixerId,
    };
    await exportLossRecord(params, name);
    ElMessage.success(`导出${name}损失明细成功`);
  };
  const activeId = 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 rectificationResponsibleUserList = ref<PersonGroupItem[]>([]);
  const reportTaskList = ref<ReportTaskListDetail[]>([]);
  const lossRecordList = ref<LossRecordListDetail[]>([]);
  const reportTaskListInfo = ref<ReportTaskListDetail>();
  const lossRecordListInfo = ref<LossRecordListDetail>();
  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;
        }
      });
    }
  };
  onMounted(async () => {
    await getDisasterLossDetailList({
      handleTaskId,
      userIdByLossFix: fixerId,
    });
    if (!disasterLossDetailList.value?.reportTaskList.length) return;
    reportTaskList.value = disasterLossDetailList.value?.reportTaskList;
    activeId.value = deptId ? Number(deptId) : reportTaskList.value[0].reportDeptId;
    reportTaskListInfo.value = reportTaskList.value.find((item) => item.reportDeptId === activeId.value);
    if (!reportTaskListInfo.value) return;
    lossRecordList.value = reportTaskListInfo.value?.lossRecordList;
    if (isNaN(activeTaskId.value)) {
      activeTaskId.value = lossRecordList.value[0].fixTaskId;
    }
    lossRecordListInfo.value = lossRecordList.value.find((item) => item.fixTaskId === activeTaskId.value);
    getFixUserList(lossRecordListInfo.value?.fixPrincipals);
    getFixRecordUser();
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  @use './src/style/common.scss' as *;
</style>
