<template>
  <div class="home">
    <nav-bar></nav-bar>
    <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 v-if="showbox">
      <van-cell-group class="cell_box">
        <van-cell title="住院病区" :value="zyinfo.DEPTNAME" />
        <van-cell title="住院床号" :value="zyinfo.BEDNO" />
        <van-cell title="入院日期" :value="zyinfo.HOSDATE" />
        <van-cell :value="zyinfo.HOSBALANCE">
          <template slot="title">
            <span class="custom-title">账户余额</span>
            <van-tag class="celltag" @click="tagclick">查询预交记录></van-tag>
          </template>
        </van-cell>
          <van-cell title="今日还可充值:" :value="zyinfo.YJJKC" />
      </van-cell-group>
      <div class="chargemoneyboxbt">
        支付金额
        <div class="chargemoneybox1">
          <div :class="this.chargemoney == 1000 ? 'box1' : 'box'" @click="clickmoney(1000)">
            <h2>1000元</h2>
          </div>
          <div :class="this.chargemoney == 2000 ? 'box1' : 'box'" @click="clickmoney(2000)">
            <h2>2000元</h2>
          </div>
          <div :class="this.chargemoney == 3000 ? 'box1' : 'box'" @click="clickmoney(3000)">
            <h2>3000元</h2>
          </div>
        </div>
        <div class="chargemoneybox2">
          <div :class="this.chargemoney == 4000 ? 'box1' : 'box'" @click="clickmoney(4000)">
            <h2>4000元</h2>
          </div>
          <div :class="this.chargemoney == 5000 ? 'box1' : 'box'" @click="clickmoney(5000)">
            <h2>5000元</h2>
          </div>
          <!-- <div :class="this.chargemoney == 8000 ? 'box1' : 'box'" @click="clickmoney(8000)">
            <h2>8000元</h2>
          </div> -->
        </div>
      </div>
      <van-cell-group>
        <van-field type="number" v-model="qtchargemoney" label="其他金额" class="qtchargemoneybt" placeholder="请输入金额"
          @input="inputmoney" />
      </van-cell-group>

      <div :class="btnclass">
        <div @click="onConfirm">支付</div>
      </div>
    </div>
    <van-empty description="住院处暂无该患者信息" v-else style="padding-top:90px" />
    <!-- <van-tabs class="order_tab" color="#46C3B0" line-height="2px" title-active-color="#46C3B0">
      <van-tab v-for="item in list" :key="item.tit">
        <template #title>{{item.tit}}</template>
        <ul>
          <li v-for="(xzks) in item.list" :key="xzks.index">
            <van-cell :title="xzks.bt" is-link :to="xzks.url" :value="xzks.time" />
          </li>
        </ul>
      </van-tab>
    </van-tabs>-->

    <!--van-collapse  v-model="activeSelect" accordion v-if="list.length>0">
      <van-collapse-item
        :title="item.DIAGNOSIS_NAME"
        :name="index"
        v-for="(item,index) in list"
        :key="index"
      >
        <ul>
          <li>
            <span>诊断名称：</span>{{item.DIAGNOSIS_NAME}}
          </li>
          <li>
            <span>诊断日期：</span>{{item.VISIT_DATE}}
          </li>
          <li>
            <span>诊断类型：</span>{{item.DIAGNOSIS_TYPE}}
          </li>
          <li>
            <span>诊断序号：</span>{{item.DIAGNOSIS_NO}}
          </li>
          <li>
            <span>票据号：</span>{{item.DIAGNOSIS_NO}}
          </li>
          <li>
            <span>电话号码：</span>{{item.PHONE_NUMBER}}
          </li>
        </ul>
      </van-collapse-item>
    </van-collapse>
    <van-empty description="暂无信息" v-else style="padding-top:90px"/-->
    <van-action-sheet v-model="showPatientSelector" title="请选择使用的患者ID" :actions="patientActions"
      @select="onPatientSelect" cancel-text="取消" @cancel="showPatientSelector = false" />
  </div>
</template>

