<template>
  <Dialog custom-show type="lg" title="灾害评估" hide-footer @close="closeDialog">
    <!-- 表格组件 -->
    <div class="common-table">
      <div class="table-header">
        <div class="td">行政区划</div>
        <div class="td">受灾人数（人）</div>
        <div class="td">失踪人数（人）</div>
        <div class="td">死亡人数（人）</div>
        <div class="td">紧急转移（人）</div>
        <div class="td">直接经济损失（万元）</div>
      </div>
      <div v-for="(item, index) in fixedTableData" :key="index" class="tr">
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text" :title="item.area_name">{{ item.area_name }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <el-input-number v-if="isEditing" v-model="item.injuries" class="custom-input" :min="0" />
            <div v-else class="area_name-text">{{ item.injuries }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <el-input-number v-if="isEditing" v-model="item.missing" class="custom-input" :min="0" />
            <div v-else class="area_name-text">{{ item.missing }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <el-input-number v-if="isEditing" v-model="item.deaths" class="custom-input" :min="0" />
            <div v-else class="area_name-text">{{ item.deaths }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <el-input-number v-if="isEditing" v-model="item.transfer" class="custom-input" :min="0" />
            <div v-else class="area_name-text">{{ item.transfer }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <el-input-number v-if="isEditing" v-model="item.economic_loss" class="custom-input" :min="0" />
            <div v-else class="area_name-text">{{ item.economic_loss }}</div>
          </div>
        </div>
      </div>
      <!-- 合计行 -->
      <div class="tr total-row">
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text">合计</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text">{{ total.injuries }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text">{{ total.missing }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text">{{ total.deaths }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text">{{ total.transfer }}</div>
          </div>
        </div>
        <div class="td">
          <div class="area_name-box">
            <div class="area_name-text">{{ total.economic_loss }}</div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="!isEditing" class="btn-box">
      <div class="btn" @click="toggleEdit">
        <div class="text">编辑</div>
      </div>
    </div>
    <div v-if="isEditing" style="display: flex">
      <div class="btn-box">
        <div class="common-btn" @click="cancelEdit">
          <div class="text">取消</div>
        </div>
        <div class="common-btn-primary" @click="saveEdit">
          <div class="text">保存</div>
        </div>
      </div>
    </div>
  </Dialog>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import BigNumber from 'bignumber.js';
import { getEventCasualties, uploadCasualties } from '@/api/duty/eventing';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 固定的行政区域列表
const fixedRegions = ['茂名市', '茂南区', '电白区', '化州市', '高州市', '信宜市'];

// 编辑状态
const isEditing = ref(false);
// 保存编辑前的原始数据
const originalData = ref([]);

// 原始数据
const tableData = ref([]);

// 固定区域的数据
const fixedTableData = ref([]);

// 合并固定区域和数据的函数
const mergeDataWithFixedRegions = () => {
  fixedTableData.value = fixedRegions.map((region) => {
    // 查找是否有该区域的数据
    const foundData = tableData.value.find((item) => item.area_name === region);

    // 如果有数据则使用，否则使用默认值0
    return (
      foundData || {
        area_name: region,
        injuries: 0,
        missing: 0,
        deaths: 0,
        transfer: 0,
        economic_loss: 0
      }
    );
  });
};

// 计算合计值
const total = computed(() => {
  // 初始化 BigNumber 对象
  const init = {
    injuries: new BigNumber(0),
    missing: new BigNumber(0),
    deaths: new BigNumber(0),
    transfer: new BigNumber(0),
    economic_loss: new BigNumber(0)
  };

  // 使用 reduce 累加
  const sums = fixedTableData.value.reduce((acc, item) => {
    return {
      injuries: acc.injuries.plus(new BigNumber(item.injuries || 0)),
      missing: acc.missing.plus(new BigNumber(item.missing || 0)),
      deaths: acc.deaths.plus(new BigNumber(item.deaths || 0)),
      transfer: acc.transfer.plus(new BigNumber(item.transfer || 0)),
      economic_loss: acc.economic_loss.plus(new BigNumber(item.economic_loss || 0))
    };
  }, init);

  // 返回格式化后的结果
  return {
    injuries: sums.injuries.toFormat(0),
    missing: sums.missing.toFormat(0),
    deaths: sums.deaths.toFormat(0),
    transfer: sums.transfer.toFormat(0),
    economic_loss: sums.economic_loss.toFormat(2)
  };
});

// 切换编辑状态
const toggleEdit = () => {
  // 进入编辑时保存当前数据快照
  originalData.value = JSON.parse(JSON.stringify(fixedTableData.value));
  isEditing.value = true;
};

const saveEdit = () => {
  isEditing.value = false;
  // 保存数据到tableData
  // tableData.value = fixedTableData.value.filter(
  //   (item) => item.injuries !== 0 || item.missing !== 0 || item.deaths !== 0 || item.transfer !== 0 || item.economic_loss !== 0
  // );
  uploadCasualties({'event_id': props.eventId, 'eventCasualties': fixedTableData.value}).then((res)=>{
    proxy?.$modal.msgSuccess(res.msg);
  })
};

const cancelEdit = () => {
  // 恢复编辑前的数据
  fixedTableData.value = JSON.parse(JSON.stringify(originalData.value));
  isEditing.value = false;
};

const emit = defineEmits(['update:show']);
const closeDialog = () => {
  emit('update:show', false);
};

const props = defineProps<{
  eventId?: string;
}>();
onMounted(() => {
  // tableData.value = [
  //   {
  //     area_name: '',
  //     injuries: 0,
  //     missing: 0,
  //     deaths: 0,
  //     transfer: 0,
  //     economic_loss: 0
  //   }
  // ];
  // mergeDataWithFixedRegions();
  getEventCasualties({ event_id: props.eventId }).then((res) => {
    tableData.value = res.data;
    mergeDataWithFixedRegions();
  });
});
</script>

<style scoped lang="scss">
.common-table {
  .total-row {
    font-weight: bold;
  }

  .table-header,
  .tr {
    display: flex;
    height: 130px;
    .td {
      flex: 1;
      padding: 8px;

      .area_name-box {
        .area_name-text {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .edit-input {
          width: 100%;
          padding: 4px;
          border: 1px solid #ccc;
          border-radius: 4px;
          text-align: center;
        }
        :deep(.el-input-number) {
          width: 60%;
        }
      }
    }
  }
}
.custom-input {
  :deep(.el-input-number__increase) {
    background-color: #ffffff;
    width: 50px;
    font-size: 25px;
  }
  :deep(.el-input-number__decrease) {
    background-color: #ffffff;
    width: 50px;
    font-size: 25px;
  }
}
.btn-box {
  flex: 1;
  //height: 421px;
  display: flex;
  justify-content: center;
  align-items: center;
  .btn {
    width: 361px;
    height: 136px;
    background: url('@/assets/images/emergencyCommandMap/communication/btn.png') no-repeat;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    .icon1,
    .icon2,
    .icon3 {
      margin-right: 20px;
      margin-top: 10px;
    }
    .icon1 {
      width: 64px;
      height: 67px;
      background: url('@/assets/images/emergencyCommandMap/communication/icon1.png') no-repeat;
    }
    .icon2 {
      width: 64px;
      height: 65px;
      background: url('@/assets/images/emergencyCommandMap/communication/icon2.png') no-repeat;
    }
    .icon3 {
      width: 64px;
      height: 63px;
      background: url('@/assets/images/emergencyCommandMap/communication/icon3.png') no-repeat;
    }
    .text {
      color: #fff;
      font-size: 38px;
    }
  }
}
</style>
