<template>
  <div class="home">
    <nav-bar />
    <div class="bj"></div>
    <ul class="timeSlelct">
      <li v-for="(item, index) in same_week" :class="{ active: same_day == item.date }" @click="timeSlelct(item)"
        :key="index">
        <div>{{ item.week }}</div>
        <div>{{ item.name }}</div>
        <span></span>
      </li>
    </ul>

    <div class="list" v-if="list.length > 0">
      <ul>
        <li v-for="(item, index) in list" :key="index" @click="handleDetail(item)">
          <a>
            <h2> <img :src="item.img || require('../assets/member_tx.png')" /></h2>
            <!-- <h2><img :src="item.img" /></h2> -->
            <!-- :class="{'on':item.APPOINT_COUNT=='0'}" -->
            <h3>
              {{ item.DOCTORNAME }}
              <span>{{ item.DOCTORTITLE }}</span>
              <!-- <em>余{{ item.APPOINT_COUNT.__text || '1000' }}</em> -->
              <p>{{ displayLabel(item) }}</p>
               <p class="expertise" v-if="item.ysjj">
            <span class="label">擅长：</span>
            <span class="content-wrapper">
              <span class="content">{{ item.ysjj }}</span>
            </span>
          </p>
            </h3>
            <!-- <h3 class="on" v-else-if="item.on == 0">
              {{ item.name }}<span>{{ item.grade }}</span
              ><em>余{{ item.ticket }}</em>
              <p>{{ item.jianj }}</p>
            </h3>-->
          </a>
        </li>
      </ul>
    </div>
    <van-empty description="暂无数据" v-else style="padding-top: 90px" />
    <van-overlay :show="overshow" z-index="999" />
  </div>
</template>

<script>
// @ is an alias to /src
import {
  apiGetPbList,
  apiGetAppointSchedulesMark,
  apiGetRegistSchedulesMark,
  apiGetAppointHidsMark,
  getinfoByName
} from "@/request/api.js";
import Vue from "vue";
import { Toast, Popup, overlay } from "vant";