<script>
import {
  apiUserCardList,
  apiInHosPatientInfoQuery,
  apiInHosChargeRecordQuery,
  apipay,
  getUserCategory,
  apiOpWxQuery,
  yjjXeQuery
} from "@/request/api.js";
import Vue from "vue";
import { Toast, Empty, Calendar, RadioGroup, Radio, Field, ActionSheet, Dialog } from "vant";
Vue.use(ActionSheet);
Vue.use(Calendar);
Vue.use(Radio);
Vue.use(RadioGroup);
Vue.use(Field);
Vue.use(Dialog);
export default {
  mounted() {
    this.title = this.$route.meta.title;
    // 显示住院预交金缴纳须知弹窗
    Dialog.alert({
      title: '住院预交金缴纳须知',
      messageAlign: 'left',
      message: '尊敬的患者及家属：\n\n现就住院预交金缴纳事宜告知如下：\n\n1、办理住院 24 小时内，暂不支持线上缴预交金，需充值请前往住院收费窗口办理。\n2、24 小时后可通过掌上医院缴费，但每位患者每日最高限 5000 元；超 5000 元需到窗口办理。\n3、窗口办理请携带患者有效身份证件、住院病历号（或押金单）；疑问可咨询护士站或收费窗口。\n\n感谢配合，祝您早日康复！'
    }).then(() => {
      // 弹窗关闭后的回调操作
    });
  },
  computed: {
    patientActions() {
      return this.patientIds.map(id => ({ name: `患者ID: ${id}`, id }));
    }
  },
  data() {
    return {
      title: "",
      card: {},
      activeSelect: 0,
      list: [],
      date: "",
      startshow: false,
      endshow: false,
      startdate: "",
      enddate: "",
      radio: "1",
      chargemoney: 1000,
      qtchargemoney: "",
      zyinfo: { YJJKC: 0 },
      showbox: false,
      btnclass: "btn",
      patientIds: [], // 存储多个 PatientId
      patientId: null, // 选中的 PatientId
      showPatientSelector: false,
      yjjxes :5000
    };
  },
  created() {

    this.card = JSON.parse(sessionStorage.getItem("card"));
    if (this.card) {
      this.getZYInfo();
      return;
    }

    apiUserCardList({ isYes: 0 }).then((res) => {
      this.card = res.data[0];
      this.getZYInfo();
    }).catch((error) => {
      // 加载失败处理
      Toast.fail('获取就诊人信息失败');
    });

  },
  methods: {
    formatDate(date) {
      return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
    },
    onstartConfirm(date) {
      this.startshow = false;
      this.startdate = this.formatDate(date);
    },
    onendConfirm(date) {
      this.endshow = false;
      this.enddate = this.formatDate(date);
    },
    onConfirm2(){
      Toast({
  message: '因医院原因，暂时不开放线上充值预交金功能，请到门诊缴费窗口充值！',
  duration: 3000 // 设置显示时长为 3 秒
});
return;
    },
    yjjxe(){
      return yjjXeQuery({patientId:this.patientId}).then(res => {
        console.log("预交金限额查询",res);
       return res.data;
      })
    },
    onConfirm() {
      // 检查当前时间是否在23:48-00:01之间，这个时间段内禁止充值
      const now = new Date();
      const hours = now.getHours();
      const minutes = now.getMinutes();
      
      if ((hours === 23 && minutes >= 48) || (hours === 0 && minutes <= 1)) {
        Toast({
          message: '当前时间段(23:48-00:01)正在对账，暂不支持支付操作，请0点过后再试！',
          duration: 5000
        });
        return;
      }
      
      if(this.zyinfo.YJJKC < this.chargemoney){
        Toast({
          message: '今日线上剩余可充值额度不足，请调整充值金额或到收费室进行充值！',
          duration: 4500 // 设置显示时长为 3 秒
        });
        return;
        // Toast({
        //   message: '您本日线上预交金充值已限额，如需充值请到收费室充值！',
        //   duration: 4000 // 设置显示时长为 4秒
        // });
       
      }
    if(this.patientId != "90134173"){
          Toast({
  message: '因医院原因，暂时不开放线上充值预交金功能，请到门诊缴费窗口充值！',
  duration: 3000 // 设置显示时长为 3 秒
});
return;
      }
     

        if(this.zyinfo.HOSDATE ){
          // 计算时间差
          const hosDate = new Date(this.zyinfo.HOSDATE);
          const now = new Date();
          const timeDiff = now - hosDate; // 毫秒差
          const hoursDiff = timeDiff / (1000 * 60 * 60); // 转换为小时
          
          if (hoursDiff < 24) {
            // 计算剩余时间
            const remainingMs = (24 - hoursDiff) * 1000 * 60 * 60;
            const remainingHours = Math.floor(remainingMs / (1000 * 60 * 60));
            const remainingMinutes = Math.floor((remainingMs % (1000 * 60 * 60)) / (1000 * 60));
            
            // 小于24小时，显示提示
            Toast({
              message: `患者24小时内如需充值需在门诊部1楼收费室进行充值，${remainingHours}小时${remainingMinutes}分钟后才能线上充值预交金！`,
              duration: 5000 // 设置显示时长为 5 秒
            });
            return;
          }
          // 大于24小时，继续执行下面的流程
        }
       
      let _this = this;
      let formData = {
        cardno: _this.zyinfo.INHOSPATIENTID,
        money: parseFloat(_this.chargemoney),
        num: _this.zyinfo.INHOSNUM,
      };
      if (_this.btnclass == "btn") {
        _this.btnclass = "btn1";

        apipay(formData).then((ref) => {
          _this.btnclass = "btn";
          //发起订单请求，等待响应，调起支付页面
          let payParams = {
              appId: ref.data.appId, // 微信的appid
              timeStamp: ref.data.timeStamp, //时间戳
              nonceStr: ref.data.nonceStr, //随机串
              package: ref.data.package,  // 订单号
              signType: "MD5", //微信签名方式：
              paySign: ref.data.paySign //微信签名
          };
            // 查询参数
        let queryParams = {
          outTradeNo: ref.data.outTradeNo
        };

 // 调起微信支付
        WeixinJSBridge.invoke('getBrandWCPayRequest', payParams, (res) => {
          console.log('微信支付返回:', res);
          console.log("订单号：", queryParams.outTradeNo);

          if (res.err_msg && res.err_msg.indexOf('ok') > -1) {
            // ✅ 支付成功，启动轮询
            this.startPaymentPolling(queryParams); // 调用组件方法
          } else if (res.err_msg && res.err_msg.indexOf('cancel') > -1) {
            Toast("用户取消支付");
          } else {
            Toast("支付失败: " + (res.err_msg || '未知错误'));
          }

          this.loading = false;
        });


          //alert(JSON.stringify(res))
          // window.location.href =
          //     _this.httpurl + "/pay.jsp?id=" + res.data.result;
        });

        setTimeout(() => {
          _this.btnclass = "btn";
        }, 2000);
      }
    },
 // 独立方法：启动轮询查询支付结果
    startPaymentPolling(queryParams) {
      // 防止重复启动
      if (this.pollTimer) {
        clearInterval(this.pollTimer);
        this.pollTimer = null;
      }

      const toast = Toast.loading({
        forbidClick: true,
        message: '正在查询支付结果...',
        loadingType: 'circular',
        duration: 0
      });

      let pollCount = 0;
      const maxPollCount = 15; // 最多 30 秒（15次 × 2秒）

      this.pollTimer = setInterval(() => {
        pollCount++;
        console.log(`第 ${pollCount} 次轮询查询支付状态...`);

        apiOpWxQuery(queryParams)
          .then((res) => {
            console.log('查询响应:', res);

            if (res.code === 200) {
              const data = res.data;
              const state = data.trade_state;

              if (state === 'SUCCESS') {
                // ✅ 支付成功
                clearInterval(this.pollTimer);
                this.pollTimer = null;
                toast.clear();
                Toast.success("支付成功");
                 // 设置支付状态为完成
                this.isPaying = false;
                // 先跳转再刷新
               this.$router.push({
                    path:
                      "/ZYCharge_list?INHOSNUM=" +
                      this.zyinfo.INHOSNUM +
                      "&HOSDATE=" +
                      this.zyinfo.HOSDATE,
                  });

                // 确保路由跳转完成后刷新页面
                this.$nextTick(() => {
                  window.location.reload();
                });

                sessionStorage.removeItem("yuyue");
              } else if (state === 'NOTPAY') {
                // 继续等待
                console.log('用户尚未支付');
              } else {
                // 其他失败状态
                clearInterval(this.pollTimer);
                this.pollTimer = null;
                toast.clear();
                Toast.fail("支付失败：" + (data.trade_state_desc || state));
              }
            } else {
              console.warn('查询接口异常:', res);
            }
          })
          .catch((error) => {
            console.error('查询请求失败:', error);
          })
          .finally(() => {
            if (pollCount >= maxPollCount) {
              if (this.pollTimer) {
                clearInterval(this.pollTimer);
                this.pollTimer = null;
              }
              toast.clear();
              Toast.fail("支付超时，请稍后查看订单状态");
            }
          });
      }, 2000);

      // 总超时兜底（30秒）
      setTimeout(() => {
        if (this.pollTimer) {
          clearInterval(this.pollTimer);
          this.pollTimer = null;
        }
        if (toast) {
          toast.clear();
        }
      }, maxPollCount * 2000);
    },

    clickmoney(chargemoney) {
      this.chargemoney = chargemoney;
      this.qtchargemoney = "";
    },
    tagclick() {
      this.$router.push({
        path:
          "/ZYCharge_list?INHOSNUM=" +
          this.zyinfo.INHOSNUM +
          "&HOSDATE=" +
          this.zyinfo.HOSDATE,
      });
    },
    inputmoney() {
      // 获取原始输入值
      const rawInput = this.qtchargemoney;
      
      // 确保输入的是数字，且最多两位小数
      // 使用正则表达式验证：只允许数字和小数点后最多两位
      if (!/^\d+(\.\d{0,2})?$/.test(rawInput)) {
        // 如果输入不符合格式，截取到最后一个有效字符
        this.qtchargemoney = rawInput.slice(0, -1);
        return;
      }
      
      // 确保输入的是数字
      let inputMoney = parseFloat(this.qtchargemoney);
      
      // 检查是否为有效数字
      if (isNaN(inputMoney)) {
        this.qtchargemoney = "";
        this.chargemoney = 1000;
        return;
      }
      
      // 限制最大金额为5000
      if (inputMoney > 5000) {
        inputMoney = 5000;
        this.qtchargemoney = "5000";
      }
      
      // 更新金额
      this.chargemoney = inputMoney;
      
      // 如果输入为空，设置默认金额
      if (this.qtchargemoney == "") {
        this.chargemoney = 1000;
      }
    },
    onPatientSelect(action) {
      this.patientId = action.id;
      this.showPatientSelector = false;
      console.log("选中的 patientId:", this.patientId);
      // 如果需要根据 patientId 做其他查询，可在这里调用
      let formData2 = {
        QueryCode: this.patientId,
        QueryType: 2,
      };
      this.apiInHosPatientInfoQuery(formData2);
    },
    apiInHosPatientInfoQuery(formData) {
      apiInHosPatientInfoQuery(formData).then((res) => {
        let _this = this;
        console.log(res);
        let jsonObj = this.$x2js.xml2js(res.data);
        console.log(jsonObj);
        let jsonObj2 = this.$x2js.xml2js(
          jsonObj.Envelope.Body.MOP_InHosPatientInfoQueryResponse
            .MOP_InHosPatientInfoQueryResult
        );
        console.log("json2",jsonObj2);
        let dataRows = jsonObj2.response.data.data_row;
        if (jsonObj2.response.returnresult.returncode == "1") {
          if (Array.isArray(dataRows)) {
            for (var i = 0; i < dataRows.length; i++) {
              if (dataRows[i].HOSSTATE == "0" || dataRows[i].HOSSTATE == "") {
            _this.yjjxe().then(money => {
    dataRows[i].YJJKC = _this.yjjxes - money;
_this.zyinfo = dataRows[i];
                _this.showbox = true;
});
              }
            }
          } else {
            if (dataRows.HOSSTATE == "0" || dataRows.HOSSTATE == "") {
            _this.yjjxe().then(money => {
  dataRows.YJJKC = _this.yjjxes - money;
   _this.zyinfo = dataRows;
              _this.showbox = true;
});

            }
          }
        }
      }).catch((error) => {
        console.error(error);
        _this.showbox = false;
      });
    },
    getZYInfo() {
      let _this = this;
      console.log(_this.card);
      let formData = {
        queryCode: _this.card.idNo,
        queryType: 7,
      };
      getUserCategory(formData).then((res) => {
        console.log(res);
        let jsonObj = this.$x2js.xml2js(res.data);
        // console.log(jsonObj);
        let jsonObj2 = jsonObj.Envelope.Body.MOP_OutpPatInfoQueryResponse
          .request;
        console.log(jsonObj2);
        if (Array.isArray(jsonObj2.request.data)) {
          // 如果是数组，遍历获取每个元素的 PatientId
          this.patientIds = jsonObj2.request.data.map(item => item.PatientId);
        } else {
          // 如果不是数组，说明只有一个对象
          this.patientIds = [jsonObj2.request.data.PatientId];
        }
        if (this.patientIds.length === 1) {
          this.patientId = this.patientIds[0];
          let formData2 = {
            QueryCode: this.patientId,
            QueryType: 2,
          };
          this.apiInHosPatientInfoQuery(formData2);
        } else if (this.patientIds.length > 1) {
          this.showPatientSelector = true; // 弹出选择器
        }
        console.log(this.patientIds);
      });
    },
    handleCardSelect() {
      this.$router.push({ path: "/Member_jzr", query: { f: 1 } });
    },
  },
};
</script>

