<template>
  <div class="home">
    <nav-bar/>
    <div class="bj"></div>
    <div class="jianjie">
      <h2><img :src="detail.img || require('@/assets/member_tx.png')"/></h2>
      <h3>
        {{ detail.name }}<span>&nbsp;&nbsp;&nbsp;{{ detail.label }}</span>
        <p>{{ detail.mname }}</p>
      </h3>
      <div class="yiguanzhu" v-if="flag" @click="cancle">
        <!--img class="img" src="../assets/chenggong.png"/-->
        <van-icon name="success"/>
        已关注
      </div>
      <div class="guanzhu" v-else @click="add">
        <!--img class="img" src="../assets/chenggong.png"/-->
        <van-icon name="plus"/>
        添加关注
      </div>
    </div>
    <div class="box1">
      <div class="container">
        <h2>坐诊信息</h2>
        <div v-if="groupedArr.length > 0">
          <div 
            v-for="(group, groupIndex) in groupedArr" 
            :key="groupIndex"
            class="department-schedule"
          >
            <h3 class="department-name">{{ group.deptName }}</h3>
            <div class="schedule-list">
              <div class="schedule-scroll">
                <div 
                  v-for="(item, index) in group.schedules" 
                  :key="index"
                  class="schedule-item"
                  @click="goToRegistration(item)"
                >
                    <div class="top-info">
                    <span>{{ formatWeekday(item.OUTPDATE) }} - {{ getTimeInterval(item.TIMEINTERVAL) }}</span>
                  </div>
                  <div class="date-info">
                    <span class="date">{{ formatDate(item.OUTPDATE) }}</span>
                  </div>
                  <div class="fee-info">
                    <span class="total-fee">挂号费: {{ calculateTotalFee(item) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div v-else class="no-schedule">
          暂无排班信息
        </div>
      </div>
    </div>
    <div class="box1">
      <div class="container">
        <h2>擅长</h2>
        <p v-html="detail.grsc"></p>
      </div>
    </div>
    <div class="box1">
      <div class="container">
        <h2>个人简介</h2>
        <div v-html="detail.info"></div>
      </div>
    </div>
    <!--    <div class="gao"></div>-->
    <!--    <div class="guahao" @click="guahao">去挂号<van-icon name="arrow" /></div>-->
    <!--  </div>-->
  </div>
</template>

<script>
// @ is an alias to /src
import {apiGetKsDoctorInfo, addConcern, cancelConcern, queryConcern,apiGetAppointHidsMark} from "@/request/api.js";
import {Toast} from "vant";

export default {
  components: {},
  mounted() {
    this.chargeType = JSON.parse(sessionStorage.getItem("card")).chargetype
    console.log(this.$route.meta.title);
    this.title = this.$route.meta.title;
    this.getData();
  },
  data() {
    return {
      active: 0,
      title: "",
      flag: false,
      checked: false,
      detail: {},
       yuyue: {},
      guanzhudoc: "",
      chargeType:"",
      jianjie: [
        {
          img: require("../assets/yisheng.jpg"),
          url: "Ysgh",
          name: "张树立",
          office: "骨科",
          grade: "主任医师、硕士生导师",
          jianj: "擅长：骨科各种危重症的诊断和抢救、以骨关节为",
        },
      ],
      arr: [], // 存储医生排班数据
      groupedArr: [] // 按科室分组后的排班数据
    };
  },
  methods: {
    // guahao() {
    //   Toast("挂号去");
    // },
    add() {

      let params = {
        patientId: this.detail.id
      }
      //给后端发送请求完成添加
      addConcern(params).then((res) => {
        console.log("打印返回结果")
        console.log(res)
      })
      // var docstr = sessionStorage.getItem("guanzhudoc");
      // sessionStorage.setItem("guanzhudoc", docstr + this.detail.id + ",");
      // this.guanzhudoc = sessionStorage.getItem("guanzhudoc");
      //console.log(this.guanzhudoc);
      this.flag = true;
      //更新关注的缓存
      // queryConcern().then(r => {//查找已经关注
      //   console.log(r.data)
      //   sessionStorage.setItem("guanzhudoc", r.data);
      // })
    },
    cancle() {
      let params = {
        patientId: this.detail.id
      }
      cancelConcern(params).then(res => {
        console.log(res)
      })
      // var docstrnew = sessionStorage.getItem("guanzhudoc");
      // sessionStorage.setItem(
      //     "guanzhudoc",
      //     docstrnew.replace(this.detail.id + ",", "")
      // );
      //console.log(this.guanzhudoc);
      this.flag = false;
      //更新关注的缓存
      // queryConcern().then(r => {//查找已经关注
      //   console.log(r.data)
      //   sessionStorage.setItem("guanzhudoc", r.data);
      // })
    },
    // 获取详情
    // 修复iOS时间格式问题，将YYYY-MM-DD转换为YYYY/MM/DD
    fixIOSDate(dateStr) {
      if (typeof dateStr === 'string') {
        return dateStr.replace(/-/g, '/');
      }
      return dateStr;
    },
    
    // 格式化日期为星期几
    formatWeekday(dateStr) {
      const fixedDateStr = this.fixIOSDate(dateStr);
      const date = new Date(fixedDateStr);
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return weekdays[date.getDay()];
    },
    
    // 格式化日期为月-日
    formatDate(dateStr) {
      const fixedDateStr = this.fixIOSDate(dateStr);
      const date = new Date(fixedDateStr);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      return `${month}月${day}日`;
    },
    
    // 获取时间段描述
    getTimeInterval(interval) {
      // 根据TIMEINTERVAL的值返回对应的时间段描述
      const intervalMap = {
        'AL': '全天',
        'AM': '上午',
        'PM': '下午'
      };
      return intervalMap[interval] || interval;
    },
    
    // 计算总挂号费（挂号费+诊疗费）
    calculateTotalFee(item) {
      const registrationFee = parseFloat(item.REGISTRATIONFEE) || 0;
      const clinicFee = parseFloat(item.CLINICFEE) || 0;
      return (registrationFee + clinicFee).toFixed(1);
    },
    
    // 跳转到挂号页面
    goToRegistration(data) {
      // 预留点击跳转功能，这里可以根据实际需求修改
      console.log('跳转到挂号页面', data);
   // 检查医生编码和姓名是否为空
      if (!data.DOCTORCODE || !data.DOCTORNAME) {
        Toast('当前科室暂无医生排班，不支持挂号，请线下缴费处询问');
        return;
      }

      this.yuyue.DoctorCode = data.DOCTORCODE;
      this.yuyue.DoctorName = data.DOCTORNAME;
      this.yuyue.DeptCode = data.DEPARTCODE;
      this.yuyue.DeptName = data.DEPTNAME;
      this.yuyue.DoctorTitle = data.DOCTORTITLE;
      this.yuyue.HisCostCode = data.HISCOSTCODE;
      this.yuyue.YBCostCode = data.YBCOSTCODE;
      this.yuyue.YBDept = data.YBDEPT;
      this.yuyue.YBDoc = data.YBDOC;
      this.yuyue.h = data.CLINICLABEL;
      this.yuyue.DoctorImg = this.detail.img
      // 设置选择的时间格式为YYYY-MM-DD（去除时间部分）
      this.yuyue.t = data.OUTPDATE.split(' ')[0];
      // 判断是否是今天
      const today = new Date().toISOString().split('T')[0];
      this.yuyue.z = this.yuyue.t === today ? 1 : 2;
      sessionStorage.setItem("yuyue", JSON.stringify(this.yuyue));
      this.$router.push({ path: "/Ysgh" });
    },
    
    getData() {
      apiGetKsDoctorInfo({
        id: this.$route.query.id,
      }).then((res) => {
        this.detail = res.data;
        console.log("医生信息",this.detail)

// 生成动态日期
const today = new Date();
const endDate = new Date(today);
endDate.setDate(today.getDate() + 7);

// 格式化日期为YYYY-MM-DD HH:mm:ss格式
const formatDate = (date, isEnd = false) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const time = isEnd ? '23:59:59' : '00:00:00';
  return `${year}-${month}-${day} ${time}`;
};

apiGetAppointHidsMark({
  DepartCode: 999999,
  DoctorCode: res.data.doct_code,
  StartTime: formatDate(today),
  EndTime: formatDate(endDate, true),
  chargeType: this.chargeType || "自费",
}).then(res=>{
  if (!res || !res.data) {
    console.error("获取排班信息失败: 响应数据为空");
    return;
  }
  
  try {
    let jsonObj = this.$x2js.xml2js(res.data);
    // console.log(jsonObj);
    
    // 添加空值检查
    if (!jsonObj || !jsonObj.Envelope || !jsonObj.Envelope.Body || 
        !jsonObj.Envelope.Body.MOP_OutpScheduleQueryResponse || 
        !jsonObj.Envelope.Body.MOP_OutpScheduleQueryResponse.MOP_OutpScheduleQueryResult) {
      console.error("XML结构不符合预期");
      return;
    }
    
    let jsonObj2 = this.$x2js.xml2js(
      jsonObj.Envelope.Body.MOP_OutpScheduleQueryResponse
        .MOP_OutpScheduleQueryResult
    );
    
    // 添加空值检查
    if (!jsonObj2 || !jsonObj2.response || !jsonObj2.response.data) {
      console.error("解析结果结构不符合预期");
      return;
    }
    
    console.log(jsonObj2);
    let arr = jsonObj2.response.data.data_row;
    
    // 过滤掉科室名称包含"军人"字样的排班信息
    let filteredArr = [];
    if (arr && Array.isArray(arr)) {
      filteredArr = arr.filter(item => {
        return !(item.DEPTNAME && item.DEPTNAME.includes('军人'));
      });
    } else if (arr && !(arr.DEPTNAME && arr.DEPTNAME.includes('军人'))) {
      // 如果只有一个对象且不包含"军人"字样
      filteredArr = [arr];
    }
    
    // 将过滤后的数据按科室分组
    let groupedData = {};
    if (filteredArr.length > 0) {
      filteredArr.forEach(item => {
        const deptName = item.DEPTNAME || '未知科室';
        if (!groupedData[deptName]) {
          groupedData[deptName] = [];
        }
        groupedData[deptName].push(item);
      });
    }
    
    // 转换为数组格式并对每个科室的排班按日期从前到后排序
    this.groupedArr = Object.keys(groupedData).map(deptName => {
      // 对同一科室的排班按时间顺序排序
      const sortedSchedules = groupedData[deptName].sort((a, b) => {
        // 使用fixIOSDate方法处理日期字符串，确保iOS设备支持
        const dateA = new Date(this.fixIOSDate(a.OUTPDATE || ''));
        const dateB = new Date(this.fixIOSDate(b.OUTPDATE || ''));
        return dateA - dateB;
      });
      
      return {
        deptName,
        schedules: sortedSchedules
      };
    });
    
    console.log(this.groupedArr);
  } catch (error) {
    console.error("处理排班信息时发生错误:", error);
    this.groupedArr = [];
  }
})
        //这里从后台获取已关注的医生


        var docstr = sessionStorage.getItem("guanzhudoc") || '';


        if (docstr.indexOf(this.detail.id) !== -1) {
          this.flag = true;
        } else {
          this.flag = false;
        }
        // console.log(docstr);
        // if (docstr.indexOf(this.detail.id) != -1) {
        //   this.flag = true;
        // } else {
        //   this.flag = false;
        // }
      });

    },
  },
};
</script>

<style scoped lang="scss">
.bj {
  background: #f5f5f5;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
}

.jianjie {
  background: #fff;
  padding: 0.375rem;
  display: flex;
  border-bottom: 0.25rem solid #f5f5f5;

  h2 img {
    width: 1.75rem;
    height: 1.75rem;
    border-radius: 50%;
    margin-right: 0.25rem;
  }

  h3 {
    color: #333;
    font-size: 0.4rem;
    position: relative;
    width: calc(100% - 2rem);

    span {
      font-size: 0.375rem;
      padding-top: 0.125rem;
     // display: block;
    }

    p {
      font-size: 0.35rem;
      color: #999;
      display: block;
      padding-top: 0.125rem;
      overflow: hidden;
    }
  }
}

.box1 {
  background: #fff;
  padding: 0.5rem 0;
  margin-bottom: 0.125rem;
}

.box1 h2 {
  font-size: 0.4rem;
  color: #333;
  padding-bottom: 0.25rem;
}

.box1 p {
  color: #333;
  font-size: 0.375rem;
  display: block;
  padding-bottom: 0.25rem;
}

.box1 img {
  max-width: 100%;
  height: auto;
}

.guanzhu,
.yiguanzhu {
  height: 0.5rem;
  width: 2rem;
  position: absolute;
  right: 0.5rem;
  border-radius: 0.25rem;
  font-size: 0.3rem;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;

  i {
    margin-right: 0.1rem;

    font-size: 0.375rem;
  }
}

.guanzhu {
  background: linear-gradient(270deg, #166bcc, #84ccff);
}

.yiguanzhu {
  background: linear-gradient(270deg, #01c268, #c4f38e);
}

.guahao {
  height: 1rem;
  width: 80%;
  position: absolute;
  left: 10%;
  bottom: 0.5rem;
  float: right;
  border-radius: 0.5rem;
  font-size: 0.5rem;
  color: #fff;
  background-color: #166bcc;
  display: flex;
  align-items: center;
  justify-content: center;
  //background-color: #ccc;
  i {
    font-size: 0.5rem;
  }

  z-index: 2;
}

.gao {
  height: 1.5rem;
  width: 100%;
  position: absolute;
  bottom: 0.1rem;
}

/* 科室排班分组样式 */
.department-schedule {
  margin-bottom: 0.75rem;
}

.department-name {
  font-size: 0.4rem;
  color: #333;
  margin-bottom: 0.3rem;
  font-weight: bold;
  padding: 0 0.2rem;
}

/* 排班信息样式 */
.schedule-list {
  position: relative;
  overflow: hidden;
}

.schedule-scroll {
  display: flex;
  gap: 0.25rem;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 0.25rem;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  padding: 0 0.2rem;
}

/* 隐藏滚动条但保留滚动功能 */
.schedule-scroll::-webkit-scrollbar {
  display: none;
}

.schedule-scroll {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.schedule-item {
  background: #f5f5f5;
  padding: 0.3rem;
  border-radius: 0.25rem;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e0e0e0;
  min-width: 1.8rem;
  max-width: 1.8rem;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.schedule-item:hover {
  background: #e8f4fd;
  border-color: #166bcc;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(22, 107, 204, 0.15);
}

.top-info {
  text-align: center;
  margin-bottom: 0.15rem;
  width: 100%;
  font-size: 0.3rem;
  color: #333;
}

.date-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.2rem;
  width: 100%;
}

.date {
  font-size: 0.35rem;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.fee-info {
  font-size: 0.3rem;
  color: #666;
  width: 100%;
}

.total-fee {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ff6b6b;
  font-weight: bold;
}

.no-schedule {
  text-align: center;
  color: #999;
  font-size: 0.375rem;
  padding: 0.5rem 0;
  background: #f5f5f5;
  border-radius: 0.25rem;
}
</style>