export default {
  data() {
    return {
      active: 0,
      title: "",
      flag: false,
      checked: false,
      time: "",

      list: [],
      istoday: false,
      yuyue: {},

      today: "",
      week: [],
      same_week: [], //保存当前最新的时间
      same_day: "", //当天的时间
      overshow: false,
    };
  },
  computed: {
    displayLabel() {
      return (item) => {
        return item.CLINICLABEL === '内科便民' ? item.CLINICLABEL + ' : 只开药，不看诊。' : item.DEPTNAME;
      }
    }
  },
  created() {
    //console.log(this.$route.meta.title);
    this.title = this.$route.meta.title;
    this.list = [];
    this.yuyue = JSON.parse(sessionStorage.getItem("yuyue"));
    this.title = this.yuyue.DeptName;
    console.log(this.yuyue);
    this.getWeek();
  },
  methods: {
    timeSlelct(item) {
      this.same_day = item.date;
      this.yuyue.t = item.date2;
      if (item.date == this.today) {
        this.yuyue.z = 1;
      } else {
        this.yuyue.z = 2;
      }
      // console.log(this.yuyue);
      this.getList();
      // console.log(item);
      // console.log(this.same_day.replace(new RegExp('/','g'),'-'))
    },
    getWeek() {
      // 默认显示当天前一周的数据
      let data = [];
      this.start = this.getDay(+7);
      this.end = this.getDay();
      for (let i = 13; i >= 0; i--) {
        data.push(this.getDay(+i));
      }
      var date = data.reverse(); //得出一周的日期进行排序
      this.week = date;
      var date = this.week;
      var pkc = []; /* 用于存储展示的日期数据 */
      var weekday = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      date.forEach((item, index) => {
        //循坏日期
        var f = new Date(item);
        var week = f.getDay(); //计算出星期几
        var str1 = item.split("/");
        var strs =
          (str1[1] >= 10 ? str1[1] : "0" + str1[1]) +
          "." +
          (str1[2] >= 10 ? str1[2] : "0" + str1[2]);
        var yyyyddmmdate =
          str1[0] +
          "-" +
          (str1[1] >= 10 ? str1[1] : "0" + str1[1]) +
          "-" +
          (str1[2] >= 10 ? str1[2] : "0" + str1[2]);
        var weeks = weekday[week]; /* 将计算出来的时间带入数字得出中文 */
        var time = Math.round(new Date(item) / 1000); //时间戳转换
        var s = {}; //用于存储每个日期对象
        s.date = item;
        s.date2 = yyyyddmmdate;
        s.name = strs;
        s.week = weeks;
        s.times = time;
        pkc.push(s);
      });
      this.same_week = pkc;
      // console.log(this.same_week)
      //pkc存储着今天的年月日星期几，时间戳等
      this.same_day = this.today = pkc[0].date; //今天的数据
      this.yuyue.t = pkc[0].date2;
      console.log(this.yuyue.t);
      // console.log(this.same_day)
      this.yuyue.z = 1;
      this.getList();
      // console.log(this.same_day)
    },
    getDay(day) {
      var today = new Date();
      var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
      today.setTime(targetday_milliseconds);
      var tYear = today.getFullYear();
      var tMonth = today.getMonth();
      var tDate = today.getDate();
      tMonth = this.doHandleMonth(tMonth + 1);
      tDate = this.doHandleMonth(tDate);
      return tYear + "/" + tMonth + "/" + tDate;
    },
    doHandleMonth(month) {
      var m = month;
      if (month.toString().length == 1) {
        m = month;
      }
      return m;
    },

    handleDetail(data) {
      // 检查医生编码和姓名是否为空
      if (!data.DOCTORCODE || !data.DOCTORNAME) {
        Toast('当前科室暂无医生排班，不支持挂号，请线下缴费处询问');
        return;
      }

      this.yuyue.DoctorCode = data.DOCTORCODE;
      this.yuyue.DoctorName = data.DOCTORNAME;
      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 = data.img 
      sessionStorage.setItem("yuyue", JSON.stringify(this.yuyue));
      this.$router.push({ path: "/Ysgh" });
    },
    getList() {
      let _this = this;
      _this.list = [];
      console.log(_this.yuyue.t);//第几天
      console.log(_this.yuyue.z);//周几
      console.log(_this.yuyue.DeptCode);
      _this.overshow = true;
      // var pbxx="<response> <returnresult> <returncode>1</returncode> <errormsg>查询成功</errormsg> </returnresult> <data> <data_row> <SubHospitalID>0000</SubHospitalID> <ScheduleId>AAASJ6AAEAACmG5AAn</ScheduleId> <OutpDate>2021/8/27 0:00:00</OutpDate> <TimeInterval>PM</TimeInterval> <DepartCode>10010011</DepartCode> <ParentDepartCode /> <DeptName>心血管内科</DeptName> <Level>1</Level> <Location>测试位置</Location> <SectionType /> <DoctorCode>000179</DoctorCode> <DoctorName>李晓龙</DoctorName> <DoctorTitle>医师</DoctorTitle> <Specialty /> <DoctorDes /> <ClinicTypeName>普通</ClinicTypeName> <ClinicFee>0.01</ClinicFee> <RegistrationFee>0.00</RegistrationFee> <RegistrationLimit>50</RegistrationLimit> <ReserveLimit>20</ReserveLimit> <RegistrationNum>0</RegistrationNum> <ReserveNum /> <ValidFlag>1</ValidFlag> </data_row> <data_row> <SubHospitalID>0000</SubHospitalID> <ScheduleId>AAASJ6AAEAACmG5AAm</ScheduleId> <OutpDate>2021/8/27 0:00:00</OutpDate> <TimeInterval>AM</TimeInterval> <DepartCode>10010011</DepartCode> <ParentDepartCode /> <DeptName>心血管内科</DeptName> <Level>1</Level> <Location>测试位置</Location> <SectionType /> <DoctorCode>000179</DoctorCode> <DoctorName>李晓龙</DoctorName> <DoctorTitle>医师</DoctorTitle> <Specialty /> <DoctorDes /> <ClinicTypeName>普通</ClinicTypeName> <ClinicFee>0.01</ClinicFee> <RegistrationFee>0.00</RegistrationFee> <RegistrationLimit>20</RegistrationLimit> <ReserveLimit>0</ReserveLimit> <RegistrationNum>0</RegistrationNum> <ReserveNum /> <ValidFlag>1</ValidFlag> </data_row> </data> </response></string>";
      // let jsonObj2 = this.$x2js.xml2js(pbxx);
      // this.list =jsonObj2.response.data.data_row;
      // _this.overshow=false;
      let chargeType = JSON.parse(sessionStorage.getItem("card")).chargetype
      console.log(chargeType)
      apiGetAppointHidsMark({
        StartTime: _this.yuyue.t + " 00:00:00",
        EndTime: _this.yuyue.t + " 23:59:59",
        DepartCode: _this.yuyue.DeptCode,
        chargeType: chargeType,
        DoctorCode: "",
      })
        .then(async (res) => {
          _this.overshow = false;
          console.log(res.data);
          let jsonObj = this.$x2js.xml2js(res.data);
          console.log(jsonObj);
          let jsonObj2 = this.$x2js.xml2js(
            jsonObj.Envelope.Body.MOP_OutpScheduleQueryResponse
              .MOP_OutpScheduleQueryResult
          );
          console.log(jsonObj2);
          let arr = jsonObj2.response.data.data_row;
          console.log("arr是",arr);
          //过滤出 OFFLINE_FLAG 为 '0' 的数据
         if (arr && Array.isArray(arr)) {
  // 过滤出 OFFLINE_FLAG 为 '0' 的数据
  arr = arr.filter(item => item.OFFLINE_FLAG === '0');
} else if (arr && arr.OFFLINE_FLAG === '0') {
  // 如果只有一个对象且符合条件，则放入数组中
  arr = [arr];
} else {
  // 如果没有符合条件的对象，则设为空数组
  arr = [];
}
       // 使用 async/await 处理图片获取
      if (arr.length >= 1) {
          for (let i = 0; i < arr.length; i++) {
            const ysinfo = await this.getDocImg(arr[i].DOCTORNAME, arr[i].DOCTORCODE);
            arr[i].img = ysinfo.img;
            arr[i].ysjj = ysinfo.ysjj;
          }
          _this.list = arr;
      }
      
      _this.overshow = false;
      console.log(_this.list);
        })
        .catch(() => {
          // 添加"稍后再试"提示
          // Toast("网络异常，请稍后再试");
          _this.overshow = false;
        });
    },

    typeFilter(data) {
      return data.filter((item) => {
        return typeof item.DoctorName == "string";
      });
    },
    // dataFilter(arr) {
    //   const res = new Map();
    //   return arr.filter(
    //       (arr) => !res.has(arr.DoctorName) && res.set(arr.DoctorName, 1)
    //   );
    // },
    getDocImg(docName, docCode) {
      let param = {
        name: docName,
        doct_code: docCode  // 传递医生编码以唯一标识医生
      }
      return getinfoByName(param).then(res => {
        console.log('医生信息:', res);
         // 提取 <p> 标签中的内容
    let ysjj = res.data.grsc;
    if (ysjj) {
      // 移除所有 HTML 标签，只保留文本内容
      ysjj = ysjj.replace(/<[^>]+>/g, '');
    }
        let params = {
          img: res.data.img,
          ysjj: ysjj
        }
        return params;
      })
    },
    showPopup() {
      this.show = true;
    },
    showMode() {
      this.showe = true;
    },
  },
};
</script>

