<template>
  <div class="home">
    <nav-bar />

    <!-- 就诊须知弹窗 -->
    <van-dialog
      v-model="showNotice"
      :title="noticeTitle"
      :overlay="false"
      show-cancel-button="false"  
      confirm-text="我已阅读"
      @confirm="handleConfirmNotice"
      class="notice-dialog"
      close-on-click-overlay="false"
      :before-close="handleBeforeClose"
      style="top: 50% !important;"
    >
      <div class="notice-content" v-html="noticeContent"></div>
    </van-dialog>

    <!-- 科室索引列表 -->
    <van-index-bar
      v-if="!showNotice"
      :index-list="indexList"
      class="custom-index-bar"
    >
      <div v-for="letter in indexList" :key="letter">
        <van-index-anchor :index="letter" />
        <van-cell
          v-for="item in groupedDepartments[letter]"
          :key="item.DEPARTCODE"
          :title="item.DEPARTNAME"
          is-link
          @click="handleGuke(item)"
        />
      </div>
    </van-index-bar>
  </div>
</template>

<script>
// 脚本部分保持不变
import { pinyin } from 'pinyin-pro';
import { apiGetAppointDeptMark, getUserCategory, getMedicalNotice,isBlack } from "@/request/api.js";
import { Dialog, Toast, IndexBar, IndexAnchor, Cell } from "vant";

export default {
  components: {
    [IndexBar.name]: IndexBar,
    [IndexAnchor.name]: IndexAnchor,
    [Cell.name]: Cell
  },
  data() {
    return {
      list: [],
      yuyue: {
        t: "",
        k: "",
        e: "",
        z: 2,
      },
      groupedDepartments: {},
      indexList: [],
      currentLetter: '',
      showNotice: true,
      noticeTitle: "挂号就诊须知",
      noticeContent: ""
    };
  },
  created() {
    // 检查是否需要显示就诊须知
    const hasReadNotice = sessionStorage.getItem('hasReadNotice');
    if (hasReadNotice) {
      this.showNotice = false;
    }
  },
  mounted() {
   // 根据 showNotice 状态决定是否加载数据
  if (!this.showNotice) {
    this.getList();
  } else {
    this.loadMedicalNotice();
  }
  this.getUserCategoryToHis();
},
  methods: {
     handleConfirmNotice() {
      this.showNotice = false;
      this.getList();
      // 记录用户已阅读就诊须知
      sessionStorage.setItem('hasReadNotice', 'true');
    },
    loadMedicalNotice() {
      getMedicalNotice({type:"挂号"}).then(res => {
        this.noticeTitle = res.data.title || "挂号就诊须知";
        this.noticeContent = res.data.content || this.getDefaultNotice();
      })
    },
    getDefaultNotice() {
      return `
        <p>一、挂号时间及门诊开放时间</p>
        <p>1、挂号时间：</p>
        <p class="indent">8:00—12:00 14:00—17:30</p>
        <p>2、就诊时间：</p>
        <p class="indent">上午：8:00—12:00</p>
        <p class="indent">下午：14:00—17:30</p>
        
        <p>二、实名制就诊须知</p>
        <p>1、我院实行实名制就诊，禁止使用他人身份信息就诊，信息不符医生有权拒绝接诊。</p>
        <p>2、病友可持身份证、社会保障卡、护照等有效证件办理挂号、缴费等业务。</p>
        <p>3、新生婴儿等特殊情况可在挂号窗口办理临时诊疗卡。</p>
        
        <p>三、挂号须知</p>
        <p>1、挂号方式：</p>
        <p class="indent">（1）当日挂号：现场窗口、微信公众号；</p>
        <p class="indent">（2）预约挂号：微信公众号、现场窗口（可提前6天）。</p>
        <p>2、现场挂号地点：门诊大厅收费窗口。</p>
        <p>3、外伤、急危重症患者请至急诊科挂号。</p>
        <p>4、一次挂号仅限当次有效，次日复诊需重新挂号。</p>
      `;
    },
    handleBeforeClose(action, done) {
      if (action === 'confirm') done();
    },
    getUserCategoryToHis() {
    isBlack().then(res => {
      if (res.data == 1 || res.data == 3) {
        Toast("您已被列入黑名单，无法使用挂号服务。如有疑问请联系医院公众号。");
        this.$router.replace({ path: "/" });
         return;
      }
    })
      let card = sessionStorage.getItem("card");
      if (!card) {
        setTimeout(() => {
          Toast("未查询到用户身份，请先绑定就诊人！！");
          this.$router.push({ path: "/Member_jzr" });
        }, 500);
        return;
      }
      let cardJson = JSON.parse(card);
      getUserCategory({
        queryCode: cardJson.patientId,
        queryType: 0,
      }).then(res => {
        cardJson.chargetype = res.data;
        sessionStorage.setItem("card", JSON.stringify(cardJson));
      }).catch(err => {
        Toast(err.message);
      });
    },
    getList() {
      let params = {
        searchType: '2',
        departCode: '',
        departLevel: '',
        departType: '0',
      };
      apiGetAppointDeptMark(params).then(res => {
        this.list = [];
        try {
          let jsonObj = this.$x2js.xml2js(res.data);
          let jsonObj2 = this.$x2js.xml2js(
            jsonObj.Envelope.Body.MOP_OutpRegisterDeptQueryResponse
              .MOP_OutpRegisterDeptQueryResult
          );
          let tempList = jsonObj2.response.data.data_row || [];
          tempList.forEach(e => {
            if (e.DEPARTLEVEL === '1') this.list.push(e);
          });
          this.groupDepartments();
        } catch (error) {
          Toast("解析科室数据失败");
        }
      }).catch(err => {
        Toast("获取科室列表失败");
      });
    },
    groupDepartments() {
  const groups = {};
  this.list.forEach(item => {
    // 过滤掉包含"军人"和"小儿科门诊"的科室
    if (item.DEPARTNAME && (item.DEPARTNAME.includes('军人') || item.DEPARTNAME.includes('小儿科门诊'))) {
      return; // 跳过这些科室
    }
    
    let firstLetter = '';
    if (item.DEPARTNAME) {
      firstLetter = pinyin(item.DEPARTNAME, {
        pattern: 'first',
        toneType: 'none'
      }).charAt(0).toUpperCase();
    }
    if (!/^[A-Z]$/.test(firstLetter)) firstLetter = '#';
    if (!groups[firstLetter]) groups[firstLetter] = [];
    groups[firstLetter].push(item);
  });
  const sortedLetters = Object.keys(groups).sort((a, b) => {
    if (a === '#') return 1;
    if (b === '#') return -1;
    return a.localeCompare(b);
  });
  sortedLetters.forEach(letter => {
    groups[letter].sort((a, b) => a.DEPARTNAME.localeCompare(b.DEPARTNAME));
  });
  this.groupedDepartments = groups;
  this.indexList = sortedLetters;
},
    handleGuke(val) {
      this.yuyue.DeptCode = val.DEPARTCODE;
      this.yuyue.DeptName = val.DEPARTNAME;
      sessionStorage.setItem("yuyue", JSON.stringify(this.yuyue));
      // this.$router.push({ path: "/xzmz2" });
      this.$router.push({ path: "/Guke" });
    }
  }
};
</script>

