<template>
  <div class="hospital-service">
    <div class="admin-page-card">
      <!-- 顶部筛选条 -->
      <div class="filter-bar">
        <div class="filter-left">
          <span class="filter-label">医院名称</span>
          <el-select v-model="filters.keyword" placeholder="全部医院" clearable filterable style="width: 220px">
            <el-option v-for="h in hospitals" :key="h.id" :label="h.name" :value="h.name" />
          </el-select>
          <el-button class="blue-sign" type="primary" plain @click="onSearch">查询</el-button>
        </div>
        <div class="filter-right">
          <div class="month-switcher">
            <el-button class="switch-btn" plain @click="prevMonth">
              <div class="inner">
                < </div>
            </el-button>
            <span class="month-label">{{ currentMonthLabel }}</span>
            <el-button class="switch-btn" plain @click="nextMonth">
              <div class="inner">></div>
            </el-button>
          </div>
          <el-button class="monthly-view-btn" type="primary" @click="monthlyVisible = true">
            <el-icon>
              <Calendar />
            </el-icon>
            <span>月视图</span>
          </el-button>
        </div>
      </div>

      <!-- 维保列表 -->
      <el-table class="admin-table service-table" :data="list" v-loading="loading" stripe
        header-cell-class-name="admin-table-header-cell">
        <el-table-column prop="hospitalName" label="医院名称" min-width="140" show-overflow-tooltip />
        <el-table-column label="客户分类" width="100">
          <template #default="{ row }">
            <div class="cat-tag" :class="`cat-${row.customerCategory}`">
              {{ row.customerCategory || "—" }}类
            </div>
          </template>
        </el-table-column>
        <el-table-column label="维保截止日期" width="120">
          <template #default="{ row }">{{ formatDate(row.maintenanceEnd) }}</template>
        </el-table-column>
        <el-table-column prop="managerName" label="客户经理" width="80" show-overflow-tooltip />
        <el-table-column label="续保完成" width="90" align="center">
          <template #default="{ row }">
            <img style="width:16px;height:16px;" v-if="row.renewal === 'no'" src="@/assets/image/admin/orders/no.svg"
              alt="">
            <img style="width:16px;height:16px;" v-if="row.renewal === 'yes'" src="@/assets/image/admin/orders/yes.svg"
              alt="">
          </template>
        </el-table-column>
        <el-table-column label="合同签署" width="90" align="center">
          <template #default="{ row }">
            <img style="width:16px;height:16px;" v-if="row.contractSigned === 'no'" src="@/assets/image/admin/orders/no.svg"
              alt="">
            <img style="width:16px;height:16px;" v-if="row.contractSigned === 'yes'" src="@/assets/image/admin/orders/yes.svg"
              alt="">
          </template>
        </el-table-column>
        <el-table-column label="款项支付" width="90" align="center">
          <template #default="{ row }">
            <img style="width:16px;height:16px;" v-if="row.paymentPaid === 'no'" src="@/assets/image/admin/orders/no.svg"
              alt="">
            <img style="width:16px;height:16px;" v-if="row.paymentPaid === 'yes'" src="@/assets/image/admin/orders/yes.svg"
              alt="">
          </template>
        </el-table-column>
        <el-table-column label="回访状态" width="90" align="center">
          <template #default="{ row }">
            <img style="width:16px;height:16px;" v-if="row.visited === 'no'" src="@/assets/image/admin/orders/no.svg"
              alt="">
            <img style="width:16px;height:16px;" v-if="row.visited === 'yes'" src="@/assets/image/admin/orders/yes.svg"
              alt="">
          </template>
        </el-table-column>
        <el-table-column label="服务操作" min-width="415" class-name="op-cell">
          <template #default="{ row }">
            <div class="op-buttons">
              <el-button class="op-btn" plain @click="openRecord(row, 'call')">
                <el-icon>
                  <img style="width:16px;height:16px;" src="@/assets/image/admin/orders/dhhf.svg" alt="">
                </el-icon>电话回访
              </el-button>
              <el-button class="op-btn" plain @click="openRecord(row, 'inspection')">
                <el-icon>
                  <img style="width:16px;height:16px;" src="@/assets/image/admin/orders/xcxj.svg" alt="">
                </el-icon>现场巡检
              </el-button>
              <el-button class="op-btn" plain @click="openRecord(row, 'training')">
                <el-icon>
                  <img style="width:16px;height:16px;" src="@/assets/image/admin/orders/pxjl.svg" alt="">
                </el-icon>培训记录
              </el-button>
              <el-button class="op-btn" plain @click="openRecord(row, 'gift')">
                <el-icon>
                  <img style="width:16px;height:16px;" src="@/assets/image/admin/orders/jnpjl.svg" alt="">
                </el-icon>纪念品记录
              </el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button class="detail-btn cyan-sign smaller" type="primary" plain @click="openDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <!-- 本月到期提醒 -->
    <div class="expiring-section admin-page-card">
      <div class="expiring-title border-title">
        本月到期提醒
      </div>
      <div class="expiring-grid" v-loading="expiringLoading">
        <el-empty v-if="!expiringLoading && expiringList.length === 0" description="暂无即将到期的维保" :image-size="80" />
        <div v-for="(h, idx) in expiringList" :key="h.hospitalId || idx" class="expiring-card">
          <div class="ex-head">
            <span class="ex-name">{{ h.hospitalName }}</span>
            <span v-if="Number(h.daysUntilExpiry) <= 30" class="ex-urgent-tag">紧急</span>
          </div>
          <div class="ex-row">
            <span class="ex-lbl">到期日期：</span>
            <span class="ex-val">{{ formatDate(h.maintenanceEnd) }}</span>
          </div>
          <div class="ex-row">
            <span class="ex-lbl">剩余天数：</span>
            <span class="ex-val">{{ formatExpiringDays(h.daysUntilExpiry) }}</span>
          </div>
          <div class="ex-tags">
            <div v-if="h.renewal !== 'yes'" class="warn-tag">未续保</div>
            <div v-if="h.paymentPaid !== 'yes'" class="warn-tag">未付款</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 维保详情/编辑弹窗 -->
    <MaintenanceDetailDialog v-model="detailVisible" :hospital-id="currentHospitalId" @saved="onSearch" />

    <!-- 服务记录弹窗（电话回访/现场巡检/培训/纪念品） -->
    <ServiceRecordDialog v-model="recordVisible" :type="recordType" :hospital-id="currentHospitalId"
      :hospital-name="currentHospitalName" />

    <!-- 客户服务月视图弹窗 -->
    <MonthlyViewDialog v-model="monthlyVisible" />
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { Calendar, Phone, View, Reading, Present } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { getAdminExpiring, getAdminMaintenance } from "@/service/modular/admin";
import { useHospitalStore } from "@/stores/api/hospital";
import MaintenanceDetailDialog from "./components/MaintenanceDetailDialog.vue";
import ServiceRecordDialog from "./components/ServiceRecordDialog.vue";
import MonthlyViewDialog from "./components/MonthlyViewDialog.vue";

