<template>
  <el-dialog :model-value="modelValue" class="monthly-view-dialog" top="5vh" :close-on-click-modal="false"
    destroy-on-close @update:model-value="(v) => $emit('update:modelValue', v)" @open="onOpen">
    <div class="body-wrap">
      <div class="body-header">
        <span class="body-title">客户服务月视图</span>
        <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="closeDialog" />
      </div>
      <div class="month-wrap">
        <div class="filter-bar">
          <div class="filter-left">
            <div class="year-select">
              <span class="filter-label">选择年份</span>
              <el-date-picker v-model="year" type="year" format="YYYY年" value-format="YYYY" style="width: 130px"
                @change="onSearch" />
            </div>
            <el-button class="year-btn" :class="{ active: yearOffset === -1 }" plain
              @click="jumpYear(-1)">去年</el-button>
            <el-button class="year-btn" :class="{ active: yearOffset === 0 }" plain @click="jumpYear(0)">今年</el-button>
            <el-button class="year-btn" :class="{ active: yearOffset === 1 }" plain @click="jumpYear(1)">明年</el-button>
          </div>
        </div>

        <div v-loading="loading" class="month-grid">
          <div v-for="m in 12" :key="m" class="month-card">
            <div class="month-head">
              <span class="month-name">{{ m }}月</span>
              <span
                v-if="monthList[m - 1]?.hospitals.some(item => item.daysUntilExpiry >= 0 && item.daysUntilExpiry <= 30)"
                class="urgent-tag">紧急</span>
              <span class="month-stats">
                <span class="num">{{ monthList[m - 1]?.expiringCount ?? 0 }}</span>家医院到期
                <span class="sep">|</span>
                已续费
                <span class="num renewed">{{ monthList[m - 1]?.renewedCount ?? 0 }}</span>家
                <span class="sep">|</span>
                未续费
                <span class="num not-renewed">{{ monthList[m - 1]?.notRenewedCount ?? 0 }}</span>家
              </span>
            </div>
            <div class="month-body">
              <template v-if="monthList[m - 1]?.hospitals?.length">
                <div v-for="h in monthList[m - 1].hospitals" :key="h.hospitalId" class="hospital-card">
                  <div class="h-top">
                    <span class="h-name">{{ h.hospitalName }}</span>
                    <span class="cat-tag" :class="`cat-${h.customerCategory}`">
                      {{ h.customerCategory }}类
                    </span>
                    <span v-if="h.renewal === 'yes'" class="renewal-name">✓已续费</span>
                  </div>
                  <div class="h-row">
                    <span class="h-lbl">到期：</span>
                    <span class="h-val">{{ formatDate(h.maintenanceEnd) }}</span>
                    <span class="days-tag" :class="daysTagClass(h.daysUntilExpiry)">
                      {{ formatDays(h.daysUntilExpiry) }}
                    </span>
                  </div>
                  <div class="h-row">
                    <span class="h-lbl">客户经理：</span>
                    <span class="h-val">{{ h.managerName || "—" }}</span>
                  </div>
                </div>
              </template>
              <div v-else class="empty-month">本月无到期医院</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import dayjs from "dayjs";
import { getAdminMonthlyView } from "@/service/modular/admin";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
});

const emit = defineEmits(["update:modelValue"]);

const loading = ref(false);
const year = ref(String(dayjs().year()));
const monthList = ref([]);

const yearOffset = computed(() => Number(year.value) - dayjs().year());

const formatDate = (v) => (v ? dayjs(v).format("M/D") : "—");

const formatDays = (n) => {
  const v = Number(n);
  if (v === null || v === undefined || isNaN(v)) return "";
  if (v <= 0) return `已过期${-v}天`;
  if (v < 100) return `还有${v}天`;
  return `${v}天后`;
};

const daysTagClass = (n) => {
  const v = Number(n);
  if (v <= 0) return "expired";
  if (v < 100) return "soon";
  return "far";
};

const loadData = async () => {
  loading.value = true;
  try {
    const res = await getAdminMonthlyView({ year: Number(year.value) });
    const list = Array.isArray(res) ? res : res?.list || [];
    const arr = new Array(12).fill(null);
    list.forEach((item) => {
      const idx = Number(item.month) - 1;
      if (idx >= 0 && idx < 12) arr[idx] = item;
    });
    // 兼容每个月份对象结构
    monthList.value = arr.map((it) => {
      if (!it) return { expiringCount: 0, renewedCount: 0, notRenewedCount: 0, hospitals: [] };
      return {
        ...it,
        hospitals: it.hospitals || [],
      };
    });
  } finally {
    loading.value = false;
  }
};

const onSearch = () => loadData();

const jumpYear = (offset) => {
  year.value = String(dayjs().year() + offset);
  loadData();
};

