<template>
  <div class="emergency-exercise-container">
    <div class="container-title">
      <span class="line"></span>
      <span class="title">应急演练</span>
    </div>
    <YearSelector
      class="year-selector"
      :years="yearsList"
      :default-year="yearSelected"
      @year-change="handleYearChange"
    />
    <div class="container-exercise" v-loading="loading">
      <div class="exercise-tabs">
        <div
          class="exercise-tab"
          :class="{ 'active-tab': item.itemCode === activeTab }"
          v-for="item in drillScopeDice"
          :key="item.itemCode"
          @click="handleChangeTab(item.itemCode)"
        >
          {{ getDrillScope(item.itemCode) }}
        </div>
      </div>
      <div class="exercise-counts">
        <div>
          <span>年度演练计划</span>
          <span class="exercise-count">{{
            exerciseCountList.find((item) => item.drillScope === activeTab)?.drillPlanCount
          }}</span>
        </div>
        <div>
          <span>已完成演练</span>
          <span class="exercise-count">{{
            exerciseCountList.find((item) => item.drillScope === activeTab)?.completedDrillCount
          }}</span>
        </div>
      </div>
      <div class="exercise-list">
        <div v-if="exercisesList.length === 0" class="exercise-list-no-data">暂无演练计划</div>
        <div class="exercise-item" v-for="item in exercisesList" :key="item.id" @click="handleJumpToDetail(item.id)">
          <div class="exercise-info">
            <span class="exercise-title">{{ item.drillContent }}</span>
            <div class="exercise-info-content">
              <span class="exercise-date">{{
                item.status === EMERGENCY_DRILL_STATUS.COMPLETE ? item.drillTime : item.dueCompleteTime
              }}</span>
              <div class="exercise-label" v-if="item.status === EMERGENCY_DRILL_STATUS.COMPLETE">
                <div class="label-content">已演练</div>
              </div>
            </div>
          </div>
          <div class="exercise-dept">{{
            mergeAndFormat(item.responsibleDeptNameList, item.coordinateDeptNameList)
          }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import YearSelector from './YearSelector.vue';
  import { useEmergencyDrillHook } from '@/views/emergency/emergency-drill/hook';
  import { EMERGENCY_DRILL_STATUS } from '@/views/emergency/emergency-drill/constants';
  import {
    QueryEmergencyDrillOverviewRes,
    DrillPlanByScopeList,
    DrillPlanList,
    getOverviewEmergencyExercise,
  } from '@/api/emergency-overview';

  const { drillScopeDice, getDrillScopeDict, getDrillScope } = useEmergencyDrillHook();

  const router = useRouter();

  const loading = ref(true);
  const emergencyExerciseData = ref<QueryEmergencyDrillOverviewRes[]>([]);
  const exerciseCountList = ref<DrillPlanByScopeList[]>([]);
  const exercisesList = ref<DrillPlanList[]>([]);

  const yearsList = ref<number[]>([]);
  const yearSelected = ref<number | undefined>();

  const activeTab = ref<string>();

  const handleChangeTab = (tabCode: string) => {
    activeTab.value = tabCode;
  };

  const handleYearChange = (year: number) => {
    yearSelected.value = year;
  };

  function mergeAndFormat(A: string = '', B: string = ''): string {
    if (!A) A = '[]';
    if (!B) B = '[]';

    const partsA = A.replace(/[\[\]]/g, '')
      .split(',')
      .map((s) => s.trim())
      .filter((s) => s.length > 0);

    const partsB = B.replace(/[\[\]]/g, '')
      .split(',')
      .map((s) => s.trim())
      .filter((s) => s.length > 0);

    return [...partsA, ...partsB].join('、');
  }

  const handleJumpToDetail = (id: number) => {
    router.push({
      path: '/emergency-management/emergency-drill/emergency-drill-plan-view',
      query: {
        id: id,
      },
    });
  };

  watch(
    [() => yearSelected.value, () => activeTab.value],
    (newValues) => {
      loading.value = true;
      exerciseCountList.value =
        emergencyExerciseData.value.find((item) => item.year === newValues[0])?.drillPlanByScopeList || [];
      exercisesList.value =
        exerciseCountList.value.find((item) => item.drillScope === newValues[1])?.drillPlanList || [];
      loading.value = false;
    },
    { immediate: true },
  );

  onMounted(async () => {
    await getDrillScopeDict();
    activeTab.value = drillScopeDice.value[0].itemCode;
    getOverviewEmergencyExercise().then((res) => {
      emergencyExerciseData.value = res.drillPlanByYearList;
      if (emergencyExerciseData.value && emergencyExerciseData.value.length > 0) {
        yearsList.value = emergencyExerciseData.value.map((item) => item.year);
        yearSelected.value = emergencyExerciseData.value[emergencyExerciseData.value.length - 1].year;
      }
    });
  });
</script>

<style scoped lang="scss">
  .container-title {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 16px;
    color: #000000;

    .line {
      width: 3px;
      height: 16px;
      background: #1777ff;
      margin-right: 10px;
    }

    .title {
      margin-right: 12px;
    }
  }

  .emergency-exercise-container {
    padding: 10px 0;
    position: relative;

    .year-selector {
      position: absolute;
      top: 11px;
      right: 16px;
    }

    .container-exercise {
      width: 100%;
      height: calc(100% - 34px);
      margin-top: 10px;

      .exercise-tabs {
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.65);

        .exercise-tab {
          cursor: pointer;
          padding: 0 10px;
          position: relative;
        }

        .exercise-tab:hover {
          color: #1890ff;
        }

        .active-tab {
          color: #1890ff;
          font-weight: 500;
        }

        .active-tab::after {
          content: '';
          display: block;
          width: 28px;
          height: 2px;
          background-color: #1777ff;
          border-radius: 2px;
          position: absolute;
          left: 50%;
          margin-top: 5px;
          transform: translateX(-50%);
        }
      }

      .exercise-counts {
        display: flex;
        justify-content: space-around;
        align-items: center;
        margin: 20px 7px 10px 7px;
        padding: 12px 0px;
        background: #e7f1ff;
        border-radius: 8px;
        font-weight: 400;
        font-size: 16px;
        color: rgba(0, 0, 0, 0.65);

        .exercise-count {
          color: #1777ff;
          margin-left: 4px;
        }
      }

      .exercise-list {
        width: 100%;
        height: calc(100% - 102px - 10px);
        margin-top: 10px;
        padding: 0 16px;
        overflow-y: auto;

        .exercise-item {
          margin-bottom: 16px;
          padding-bottom: 18px;
          border-bottom: 1px solid #e8e8e8;
          cursor: pointer;

          .exercise-info {
            display: flex;
            justify-content: space-between;
            position: relative;

            .exercise-title {
              font-weight: 500;
              font-size: 16px;
              color: #333333;
            }

            .exercise-info-content {
              display: flex;
              align-items: center;
            }

            .exercise-date {
              font-weight: 400;
              font-size: 14px;
              color: #666666;
            }

            .exercise-label {
              width: 46px;
              height: 16px;
              border-radius: 3px;
              background: #52c41a;
              font-size: 10px;
              color: #ffffff;
              margin-left: 5px;
              transform: skew(-15deg, 0deg);

              .label-content {
                transform: skew(15deg, 0deg);
                text-align: center;
                line-height: 16px;
              }
            }
          }

          .exercise-dept {
            font-weight: 400;
            font-size: 14px;
            color: #666666;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .exercise-item:hover {
          .exercise-title,
          .exercise-dept {
            color: #1890ff;
          }
        }

        .exercise-item:last-child {
          margin-bottom: 0;
        }
      }

      .exercise-list-no-data {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #666666;
      }
    }
  }
</style>
