<template>
  <view class="container">
    <view class="content" v-if="showCon">
      <view class="parentBox">
        <view class="money_info_box">
          <view class="money_info">
            <text>{{orderDetail.PriceName}}</text>
            <text class="colorCustom">￥{{orderDetail.PayMoney/100}}</text>
          </view>
          <view class="count_down_box border_top">
            订单已生成，请在<text class="colorCustom">{{endTimesDiy}}</text>内完成支付
          </view>
        </view>
        <view class="time_box">
          <view class="time_box_list">
            <text>就诊人</text>
            <text>{{orderDetail.MemberName}}</text>
          </view>
          <view class="time_box_list ellipsis" v-if="orderDetail.CardType">
            <text>{{orderDetail.CardType == '1'?'就诊卡号':orderDetail.CardType == '16'?'健康卡号':'住院号'}}</text>
            <text>{{orderDetail.CardNo}}</text>
          </view>
          <view class="time_box_list">
            <text>收款单位</text>
            <text class="bor_bottom border_bottom">{{hosName}}</text>
          </view>
          <view class="time_box_list">
            <text>订单号</text>
            <text>{{orderDetail.OrderNum}}</text>
          </view>
          <view class="time_box_list">
            <text>创建时间</text>
            <text>{{orderDetail.BeginDate}}</text>
          </view>
        </view>
      </view>
      <!-- 多个支付方式时显示 -->
      <view class="content_pay" v-if="pageConfig.payWay == '2'">
        <view class="info_list border_bottom" @click="confirmClick">
          <image class="list_circle" :src="iconUrl.treasure_pay"></image>
          <view class="list_name">支付宝支付</view>
          <image class="public_right_img" :src="iconUrl.icon_right"></image>
        </view>
        <view class="info_list border_bottom" @click="confirmClick">
          <image class="list_circle" :src="iconUrl.wechat_pay"></image>
          <view class="list_name">微信支付</view>
          <image class="public_right_img" :src="iconUrl.icon_right"></image>
        </view>
        <view class="info_list border_bottom" @click="confirmClick">
          <image class="list_circle" :src="iconUrl.unionpay_pay"></image>
          <view class="list_name">银联支付</view>
          <image class="public_right_img" :src="iconUrl.icon_right"></image>
        </view>
        <view class="info_list border_bottom" @click="confirmClick">
          <image class="list_circle" :src="iconUrl.cloudf_paylash"></image>
          <view class="list_name">云闪付支付</view>
          <image class="public_right_img" :src="iconUrl.icon_right"></image>
        </view>
        <view class="info_list border_bottom" @click="abcWapUnitePay">
          <image class="list_circle" :src="iconUrl.pay_abcPay"></image>
          <view class="list_name">农行支付</view>
          <image class="public_right_img" :src="iconUrl.icon_right"></image>
        </view>
      </view>
      <!-- 单个支付方式时显示 -->
      <view class="content_btn" v-if="pageConfig.payWay == '1'">
        <view class="btn cancel_btn" @click="cancelClick" v-if="orderDetail.PayState == 0">取消订单</view>
        <view class="btn confirm_btn backgroundCustom" :class="{'width100': orderDetail.PayState != 0}" @click="confirmClick">去支付</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onUnmounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { common } from '@/utils';
import icon from '@/utils/icon';
import { pagesPatientFn, getState } from '@/utils';
import { getConfigKey, getUnitePay, payCallBack } from '@/pagesPatient/service/pay/index';
import { orderDetailLocal, orderCancel } from '@/pagesPatient/service/record/index';

const app = getApp();
const iconUrl = ref(icon);
const orderId = ref('');
const currentUser = ref<any>({});
const showCon = ref(false);
const orderDetail = ref<any>({});
const endTimesDiy = ref('');
const hosName = ref('');
const pageConfig = ref<any>({});
let countdown: any = null;

onLoad((options) => {
  let config = common.deepCopy(app.globalData.config.pageConfiguration.payMent_config);
  hosName.value = app.globalData.hospitalInfo.HospitalAlias;
  orderId.value = options.orderId;
  currentUser.value = app.globalData.currentUser;
  pageConfig.value = config;
  main();
});

onUnmounted(() => {
  if (countdown) {
    clearInterval(countdown);
  }
});

const main = async () => {
  //获取订单详情
  let queryData = {
    OrderId: orderId.value
  };
  let resp = await orderDetailLocal(queryData);
  if (!common.isEmpty(resp)) {
    resp[0].OrderMemo = resp[0].OrderMemo ? JSON.parse(resp[0].OrderMemo) : {};
    orderDetail.value = resp[0];
    endTimesDiy.value = common.getexpirationTime(resp[0].EndDate);
    showCon.value = true;
    
    // 根据返回信息，修改页面标题
    uni.setNavigationBarTitle({
      title: resp[0].PriceName,
    });
    
    //倒计时
    countdown = setInterval(async () => {
      let currentTime = endTimesDiy.value;
      if (currentTime == '0' || currentTime == 0) {
        clearInterval(countdown);
        // 倒计时为0时查询订单转态 并取消订单
        let respCheck = await orderDetailLocal(queryData);
        // 判断不为空 且当前订单转态为待支付中
        if (!common.isEmpty(respCheck) && ((respCheck[0].PayState == 0 || respCheck[0].PayState == 1) && respCheck[0].BizState == 0 && respCheck[0].OverState == 0)) {
          let orderCancelData = {
            OperatorName: respCheck[0].OperatorName,
            OperatorId: respCheck[0].OperatorId,
            OrderId: respCheck[0].OrderId
          };
          await orderCancel(orderCancelData, respCheck[0].ServiceId);
        }
        common.showModal('订单支付超时', async () => {
          common.navigateBack(1);
        }, {
          title: '提示'
        });
      } else {
        endTimesDiy.value = common.getexpirationTime(resp[0].EndDate);
      }
    }, 1000);
  }
};