const closeDialog = () => emit("update:modelValue", false);

const onOpen = () => {
  year.value = String(dayjs().year());
  loadData();
};

watch(
  () => props.modelValue,
  (v) => {
    if (v) onOpen();
  },
);
</script>

<style lang="scss">
@use "@/assets/style/admin-common.scss" as *;

.monthly-view-dialog {
  width: 1522px;
  max-width: 90vw;
  padding: 0;

  .month-wrap {
    border-radius: 12px;
    border: 1px solid #E0E0E0;
    overflow: hidden;

    .filter-bar {
      display: flex;
      align-items: center;
      height: 70px;
      background: #F9FAFF;
      border-bottom: 1px solid #E0E0E0;
      padding-left: 24px;

      .filter-left {
        display: flex;
        align-items: center;

        .year-select {
          display: flex;
          align-items: center;
          gap: 8px;

          .filter-label {
            font-weight: 400;
            font-size: 14px;
            color: #1D2129;
          }
        }

        .year-btn {
          border: none !important;
          background-color: #fff !important;
          color: #666666;
          margin-left: 24px;

          &:hover,
          &.active {
            background: #3289FB !important;
            color: #fff;
          }
        }
      }
    }

    .month-grid {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      padding: 14px 21px;
      gap: 8px;

      .month-card {
        background: #fff;
        border: 1px solid #E0E0E0;
        border-radius: 12px;
        overflow: hidden;

        .month-head {
          display: flex;
          flex-wrap: nowrap;
          align-items: center;
          background: #F9FAFF;
          border-bottom: 1px solid #E0E0E0;
          white-space: nowrap;
          padding: 0 10px;
          height: 46px;

          .month-name {
            font-weight: normal;
            font-size: 16px;
            color: #1D2129;
            margin-right: 6px;
          }

          .urgent-tag {
            display: inline-block;
            width: 39px;
            height: 18px;
            background: #FF383C;
            border-radius: 8px 8px 8px 8px;
            line-height: 18px;
            text-align: center;
            font-weight: 500;
            font-size: 12px;
            color: #FFFFFF;
          }

          .month-stats {
            font-weight: normal;
            font-size: 14px;
            color: #666;
            flex: 0;
            margin-left: auto;

            .sep {
              margin: 0 2px;
              color: #c0c4cc;
            }

            .num {
              color: #3289FB;
            }
          }
        }

        .month-body {
          flex: 1;
          display: flex;
          flex-direction: column;
          padding: 14px 21px;
          gap: 4px;
          height: 200px;
          overflow-y: auto;

          .hospital-card {
            background: #FBFBFB;
            border-radius: 12px 12px 12px 12px;
            border: 1px solid #EFEFEF;
            padding: 10px;

            .h-top {
              display: flex;
              align-items: center;
              gap: 8px;
              margin-bottom: 8px;

              .h-name {
                font-weight: 600;
                font-size: 14px;
                color: #1D2129;
                max-width: 14em;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
              }

              .cat-tag {
                width: 32px;
                height: 18px;
                border-radius: 4px 4px 4px 4px;
                display: inline-block;
                line-height: 18px;
                text-align: center;
                font-weight: 400;
                font-size: 12px;
                color: #FFFFFF;

                &.cat-A {
                  background: #3289FB;
                }

                &.cat-B {
                  background: #34C759;
                }

                &.cat-C {
                  background: #FF8D28;
                }
              }

              .renewal-name {
                width: 60px;
                height: 18px;
                background: #00C3D0;
                border-radius: 4px 4px 4px 4px;
                line-height: 18px;
                text-align: center;
                font-weight: 400;
                font-size: 12px;
                color: #FFFFFF;
              }
            }

            .h-row {
              display: flex;
              align-items: center;
              line-height: 1.1;
              margin-bottom: 4px;
              font-weight: 400;
              font-size: 14px;
              color: #1D2129;

              .h-lbl {
                color: #909399;
                margin-right: 2px;
              }


              .days-tag {
                display: inline-block;
                margin-left: auto;
                padding: 2px;
                background: #FFEBEC;
                border-radius: 4px 4px 4px 4px;
                font-weight: 400;
                font-size: 12px;
                color: #FF383C;

                &.soon {
                  background: #FFEFE2;
                  color: #FF8D28;
                }

                &.far {
                  background: #E8FFEE;
                  color: #34c759;
                }

                &.expired {
                  background: #ffebec;
                  color: #ff383c;
                }
              }
            }

            .h-row+.h-row {
              margin-bottom: 0;
            }
          }

          .empty-month {
            flex: 1;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 400;
            font-size: 14px;
            color: #BCBCBC;
          }
        }
      }
    }
  }


}
</style>