const list = ref([]);
const loading = ref(false);
const expiringLoading = ref(false);
const expiringList = ref([]);

// 通用医院列表（来自 Pinia store，多页面共享缓存）
const hospitalStore = useHospitalStore();
const hospitals = computed(() => hospitalStore.list);

const filters = reactive({ keyword: undefined });

// 月份切换（用于服务操作按钮列对齐设计稿，实际不参与筛选）
const currentMonth = ref(dayjs());
const currentMonthLabel = computed(() => currentMonth.value.format("YYYY年M月"));
const prevMonth = () => {
  currentMonth.value = currentMonth.value.subtract(1, "month");
  loadList();
};
const nextMonth = () => {
  currentMonth.value = currentMonth.value.add(1, "month");
  loadList();
};

const formatDate = (v) => (v ? dayjs(v).format("YYYY-MM-DD") : "—");

const formatExpiringDays = (n) => {
  const v = Number(n);
  return `${v}天`;
};

const loadList = async () => {
  loading.value = true;
  try {
    const res = await getAdminMaintenance({
      page: 1,
      pageSize: 200,
      keyword: filters.keyword || undefined,
      year: currentMonth.value.year(),
      month: currentMonth.value.month() + 1,
    });
    list.value = res?.list || [];
  } finally {
    loading.value = false;
  }
};

