<template>
  <div class="home">
    <nav-bar></nav-bar>
    <div class="bj"></div>
    <div class="lxr">
      <div class="lxrr">
        <h2>
          {{ PatientName }}
          <p>卡号：{{ PatientId }}</p>
        </h2>
        <h3></h3>
      </div>
    </div>

    <div class="ts_box" v-if="status == '3'">
      <h2>注意事项</h2>
      <p class="p1">1.此挂号信息由于网络或其他原因导致暂未收到支付信息，5分钟未收到支付成功通知的挂号信息会有取消按钮，请点击取消按钮取消后重新挂号。</p>
      <p class="p1">2.取消后，已支付的金额会原路返回，请注意查收。</p>
      <p class="p1">3.如果未挂号成功且没有取消按钮，请等5分钟后刷新重试。</p>
    </div>

    <div class="qrxx">
      <ul>
        <li>
          <h2>医生名称</h2>
          <h3>{{ DoctorName }}</h3>
        </li>
        <li>
          <h2>就诊时间</h2>
          <h3>{{ Registerdate }}</h3>
        </li>
        <li>
          <h2>医院名称</h2>
          <h3>武警宁夏总队医院</h3>
        </li>
        <li>
          <h2>就诊科室</h2>
          <h3>{{ DepartName }}</h3>
        </li>
        <li>
          <h2>挂号金额</h2>
          <h3>¥{{ money }}</h3>
        </li>
      </ul>
    </div>

    <!-- 二维码区域：仅基于 PatientId 生成 -->
    <div class="qrcode">
  <vue-qr
    v-if="status != '3' && PatientId"
    :size="180"
    :margin="0"
    :auto-color="true"
    :dot-scale="1"
    :text="PatientId"
  />
</div>
<p class="qrcode-tip" v-if="status != '3' && PatientId">
    线下就诊需通过该码，到自助机/报到机处点击“就诊签到”，扫码签到排号。
  </p>

<van-button
      class="btn"
      color="#166bcc"
      :loading="loading"
      type="primary"
      loading-text="处理中..."
      style="margin-bottom: 15px;"
      @click="handleCancel2"
      v-if="RefundSTATE == 'Y'"
    >
      换号
    </van-button>
    <van-button
      class="btn"
      color="#166bcc"
      :loading="loading"
      type="primary"
      loading-text="处理中..."
      @click="handleCancel"
      v-if="RefundSTATE == 'Y'"
    >
      退号
    </van-button>
    
    <van-button
      class="btn"
      color="#166bcc"
      :loading="loading"
      type="primary"
      loading-text="处理中..."
      @click="handleSignIn"
      v-if="RefundSTATE == 'Y'"
    >
      线上签到
    </van-button>

    <van-button
      class="btn"
      color="#166bcc"
      :loading="loading"
      type="primary"
      loading-text="处理中..."
      @click="CancelGH"
      v-if="CancleSTATE == 'Y'"
    >
      取消
    </van-button>

    <!-- 遮罩层加载效果 -->
    <van-overlay :show="show" z-index="999">
      <div class="loading-wrapper">
        <van-loading size="50px" vertical>处理中...</van-loading>
      </div>
    </van-overlay>
  </div>
</template>

<script>
import {
  apiopBillsPayedRefundQuery,
  apiopBillsPayedRefund,
  apiopRegisterCancel
} from "@/request/api.js";
import { Toast, Dialog } from "vant";
import VueQr from 'vue-qr';