<style scoped lang="scss">
.lxr {
  .van-cell--center {
    border-radius: 15px;
    padding: 20px;
    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: 15px;
    padding: 20px;
    background: url(../assets/lxrbj.png) no-repeat;
    background-size: 100% 100%;
    background-position: center center;
    color: #fff;
    padding: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    h2 {
      font-size: 32px;

      p {
        font-size: 28px;
        padding-top: 10px;
      }
    }

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

::v-deep .van-tabs__content {
  margin-top: 20px;
}

.time_box {
  margin: 10px;
  padding: 10px;
  height: 265px;
  border-radius: 14px;
  background-color: #fff;
}

.btn {
  //position: fixed;
  padding: 100px 30px;
  bottom: 0px;

  div {
    width: 690px;
    height: 68px;
    line-height: 68px;
    text-align: center;
    background: #166bcc;
    border-radius: 14px;
    display: block;
    margin: 0px auto;
    font-size: 32px;
    color: #ffffff;
  }
}

.btn1 {
  //position: fixed;
  padding: 100px 30px;
  bottom: 0px;

  div {
    width: 690px;
    height: 68px;
    line-height: 68px;
    text-align: center;
    background: #c4c4c4;
    border-radius: 14px;
    display: block;
    margin: 0px auto;
    font-size: 32px;
    color: #ffffff;
  }
}

.celltag {
  margin-left: 20px;
  background-color: #fff;
  color: #f49d13;
}

.chargemoneybox1 {
  padding-top: 20px;
  padding-left: 30px;
  display: flex;
  align-items: center;
  color: #f49d13;
}

.chargemoneybox2 {
  padding-left: 30px;
  display: flex;
  align-items: center;
  color: #f49d13;
}

.box {
  border-style: solid;
  border-width: 5px;
  border-color: #f49d13;
  border-radius: 15px;
  margin: 15px;
  padding: 20px 40px;
}

.box1 {
  border-style: solid;
  border-width: 5px;
  border-color: #166bcc;
  border-radius: 15px;
  margin: 15px;
  padding: 20px 40px;
  background-color: #166bcc;
  color: #fff;
}

.chargemoneyboxbt {
  padding-top: 20px;
  padding-left: 30px;
  font-size: 28px;
  font-weight: 600;
  color: #000;
}

.qtchargemoneybt {
  font-size: 28px;
  font-weight: 600;
  color: #000;
}
</style>
