<template>
  <div class="home">
    <nav-bar/>
    <div class="bj"></div>
    <div class="lxr" @click="handleCardSelect">
      <div class="lxrr" v-if="card && card.id">
        <h2>
          {{ card.name }}
          <p>卡号：{{ card.cardNo }}</p>
        </h2>
        <h3>
          <i class="van-icon van-icon-arrow van-cell__right-icon"></i>
        </h3>
      </div>
      <van-contact-card type="add" add-text="请选择就诊人" v-else/>
    </div>
    <div class="time_box">
      <van-cell title="报告单类型" class="bgcell">
        <van-radio-group v-model="radio" direction="horizontal">
          <van-radio name="1" icon-size="20px">检验单</van-radio>
          <van-radio name="2" icon-size="20px">检查单</van-radio>
        </van-radio-group>
      </van-cell>
      <div style="margin: 0 0 0 20px;">
      <p>检验单查询内容：血/尿/便</p>
      <p>检查单查询内容：B超/心电图/DR/CT/核磁</p>
      </div>
      <van-cell title="开始时间" :value="startdate" @click="startshow = true"/>
      <van-cell title="结束时间" :value="enddate" @click="endshow = true"/>
      <van-calendar
          v-model="startshow"
          :min-date="new Date(2020, 0, 1)"
          @confirm="onstartConfirm"
          :show-confirm="false"
          color="#2e82ef"
      />
      <van-calendar
          v-model="endshow"
          :min-date="new Date(2020, 0, 1)"
          @confirm="onendConfirm"
          :show-confirm="false"
          color="#2e82ef"
      />
    </div>
    <van-button
        class="btn"
        color="#166bcc"
        :loading="loading"
        type="primary"
        loading-text="加载中..."
        @click="onConfirm"
    >查询
    </van-button
    >
    <div class="listbox">
      <!--      <van-cell-->
      <!--          v-if="radio=='2'"-->
      <!--          v-for="item in list"-->
      <!--          :key="item.regno"-->
      <!--          :title="item.ordername.substr(0, 20)"-->
      <!--          :value="item.times"-->
      <!--          :label="'报告ID：' + item.regno"-->
      <!--          @click="querylistmx(item)"-->
      <!--      />-->
      <van-cell
          v-if="radio=='1'"
          class="listitem"
          v-for="item in lislist"
          :key="item.reportId"
          :title="item.reportName"
          :value="item.reportPdfFilePath.split('/')[2]"
          :label="item.reportName"
          @click="querypacsmx(item)"
      />
          <van-cell
          v-if="radio=='2'" 
           class="listitem"
          v-for="item in pacslist"
          :key="item.RequestElectronic"
          :title="item.StudiesExamine"
          :value="item.RequestElectronic"
          :label="item.StudiesExamine"
          @click="querypacsdetail(item)"
      />
    </div>
    <!-- PACS详情弹窗 -->
<van-popup
  v-model="pacsDetailShow"
  closeable
  title="检查报告详情"
  position="bottom"
  :style="{ height: '90%', overflow: 'auto' }"