export default {
  components: {
    VueQr,
  },
  data() {
    return {
      title: "",
      PatientId: '',
      PatientName: '',
      DepartName: '',
      DoctorName: '',
      Registerdate: '',
      TimeInterval: '',
      money: '',
      status: '',
      RefundSTATE: 'N',
      CancleSTATE: 'N',
      PowerTranID: '',
      OrderNo: '',
      paytype: '',
      show: false,
      loading: false,
      hisopernum:'',
    };
  },
  mounted() {
    const query = this.$route.query;
    // console.log("query:",query);
    this.status = query.status || '';
    this.OrderNo = query.OrderNo || '';
    this.PatientId = query.PatientId || '';
    this.PatientName = query.PatientName || '';
    this.DepartName = query.DepartName || '';
    this.DoctorName = query.DoctorName || '';
    this.Registerdate = query.Registerdate || '';
    this.TimeInterval = query.TimeInterval || '';
    this.money = query.money || '';

    // 如果状态为 1（已支付），查询是否可退号
    if (this.status == '1') {
      this.refundQuery();
    }
    // 如果状态为 3（待支付超时），检查是否可取消
    else if (this.status == '3') {
      const LockTime = new Date(query.LockTime);
      const now = new Date();
      if (Math.floor((now - LockTime) / 1000) > 300) {
        this.CancleSTATE = 'Y';
      }
    }
  },
  methods: {
    handleSignIn() {
      Toast({
        message: '目前请到自助机/签到机上进行签到',
        duration: 5000
      });
    },
    CancelGH() {
      this.show = true;
      apiopRegisterCancel({ hisorderno: this.OrderNo })
        .then(() => {
          this.show = false;
          Toast("取消成功");
          setTimeout(() => this.$router.back(-1), 500);
        })
        .catch(() => {
          this.show = false;
          Toast("取消失败，请稍后重试");
          setTimeout(() => this.$router.back(-1), 500);
        });
    },

    refundQuery() {
      const formData = {
        PatientId: this.PatientId,
        FlowNo: this.OrderNo,
      };
      apiopBillsPayedRefundQuery(formData)
        .then((res) => {
          const jsonObj = this.$x2js.xml2js(res.data);
          const data = jsonObj.Envelope.Body.MOP_OutpBillsPayedRefundQueryResponse.request.request;
          console.log(data);
          if (data.returnresult.returncode === "1") {
            if (data.data.HisOperNum === "wx") {
              this.RefundSTATE = data.data.RefundSTATE;
              // console.log(this.RefundSTATE);
              this.PowerTranID = data.data.PowerTranID;
              this.paytype = data.data.PayType;
              this.hisopernum = data.data.HisOperNum;
            }
          }
        })
        .catch((err) => {
          console.error("退号查询失败", err);
        });
    },

    handleCancel() {
      const now = new Date();
      const hour = now.getHours();
      const minute = now.getMinutes();

      // 限制退号时间：8:30 - 23:00
      if (hour < 8 || (hour === 8 && minute < 30) || hour >= 23) {
        Toast("当前暂无法退号，请于每日8:30-23:00期间进行退号退费操作\n或到线下缴费处进行退费退号");
        return;
      }

      Dialog.confirm({
        title: "提示",
        message: "是否退号\n注：退号需在挂号当天或次日9点后办理，\n超过就诊时间无法退费退号",
      }).then(() => {
        this.show = true;
        const formData = {
          patientid: this.PatientId,
          billsmsg: this.OrderNo,
          paynature: 1,
          paytype: this.paytype,
          powertranid: this.PowerTranID,
          zfamount: this.money,
          ybzhamount: '',
          ybtcamount: '',
          yboutmsg: '',
          hisopernum: this.hisopernum,
          txsend:'退号'
        };

        apiopBillsPayedRefund(formData)
          .then((res) => {
            if (res && (res.code === 200 || res.code === "200")) {
              Toast("退号成功");
            } else {
              Toast(res.data?.message || res.message || "操作失败");
            }
          })
          .catch((error) => {
            console.error("退号接口异常:", error);
            Toast("退号失败: " + (error.message || "网络异常"));
          })
          .finally(() => {
            this.show = false;
            setTimeout(() => this.$router.back(-1), 2000);
          });
      });
    },
    handleCancel2() {
      const now = new Date();
      const hour = now.getHours();
      const minute = now.getMinutes();

      // 限制退号时间：8:30 - 23:00
      if (hour < 8 || (hour === 8 && minute < 30) || hour >= 23) {
        Toast("当前暂无法换号，请于每日8:30-23:00期间进行换号操作\n或到线下缴费处进行换号");
        return;
      }

      Dialog.confirm({
        title: "提示",
        message: "是否换号\n注：换号需在挂号当天或次日8:30后办理，\n超过就诊时间无法换号",
      }).then(() => {
        this.show = true;
        const formData = {
          patientid: this.PatientId,
          billsmsg: this.OrderNo,
          paynature: 1,
          paytype: this.paytype,
          powertranid: this.PowerTranID,
          zfamount: this.money,
          ybzhamount: '',
          ybtcamount: '',
          yboutmsg: '',
          hisopernum: this.hisopernum,
          txsend:'退号'
        };

        apiopBillsPayedRefund(formData)
          .then((res) => {
            if (res && (res.code === 200 || res.code === "200")) {
              Toast("退号成功");
            } else {
              Toast(res.data?.message || res.message || "操作失败");
            }
          })
          .catch((error) => {
            console.error("退号接口异常:", error);
            Toast("退号失败: " + (error.message || "网络异常"));
          })
          .finally(() => {
            this.show = false;
            setTimeout(() => {
  this.$router.push('/xzmz');
}, 2000);
          });
      });
    }
  }
};
</script>

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

.loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  .van-loading {
    color: #fff;
    text-align: center;
  }
}

.lxr .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;
    }
  }
}

.qrxx ul li {
  border-bottom: 1px solid #f5f5f5;
  padding: 0.375rem;
  background: #fff;
  display: flex;
  color: #333;

  h2 {
    font-size: 0.375rem;
    width: 2.5rem;
  }

  h3 {
    width: calc(100% - 2.5rem);
    font-size: 0.375rem;
  }
}

.btn {
  width: 90%;
  margin: 10px auto 0;
  // margin-top: 1rem;
  border-radius: 0.375rem;
  display: block;
}

.qrcode {
  padding: 0.5rem 0;
  display: flex;
  justify-content: center;
}

.ts_box {
  padding: 0.375rem 0.25rem;
  color: #000;
  .p1 {
    padding-top: 0.125rem;
  }
}
.qrcode-tip {
  margin-top: 0.3rem;
  font-size: 0.34rem;
  color: #666;
  text-align: center;
  line-height: 1.4;
  padding: 0 1rem;
}
</style>