<style scoped lang="scss">
.home {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
  overflow: hidden;
}

// 核心：强制隐藏取消按钮，确保只显示一个按钮
::v-deep .notice-dialog {
  .van-dialog__wrap {
    padding: 0 0.3rem;
  }
  .van-dialog {
    width: 100%;
    max-width: 750px;
    border-radius: 0.2rem;
    overflow: hidden;
  }
  
  // 标题样式
  .van-dialog__title {
    font-size: 0.42rem !important;
    color: #333;
    padding: 0.4rem 0.4rem 0.2rem;
    font-weight: 600;
    text-align: center;
  }
  
  // 内容区域样式
  .van-dialog__content {
    padding: 0.3rem 0.4rem;
    max-height: 60vh;
    overflow-y: auto;
    box-sizing: border-box;
    
    .notice-content {
      p {
        font-size: 0.35rem !important;
        color: #666;
        line-height: 1.6;
        margin: 0.2rem 0;
        text-align: justify;
      }
      p.indent {
        padding-left: 0.4rem;
        text-align: left;
      }
    }
  }
  
  // 按钮区域：强制隐藏取消按钮，确认按钮居中
  .van-dialog__footer {
    padding: 0.2rem 0.4rem 0.4rem;
    display: flex;
    justify-content: center;  /* 按钮居中 */
    background-color: #fff;
    
    // 强制隐藏取消按钮（解决默认显示问题）
    .van-dialog__cancel {
      display: none !important;
    }
    
    // 确认按钮样式
    .van-dialog__confirm {
      width: 80%;
      height: 0.9rem;
      line-height: 0.9rem;
      font-size: 0.34rem;
      background-color: #46c3b0;
      color: #fff;
      border-radius: 0.45rem;
    }
  }
}

// 滚动条美化
::v-deep .van-dialog__content::-webkit-scrollbar {
  width: 6px;
}
::v-deep .van-dialog__content::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 3px;
}

// 索引栏样式（不变）
::v-deep .custom-index-bar {
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

  .van-index-bar__index-list {
    right: 4px;
    padding: 10px 0;
    background-color: rgba(212, 212, 212, 0.806);
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .van-index-bar__index {
    width: 0.5rem;
    height: 0.5rem;
    line-height: 0.5rem;
    font-size: 0.4rem;
    color: #666;
    margin: 0.2rem 0;
    text-align: center;

    &.van-index-bar__index--active {
      color: #46c3b0;
      font-weight: bold;
      transform: scale(1.1);
    }
  }

  .van-index-anchor {
    height: 0.8rem;
    line-height: 0.8rem;
    padding: 0 0.3rem;
    background-color: #f0f0f0;
    color: #888;
    font-size: 0.28rem;
    font-weight: 500;
  }

  .van-cell {
    margin: 0;
    border-bottom: 1px solid #eee;
    background-color: #fff;
    .van-cell__title {
      font-size: 0.32rem;
    }
    .van-cell__right-icon {
      display: none !important;
    }
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>