/**
 * 取消订单
 */
const cancelClick = () => {
  let detail = orderDetail.value;
  pagesPatientFn.cancelOrder(detail, () => {
    common.navigateBack(1);
  });
};

/**
 * 去支付
 */
const confirmClick = () => {
  let detail = orderDetail.value;
  common.throttle(async () => {
    //统一下单
    let configKeyResp = await getConfigKey(detail.OrderId, detail.ServiceId);
    if (!common.isEmpty(configKeyResp)) {
      // 获取支付配置
      let queryData = {
        token: uni.getStorageSync('token'),
        openId: uni.getStorageSync('openid'),
        orderId: detail.OrderId,
        priceName: detail.PriceName
      };
      let unitePayResp = await getUnitePay(queryData); // Note: Original code passed configKeyResp.WxPayConfigKey as second arg, but getUnitePay definition only takes one arg. Assuming definition is correct or handled inside.
      // However, looking at the definition in pay/index.ts: export const getUnitePay = async (queryData: any) => { ... }
      // It only accepts queryData. The original code passed a second argument which might be ignored or the definition I saw was incomplete.
      // Based on strict TS, I should follow the definition.
      
      // 调用JSAPI支付接口，拉起支付后，订单已失效，拦截本次支付
      if (!common.isEmpty(unitePayResp)) {
        let waunitePayData = await wxPayMent(unitePayResp);
        if (waunitePayData) {
          let callBackData = {
            token: uni.getStorageSync('token'),
            orderId: detail.OrderId,
          };
          // Same here for payCallBack
          await payCallBack(callBackData); 
          common.goToUrl(`/pagesPatient/st1/business/pay/payStateQuery/payStateQuery?orderId=${detail.OrderId}`, {
            skipWay: "redirectTo"
          });
        }
      }
    }
  });
};

/**
 * 农行的wap下单
 */
const abcWapUnitePay = () => {
  let detail = orderDetail.value;
  common.throttle(async () => {
    //统一下单
    let configKeyResp = await getConfigKey(detail.OrderId, detail.ServiceId);
    let token = uni.getStorageSync('token');
    if (!common.isEmpty(configKeyResp)) {
      common.goToUrl(`/pagesPatient/st1/business/pay/payMent/payMentH5?orderId=${detail.OrderId}&priceName=${detail.PriceName}&token=${token}&clientId=${detail.ChannelId}&configKey=${configKeyResp.AbcPayConfigKey}`);
    }
  });
};

/**
 * 调起微信支付
 */
const wxPayMent = (data: any) => {
  return new Promise(resolve => {
    uni.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': 'MD5',
      'paySign': data.paySign,
      'success': function (res) {
        resolve(res);
      },
      'fail': function (res) {
        resolve(false);
      }
    });
  });
};
</script>

<style lang="scss" scoped>
.money_info_box {
  background: white;
  margin-top: 20upx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.money_info {
  padding: 98upx 0 72upx 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.money_info text:nth-child(1) {
  font-size: 30upx;
  color: #333;
  margin-bottom: 20upx;
}

.money_info text:nth-child(2) {
  font-size: 56upx;
}

.count_down_box {
  width: 100%;
  text-align: left;
  padding: 40upx 30upx;
  box-sizing: border-box;
  font-size: 32upx;
  color: #333;
}

.count_down_box text {
  padding: 0 15upx;
}

.time_box {
  background: white;
  padding: 30upx 0 30upx 30upx;
  margin-top: 20upx;
}

.time_box_list {
  margin-bottom: 34upx;
}

.time_box_list:last-child {
  margin-top: 30upx;
  margin-bottom: 0;
}

.time_box_list text:nth-child(1) {
  width: 26%;
  display: inline-block;
  font-size: 32upx;
  color: #999;
}

.time_box_list text:nth-child(2) {
  width: 74%;
  font-size: 32upx;
  color: #333;
}

.bor_bottom {
  padding-bottom: 30upx;
  display: inline-block;
}

/* 支付方式 */

.content_pay {
  padding: 1upx 33upx;
}

.info_list {
  position: relative;
  display: flex;
  align-items: center;
  padding: 33upx 0;
}

.content_pay .list_circle {
  width: 48upx;
  height: 48upx;
}

.content_pay .list_name {
  font-size: 32upx;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: rgba(0, 0, 0, 1);
  line-height: 60upx;
  margin-left: 31upx;
}

/* 底部按钮 */

.content_btn {
  width: 100%;
  height: 98upx;
  font-size: 32upx;
  font-weight: 500;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1000;
}

.content_btn .btn {
  width: 50%;
  height: 98upx;
  line-height: 98upx;
  float: left;
  text-align: center;
  justify-items: center;
}

.content_btn .btn.width100 {
  width: 100%;
}

.confirm_btn {
  background: rgba(41, 207, 140, 1);
  color: #fff;
}

.cancel_btn {
  color: red;
  background-color: #fff;
}

.public_info_item.border_top {
  height: 1px;
}

.ellipsis {
  white-space: nowrap;
  /* 确保文本在一行内显示 */
  overflow: hidden;
  /* 隐藏溢出的内容 */
  text-overflow: ellipsis;
  /* 使用省略号表示溢出的文本 */
}
</style>