const loadExpiring = async () => {
  expiringLoading.value = true;
  try {
    const res = await getAdminExpiring();
    expiringList.value = Array.isArray(res) ? res : res?.list || [];
  } finally {
    expiringLoading.value = false;
  }
};

const onSearch = () => loadList();
const onReset = () => {
  filters.hospitalId = undefined;
  loadList();
};

// 详情弹窗
const detailVisible = ref(false);
const currentHospitalId = ref("");
const openDetail = (row) => {
  currentHospitalId.value = row.hospitalId;
  detailVisible.value = true;
};

// 服务记录弹窗
const recordVisible = ref(false);
const recordType = ref("call");
const currentHospitalName = ref("");
const openRecord = (row, type) => {
  currentHospitalId.value = row.hospitalId;
  currentHospitalName.value = row.hospitalName || "";
  recordType.value = type;
  recordVisible.value = true;
};

// 月视图弹窗
const monthlyVisible = ref(false);

onMounted(() => {
  hospitalStore.ensureLoaded();
  loadList();
  loadExpiring();
});
</script>

<style scoped lang="scss">
.hospital-service {
  .filter-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 12px;

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

      .filter-label {
        font-size: 14px;
        color: #1d2129;
      }
    }

    .filter-right {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .month-switcher {
      display: inline-flex;
      align-items: center;
      overflow: hidden;
      background: #FFFFFF;
      border-radius: 8px 8px 8px 8px;
      border: 1px solid #E0E0E0;

      .switch-btn {
        border: none;
        border-radius: 0;
        padding: 6px 8px !important;
        min-height: 32px;
        background: transparent;
        color: #606266;

        .inner {
          width: 24px;
          height: 24px;
          background: #EDEDED;
          border-radius: 8px 8px 8px 8px;
          line-height: 24px;
          text-align: center;
          color: #BCBCBC;
        }

        &:hover {
          background: #f5f7fa;
        }
      }

      .month-label {
        padding: 0 12px;
        font-size: 14px;
        color: #1d2129;
        min-width: 100px;
        text-align: center;
      }
    }

    .monthly-view-btn {
      display: inline-flex;
      align-items: center;
      gap: 4px;
    }
  }
}

.cat-tag {
  width: 48px;
  height: 30px;
  border-radius: 8px 8px 8px 8px;
  line-height: 30px;
  text-align: center;
  font-weight: 500;
  font-size: 14px;

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

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

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

:deep(.op-cell) {
  .op-buttons {
    display: flex;
    flex-wrap: nowrap;
    gap: 5px;
  }

  .op-btn {

    border-radius: 8px 8px 8px 8px;
    border: 1px solid #E0E0E0;
    font-weight: 400;
    font-size: 14px;
    color: #1D2129;
    line-height: 18px;
    background: #fff;
    font-weight: 400;
    padding: 6px 10px !important;
    margin: 0;

    .el-icon {
      margin-right: 2px;
    }
  }
}


.expiring-section {
  margin-top: 24px;

  .expiring-title {
    margin-bottom: 16px;
  }

  .expiring-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 24px;
  }

  .expiring-card {
    background: #FFFFFF;
    border-radius: 12px 12px 12px 12px;
    border: 1px solid #E0E0E0;
    padding: 16px;

    .ex-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 6px;

      .ex-name {
        font-weight: 600;
        font-size: 16px;
        color: #1D2129;
      }

      .ex-urgent-tag {
        background: #ff383c;
        color: #fff;
        padding: 2px 8px;
        font-weight: 500;
        font-size: 14px;
        color: #FFFFFF;
        line-height: 18px;
        border-radius: 8px 8px 8px 8px;
      }
    }

    .ex-row {
      display: flex;
      align-items: center;
      gap: 4px;
      color: #666666;
      line-height: 18px;
      font-weight: 400;
      font-size: 14px;
      margin-bottom: 6px;

      .ex-lbl {
        color: #999999;
      }
    }

    .ex-tags {
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #EFEFEF;
      display: flex;
      gap: 12px;

      .warn-tag {
        background: #FFEBEC;
        border-radius: 8px 8px 8px 8px;
        color: #ff383c;
        font-weight: 500;
        font-size: 14px;
        color: #FF383C;
        line-height: 18px;
        padding: 2px 8px;
      }
    }
  }
}
</style>

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