<style scoped lang="scss">
::-webkit-scrollbar {
  width: 0 !important;
}

ul.timeSlelct {
  display: flex;
  justify-content: space-between;
  position: fixed;
  z-index: 10;
  width: 100%;
  height: 1.8rem;
  overflow-x: auto;

  li {
    padding: 0.25rem;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: center;
    background-color: rgba(22, 104, 204, 0.2);
    position: relative;
    border-left: 1px solid #f5f5f5;
    border-radius: 0.25rem;
    margin: 0.05rem;
  }

  li:nth-child(1) {
    border-left: 0;
  }

  .active {
    background-color: #166bcc;
    color: #fff;
  }
}

.bj {
  background: #f5f5f5;
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: -1;
}

.list {
  margin-top: 1.75rem;
  position: relative;
  z-index: 1;
}

.list ul li {
  background: #fff;
  margin-bottom: 0.25rem;

  a {
    display: flex;
    box-sizing: border-box;
    padding: 0.375rem;

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

    h3 {
      color: #333;
      font-size: 30px;
      position: relative;
      // width: calc(100% - 118px);
      width: 100%;

      span {
        font-size: 0.28rem;
        color: #666;
        // padding-left: 0.125rem;
      }

      p {
        font-size: 0.375rem;
        color: #999;
        display: block;
        padding-top: 0.25rem;
      }

      em {
        width: 1rem;
        height: 0.375rem;
        line-height: 0.375rem;
        background: linear-gradient(-90deg, #ff464f, #ff6e77);
        border-radius: 0.125rem;
        position: absolute;
        right: 0;
        top: 0;
        font-size: 0.25rem;
        text-align: center;
        color: #fff;
      }
        p.expertise {
        font-size: 0.375rem;
        color: #666;
        display: flex;
        align-items: center;
        padding-top: 0.15rem;
        line-height: 1.4;
        white-space: nowrap;
        overflow: hidden;
        
        .label {
          font-weight: bold;
          color: #333;
          flex-shrink: 0;
          margin-right: 0.1rem;
        }
        
        .content-wrapper {
          overflow: hidden;
          position: relative;
          flex: 1;
        }
        
        .content {
          display: inline-block;
          animation: scroll-left 15s linear infinite;
          margin-left: 170px;
        }
        
        @keyframes scroll-left {
          0% {
            transform: translateX(0);
          }
          100% {
            transform: translateX(-100%);
          }
        }
      }
    }

    h3.on em {
      background: #999999;
    }
  }
}
</style>