>
  <div class="pacs-detail-container">
    <!-- 患者基本信息 -->
    <div class="pacs-section">
      <h3 class="section-title">患者信息</h3>
      <div class="info-row">
        <span class="info-label">姓名：</span>
        <span class="info-value">{{ currentPacsDetail?.PatientsName }}</span>
        <span class="info-label">性别：</span>
        <span class="info-value">{{ currentPacsDetail?.PatientsSex === 'M' ? '男' : '女' }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">年龄：</span>
        <span class="info-value">{{ currentPacsDetail?.StudiesAge }}</span>
        <span class="info-label">出生日期：</span>
        <span class="info-value">{{ currentPacsDetail?.PatientsDOB }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">身份证号：</span>
        <span class="info-value">{{ currentPacsDetail?.PatientsCertificate }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">联系电话：</span>
        <span class="info-value">{{ currentPacsDetail?.PatientsPhone }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">地址：</span>
        <span class="info-value">{{ currentPacsDetail?.PatientsAddress }}</span>
      </div>
    </div>

    <!-- 检查信息 -->
    <div class="pacs-section">
      <h3 class="section-title">检查信息</h3>
      <div class="info-row">
        <span class="info-label">检查项目：</span>
        <span class="info-value">{{ currentPacsDetail?.StudiesExamine }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">申请单号：</span>
        <span class="info-value">{{ currentPacsDetail?.RequestElectronic }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">申请科室：</span>
        <span class="info-value">{{ currentPacsDetail?.RequestDepartmentAlias }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">申请医生：</span>
        <span class="info-value">{{ currentPacsDetail?.RequestDoctorAlias }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">检查日期：</span>
        <span class="info-value">{{ currentPacsDetail?.StudiesDateTime }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">检查科室：</span>
        <span class="info-value">{{ currentPacsDetail?.StudiesDepartmentName }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">检查费用：</span>
        <span class="info-value">{{ currentPacsDetail?.StudiesExaminePrice ? '¥' + currentPacsDetail?.StudiesExaminePrice : '未标注' }}</span>
      </div>
    </div>

    <!-- 检查所见 -->
    <div class="pacs-section">
      <h3 class="section-title">表现</h3>
      <div class="report-content">
        {{ currentPacsDetail?.ReportsEvidences }}
      </div>
    </div>

    <!-- 检查结论 -->
    <div class="pacs-section">
      <h3 class="section-title">报告结论</h3>
      <div class="report-content conclusion">
        {{ currentPacsDetail?.ReportsConclusion }}
      </div>
    </div>
 <!-- 报告信息 -->
    <div class="pacs-section">
      <h3 class="section-title">审核信息</h3>
      <div class="info-row">
        <span class="info-label">报告医生：</span>
        <span class="info-value">{{ currentPacsDetail?.ReportsDoctorAlias }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">报告日期：</span>
        <span class="info-value">{{ currentPacsDetail?.ReportsDateTime }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">审核医生：</span>
        <span class="info-value">{{ currentPacsDetail?.ApproveDoctorAlias }}</span>
      </div>
       <div class="info-row">
        <span class="info-label">审核日期：</span>
        <span class="info-value">{{ currentPacsDetail?.ApproveDateTime }}</span>
      </div>
      <div class="info-row">
        <span class="info-label">复审医生：</span>
        <span class="info-value">{{ currentPacsDetail?.ReviewsDoctorAlias }}</span>
      </div>
       <div class="info-row">
        <span class="info-label">复审日期：</span>
        <span class="info-value">{{ currentPacsDetail?.ReviewsDateTime }}</span>
      </div>
    </div>
    <!-- PDF查看按钮（预留功能） -->
    <div class="pdf-view-section">
      <van-button 
        type="primary" 
        color="#166bcc"
        block
        @click="viewPacsPdf"
      >
        查看PDF报告
      </van-button>
    </div>
  </div>
</van-popup>
    <van-popup
        id="pdf"
        v-model="resultshow"
        @click="resultshow = false"
        :class="popupclass"
    ></van-popup>
  </div>
</template>

<script>
import {
  apiopPacscx,
  apiopLiscx,
  GetPdfReportsAddress,
  getPacsPdf
} from "@/request/api.js";
import axios from "axios";
import Vue from "vue";

import {Toast, Empty, Calendar, RadioGroup, Radio, Slider} from "vant";
import 'canvas';
import 'dommatrix/dist/dommatrix.js';
import 'web-streams-polyfill/dist/ponyfill.js';
import $ from 'jquery'; // 添加这行来引入jQuery

Vue.use(Calendar);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Slider);
export default {
  mounted() {
    this.title = this.$route.meta.title;
  },
  components: {
  },
  data() {
    return {
      title: "",
      card: {},
      activeSelect: 0,
      list: [],
      pacslist: [],
      lislist: [],
      date: "",
      startshow: false,
      endshow: false,
      startdate: "",
      enddate: "",
      radio: "1",
      loading: false,
      src: "", // pdf文件地址
      resultshow: false,
      scale: 0, //放大系数
      idx: -1,
      pdfh5: null,
      popupclass: "wrapper0",
    pacsDetailShow: false, // 控制PACS详情弹窗显示
    currentPacsDetail: null, // 保存当前PACS详情数据
    };
  },

  created() {
     // 设置默认时间范围
    this.setDefaultDateRange();
    this.card = JSON.parse(sessionStorage.getItem("card"));
      console.log(this.card)
      if (this.card === undefined || this.card === null) {
        Toast("未查询到用户身份，请先绑定就诊人！！")
        this.$router.push({path: "/Member_jzr"});}
        else{
          return;
        }
    /*apiUserCardList({ isYes: 0 }).then(res => {
      this.card = res.data[0];
    });*/
  },
  methods: {
     viewPacsPdf() {
    // 这里将实现PDF查看功能
    console.log("准备查看PDF报告", this.currentPacsDetail);
    let params = {
      PatientsID: this.card.cardNo,
      StudiesDateTime: this.currentPacsDetail?.StudiesDateTime,
      RequestElectronic: this.currentPacsDetail?.RequestElectronic,
      AccessionNumber: this.currentPacsDetail?.AccessionNumber,
      StudiesModalities: this.currentPacsDetail?.StudiesModalities,
      AdmissionSource: this.currentPacsDetail?.AdmissionSource,
    };
 
      if (this.card.cardNo == null) {
        Toast("请选择就诊人");
        return;
      }
    GetPdfReportsAddress(params).then(res => {
      console.log("PDF文件地址：", res);
       let jsonObj = this.$x2js.xml2js(res.data);
            console.log(jsonObj);
            let jsonObj2 = this.$x2js.xml2js(
                jsonObj.Envelope.Body.GetPdfReportsAddressResponse
                    .return
            );
            console.log(jsonObj2);
            if(jsonObj2.PdfReports.exeResult =="true"){
              // src: jsonObj2.PdfReports.reports.report.pdfFile
              //"http://....."
              console.log(jsonObj2.PdfReports.reports.report.pdfFile);
              let param = {
                reportPdfFilePath: jsonObj2.PdfReports.reports.report.pdfFile
              }
              getPacsPdf(param).then(res => {
                console.log(res);
                if(res.code == 200){ 
                   param.reportPdfFilePath = res.data
                   this.querypacsmx(param)
                }
               

              });
            
            }
    });
  },
    querypacsdetail(item){
console.log(item);
 this.currentPacsDetail = item;
  // 显示详情弹窗
  this.pacsDetailShow = true;
  
  // 这里预留PDF查询方法的调用位置
  // this.queryPacsPdf(item);
    },
    onChange(scale) {
      this.$refs.pdf.$el.style.width = parseInt(100 + scale) + "%";
    },
// 添加设置默认日期范围的方法
    setDefaultDateRange() {
      const today = new Date();
      // 设置结束时间为今天
      this.enddate = this.formatDate(today);
      
      // 设置开始时间为三个月前
      const threeMonthsAgo = new Date();
      threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
      this.startdate = this.formatDate(threeMonthsAgo);
    },
    formatDate(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      month = month > 9 ? month : "0" + month;
      let day = date.getDate();
      day = day > 9 ? day : "0" + day;
      return year + "-" + month + "-" + day;
    },
    onstartConfirm(date) {
      this.startshow = false;
      this.startdate = this.formatDate(date);
    },
    onendConfirm(date) {
      this.endshow = false;
      this.enddate = this.formatDate(date);
    },
    onConfirm() {
      this.loading = true;
      if (this.startdate == "" || this.enddate == "") {
        Toast("请选择起止时间");
        this.loading = false;
      } else {
        this.resultshow = true; //先刷新一下弹窗，加载pdfbox，避免查看报告刷不出来
        this.popupclass = "wrapper0";
        if (this.radio == "1") {
          this.getLisList();

        } else {
          this.getPacsList();
        }
      }
    },
    async querypacsmx(item) {

      /*
       // let pdfUrl = "http://101.132.179.117/gzhsvr" + item.reportPdfFilePath;
      // let pdfUrl = encodeURIComponent('http://101.132.179.117/gzhsvr/storage/2023-10-07/2023-10-07_30_1_101.PDF');
      let pdfUrl = encodeURIComponent('http://101.132.179.117/gzhsvr/storage/2023-10-04/2023-10-04_2_1_1.PDF');
      let pdfData = PDFJS.getDocument(pdfUrl);

      pdfData.promise.then((pdf) => {
        this.numPages = pdf.numPages
        for (let i = 1; i <= this.numPages; i++) {
          pdf.getPage(i).then((page) => {
            let canvas = this.$refs['myCanvas_' + i][0];
            let viewport = page.getViewport(3);
            canvas.height = viewport.height;
            canvas.width = viewport.width;
            let ctx = canvas.getContext("2d");
            let renderContext = {
              canvasContext: ctx,
              viewport: viewport,
            };
            page.render(renderContext)
          });
        }
      });
      * */
      //this.src="http://wx.btdbyy.cn:9081/storage/"+item.pdfurl;
      $("#pdfbox").remove();
      this.popupclass = "wrapper";
      this.resultshow = true;
      
      // 动态导入 Pdfh5 和相关样式
      const { default: Pdfh5 } = await import('pdfh5');
      await import('pdfh5/css/pdfh5.css');
      
      //实例化
      //  console.log("@@@"+"http://153.0.195.114:8855"+(item.reportPdfFilePath))
      if (this.pdfh5) {
        this.pdfh5.destroy()
        this.pdfh5 = null
      }
      setTimeout(() => {
        var $div = '<div id="pdfbox"></div>';
        $("#pdf").append($div); //将新创建的div节点插入到nav容器的内容底部
        this.pdfh5 = new Pdfh5("#pdfbox", {
          pdfurl: "https://nxwj.btlsoln.com/nxwj-gzhsvr" + item.reportPdfFilePath,
          // lazy: true, // 是否懒加载
          // withCredentials: true,
          // renderType: "svg",
          // maxZoom: 3, //手势缩放最大倍数 默认3
          // scrollEnable: true, //是否允许pdf滚动
          // zoomEnable: true, //是否允许pdf手势缩放
          // cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.5.207/cmaps/',
          // pdfurl: "http://153.0.195.114:8855/storage/2023-01-27/2023-01-27_15_1_1001.PDF"
        });
      }, 200);
    },

    async querylistmx(item) {

      // 动态导入 Pdfh5 和相关样式
      const { default: Pdfh5 } = await import('pdfh5');
      await import('pdfh5/css/pdfh5.css');

      $("#pdfbox").remove();
      this.popupclass = "wrapper";
      this.resultshow = true;
      //实例化
      //  console.log("@@@"+"http://153.0.195.114:8855"+(item.reportPdfFilePath))
      if (this.pdfh5) {
        this.pdfh5.destroy()
        this.pdfh5 = null
      }
      setTimeout(() => {
        var $div = '<div id="pdfbox"></div>';
        $("#pdf").append($div); //将新创建的div节点插入到nav容器的内容底部
        this.pdfh5 = new Pdfh5("#pdfbox", {
          pdfurl: "https://nxwj.btlsoln.com/gzhsvr" + item.reportPdfFilePath,
          // lazy: true, // 是否懒加载
          // withCredentials: true,
          // renderType: "svg",
          // maxZoom: 3, //手势缩放最大倍数 默认3
          // scrollEnable: true, //是否允许pdf滚动
          // zoomEnable: true, //是否允许pdf手势缩放
          // cMapUrl: 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.5.207/cmaps/',
          // pdfurl: "http://153.0.195.114:8855/storage/2023-01-27/2023-01-27_15_1_1001.PDF"
        });
      }, 200);


      $("#pdfbox").remove();
      this.popupclass = "wrapper";
      this.resultshow = true;
      var $div = '<div id="pdfbox"></div>';
      $("#pdf").append($div); //将新创建的div节点插入到nav容器的内容底部
      this.src = "http://wx.btdbyy.cn:9082/" + item.pdfurl;
      //this.src="http://wx.btdbyy.cn:9082/assets/LIS_PDF/20211129/738994.PDF"
      //实例化
      /*this.pdfh5 = new Pdfh5("#pdfbox", {
        pdfurl: this.src,
        });*/
      $.ajax({
        url: this.src, //假设这是pdf文件流的请求接口
        type: "get",
        cache: false,
        mimeType: "text/plain; charset=x-user-defined", //jq ajax请求文件流的方式
        //dataType:"jsonp",
        crossDomain: true, //设置跨域为true
        success: function (data) {
          this.pdfh5 = new Pdfh5("#pdfbox", {
            data: data,
          });
        },
      });
    },
    getLisList() { 
      let that = this;
      that.list = [];
      that.lislist = [];
      let formData = {
        QueryCode: that.card.cardNo,
        //QueryCode:"0001238384",
        QueryType: 1,
        StartTime: that.startdate + " 00:00:00",
        EndTime: that.enddate + " 23:59:59",
      };
      if (that.card.cardNo == null) {
        Toast("请选择就诊人");
        return;
      }
      that.resultshow = false; //先刷新一下弹窗，加载pdfbox，避免查看报告刷不出来
      apiopLiscx(formData)
          .then((res) => {
            // console.log(res);
            this.loading = false;
            console.log(res.data.response);
            if (res.code === 200 && res.data.response.length > 0) {
              for (var i = 0; i < res.data.response.length; i++) {
                that.lislist.push(res.data.response[i]);
              }
            } else if (res.code === 110005) {
              Toast(res.message);
            } else {
              Toast("暂无检验报告");
            }
          })
          .catch((err) => {
            Toast("网络异常，请稍后重试");
            this.loading = false;
          });
    },

    getPacsList() {
      let that = this;
      that.list = [];
      that.pacslist = [];
      let formData = {
        QueryCode: that.card.cardNo,
        //QueryCode:"0001238384",
        QueryType: 2,
        StartTime: that.startdate + " 00:00:00",
        EndTime: that.enddate + " 23:59:59",
      };
      if (that.card.cardNo == null) {
        Toast("请选择就诊人");
        return;
      }
      that.resultshow = false; //先刷新一下弹窗，加载pdfbox，避免查看报告刷不出来
      apiopPacscx(formData)
          .then((res) => {
            console.log(res);
            this.loading = false;
            if (res.code === 200 && res.data.exeFiles !== undefined) {
              for (var i = 0; i < res.data.exeFiles.length; i++) {
                that.pacslist.push(res.data.exeFiles[i]);
              }
            } else if (res.code === 110005) {
              Toast(res.message);
            } else {
              Toast("暂无检查报告");
            }
          })
          .catch((err) => {
            Toast("网络异常，请稍后重试");
            this.loading = false;
          });
    },

    handleCardSelect() {
      this.$router.push({path: "/Member_jzr", query: {f: 1}});
    },
  },
};
</script>

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

.lxr {
  .van-cell--center {
    border-radius: 0.25rem;
    padding: 0.25rem;
    background: url(../assets/lxrbj.png) no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    color: #fff;

    .van-cell__value--alone {
      color: #fff;
    }

    .van-cell__right-icon {
      color: #fff;
    }
  }

  .van-contact-card::before {
    background: none;
  }

  ::v-deep .van-contact-card--add .van-cell__left-icon {
    color: #fff;
    opacity: 0.6;
  }

  .lxrr {
    border-radius: 0.25rem;
    background: url(../assets/lxrbj.png) no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    color: #fff;
    padding: 0.4rem;
    display: flex;
    align-items: center;
    justify-content: space-between;

    h2 {
      font-size: 0.5rem;

      p {
        font-size: 0.4rem;
        padding-top: 0.15rem;
      }
    }

    h3 .van-cell__right-icon {
      color: #fff;
    }
  }
}

::v-deep .van-tabs__content {
  margin-top: 0.25rem;
}

.time_box {
  background-color: #fff;
  margin: 0.25rem;
  padding: 0.25rem;
  height: 4.2rem;
  border-radius: 0.375rem;
  box-shadow: 0 0 0.25rem #ccc;
}

.btn {
  width: 90%;
  position: relative;
  margin: 5%;
  border-radius: 0.375rem;
}

.bgcell {
  .van-cell__value {
    min-width: 70%; //可根据自己需求设定值
    text-align: left;
  }

  .van-radio {
    padding-right: 0.25rem;
  }
}

.listbox {
  .van-cell__title {
    min-width: 70%; //可根据自己需求设定值
    text-align: left;
  }

  .van-cell__value {
    font-size: 0.375rem;
    text-align: right;
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 95%;
  height: 80%;
  border-radius: 0.25rem;
}

.wrapper0 {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 0%;
  height: 0%;
  border-radius: 0.25rem;
}

.canvas-container {
  width: 100%;
  overflow: hidden;
}

.pdf-container {
  width: 100%;
}
.pacs-detail-container {
  padding: 0.194rem; /* 15px = 15 ÷ 77.27 ≈ 0.194rem */
  font-size: 0.22rem; /* 17px（基础字体大小，对应比例基准） */
}

.pacs-section {
  margin-bottom: 0.311rem; /* 24px = 24 ÷ 77.27 ≈ 0.311rem */
  padding-bottom: 0.233rem; /* 18px = 18 ÷ 77.27 ≈ 0.233rem */
  border-bottom: 1px solid #eee;
}

.pacs-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  font-size: 0.38rem; 
  color: #166bcc;
  margin-bottom: 0.155rem; /* 12px = 12 ÷ 77.27 ≈ 0.155rem */
  padding-left: 0.065rem; /* 5px = 5 ÷ 77.27 ≈ 0.065rem */
  border-left: 0.039rem solid #166bcc; /* 3px = 3 ÷ 77.27 ≈ 0.039rem */
  font-weight: 600;
}

.info-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 0.181rem; /* 14px = 14 ÷ 77.27 ≈ 0.181rem */
  line-height: 1.8;
}

.info-label {
  color: #666;
  min-width: 1.165rem; /* 90px = 90 ÷ 77.27 ≈ 1.165rem */
  font-size: 0.3rem; /* 17px */
}

.info-value {
  flex: 1;
  margin-right: 0.194rem; /* 15px = 15 ÷ 77.27 ≈ 0.194rem */
  word-break: break-word;
  font-size: 0.3rem; /* 17px */
}

.report-content {
  line-height: 1.8;
  white-space: pre-line;
  color: #333;
  padding: 0.065rem; /* 5px = 5 ÷ 77.27 ≈ 0.065rem */
  font-size: 0.35rem; /* 17px */
}

.conclusion {
  color: #e53935;
  font-weight: 500;
  font-size: 0.36rem; /* 17px */
}

.pdf-view-section {
  margin-top: 0.323rem; /* 25px = 25 ÷ 77.27 ≈ 0.323rem */
  padding: 0.129rem 0; /* 10px = 10 ÷ 77.27 ≈ 0.129rem */
}
.listitem {
  margin-bottom: 2px;
}
</style>
