<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">{{ name }}</span>
    </header>
    <main class="safety-platform-container__main">
      <div class="complete-time">
        <div class="section-title">应急处置信息</div>
        <span style="color: red">*</span>
        <span>处置完成时间：</span>
        <el-date-picker
          v-model="formParam.completeTime"
          type="datetime"
          placeholder="选择处置完成时间"
          :clearable="false"
        />
        <div class="required-field-tip" v-if="requiredFieldTipVisible">*请选择应急处置完成时间！</div>
      </div>
      <div class="loss-table">
        <div class="section-title">损失情况</div>
        <el-button type="primary" :icon="Plus" @click="addLossItemRecordVisible = true">添加损失物品</el-button>
        <el-button type="primary" @click="linkLossReportVisible = true">关联损失上报</el-button>
        <BasicTable :tableData="lossItemRecords" :tableConfig="tableConfig" class="loss-item-table">
          <template #lossItemLocation="scope">
            <span>{{ scope.row.buildingNo }}号楼{{ scope.row.floorNo }}层{{ scope.row.roomNo }}</span>
          </template>
          <template #safetyLevel="scope">
            <span>{{ getSafetyLevel(scope.row.safetyLevel) }}</span>
          </template>
          <template #action="scope">
            <ActionButton text="删除" @click="handleDeleteLossItemRecord(scope.row)" />
          </template>
        </BasicTable>
      </div>
      <div>
        <div class="section-title">总结与改进建议</div>
        <div class="suggestion-text">
          <div class="suggestion-title">总结与改进建议：</div>
          <el-input
            v-model="formParam.suggestion"
            style="min-width: 240px"
            :autosize="{ minRows: 4 }"
            type="textarea"
            placeholder="请输入总结与改进建议"
          />
        </div>
      </div>
    </main>
    <footer class="safety-platform-container__footer">
      <el-button @click="handleSaveInfo">保存</el-button>
      <el-button type="primary" @click="handleUpdateStatus">提交</el-button>
    </footer>
  </div>
  <AssociateLossReport
    v-if="linkLossReportVisible"
    @submit="handleLinkLossReport"
    @cancel="linkLossReportVisible = false"
  />
  <AddLossItemRecord
    v-if="addLossItemRecordVisible"
    @submit="handleAddLossItemRecord"
    @cancel="addLossItemRecordVisible = false"
  />
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, ElInput, ElButton, ElDatePicker } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useDisasterControlHook } from '@/views/disaster/disaster-control/src/hook';
  import {
    LossRecordItem,
    getEmergencyProcedureCompleteInfo,
    addLossItemRecord,
    associateLossItemRecord,
    deleteLossItemRecord,
    updateEmergencyProcedure,
  } from '@/api/emergency-procedure';
  import { EMERGENCY_PROCEDURE_STATUS } from './constant';
  import { PROCEDURE_COMPLETE_LOSS_ITEM_TABLE_COLUMNS, PROCEDURE_LIST_TABLE_OPTIONS } from './config';
  import AssociateLossReport from './components/AssociateLossReport.vue';
  import AddLossItemRecord from './components/AddLossItemRecord.vue';

  const { tableConfig } = useTableConfig(PROCEDURE_COMPLETE_LOSS_ITEM_TABLE_COLUMNS, PROCEDURE_LIST_TABLE_OPTIONS);
  const { getSafetyLevel, getSafetyLevelDict } = useDisasterControlHook();

  const route = useRoute();
  const router = useRouter();
  const id = Number(route.params.id);
  const name = ref('应急处置完成');

  const requiredFieldTipVisible = ref(false);

  const lossItemRecords = ref<LossRecordItem[]>([]);
  const linkLossReportVisible = ref(false);
  const addLossItemRecordVisible = ref(false);

  const formParam = reactive({
    completeTime: '',
    suggestion: '',
  });

  watch(
    () => formParam.completeTime,
    (newValue) => {
      if (newValue) requiredFieldTipVisible.value = false;
    },
  );

  const handleAddLossItemRecord = (addItem, responsibleDeptName) => {
    addLossItemRecord({ ...addItem, handleTaskId: id, responsibleDeptName: responsibleDeptName }).then(() => {
      ElMessage({
        message: '添加成功',
        type: 'success',
      });
      addLossItemRecordVisible.value = false;
      getLossItemRecords();
    });
  };

  const handleLinkLossReport = (taskId: number) => {
    associateLossItemRecord({ emergencyHandleTaskId: id, disasterHandleTaskId: taskId }).then(() => {
      ElMessage({
        message: '关联成功',
        type: 'success',
      });
      linkLossReportVisible.value = false;
      getLossItemRecords();
    });
  };

  const handleDeleteLossItemRecord = (record: LossRecordItem) => {
    deleteLossItemRecord(record.id).then(() => {
      ElMessage({
        message: '删除成功',
        type: 'success',
      });
      getLossItemRecords();
    });
  };

  const handleSaveInfo = () => {
    if (!formParam.completeTime) {
      requiredFieldTipVisible.value = true;
      return;
    }
    updateEmergencyProcedure({
      id: id,
      completeTime: formParam.completeTime,
      suggestion: formParam.suggestion,
    }).then(() => {
      ElMessage({
        message: '信息已保存',
        type: 'success',
      });
    });
  };

  const handleUpdateStatus = () => {
    if (!formParam.completeTime) {
      requiredFieldTipVisible.value = true;
      return;
    }
    updateEmergencyProcedure({
      id: id,
      status: EMERGENCY_PROCEDURE_STATUS.HASFINISHED,
      completeTime: formParam.completeTime,
      suggestion: formParam.suggestion,
    }).then(() => {
      ElMessage({
        message: '信息已提交',
        type: 'success',
      });
      router.back();
    });
  };

  const getLossItemRecords = async () => {
    tableConfig.loading = true;
    const response = await getEmergencyProcedureCompleteInfo(id);
    formParam.completeTime = response.completeTime;
    formParam.suggestion = response.suggestion;
    lossItemRecords.value = response.lossRecords || [];
    tableConfig.loading = false;
  };

  onMounted(() => {
    getLossItemRecords();
    getSafetyLevelDict();
  });
</script>

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

  .safety-platform-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8px !important;
  }

  .safety-platform-container__main {
    .section-title {
      font-size: 18px;
      font-weight: 600;
      color: #000;
      margin-bottom: 16px;
    }

    .required-field-tip {
      color: red;
      margin: 10px 0 0 120px;
      font-size: 12px;
    }

    .loss-item-table {
      margin-top: 16px;
    }

    .complete-time,
    .loss-table {
      margin-bottom: 46px;
    }

    .suggestion-text {
      display: flex;

      .suggestion-title {
        width: 150px;
        margin-right: 8px;
      }
    }
  }
</style>
