<template>
  <view class="container">
    <!-- 支付信息卡片 -->
    <view class="payment-card">
      
      <!-- 订单信息 -->
      <view class="order-info">
        <view class="info-item">
          <text class="label">订单编号</text>
          <view class="value-container">
            <text class="value">{{ orderInfo.orderSn }}</text>
            <text class="refresh-btn" @click="generateRandomOrderSn">刷新</text>
          </view>
        </view>
        
        <view class="info-item">
          <text class="label">订单标题</text>
          <input class="value-input" v-model="orderInfo.billContent" placeholder="测试商品" />
        </view>
        
        <!-- <view class="info-item">
          <text class="label">分账方式</text>
          <view class="radio-group">
            <view 
              v-for="(item, index) in paymentMethods" 
              :key="index" 
              class="radio-item" 
              :class="{ active: orderInfo.billType === item.value }"
              @click="orderInfo.billType = item.value"
            >
              <view class="radio-circle">
                <view v-if="orderInfo.billType === item.value" class="radio-inner"></view>
              </view>
              <text>{{ item.label }}</text>
            </view>
          </view>
        </view> -->
        
        <view class="info-item">
          <text class="label">支付金额</text>
          <view class="price-container">
            <text class="currency">¥</text>
            <input 
              class="value-input price-input" 
              type="digit" 
              v-model="payAmount" 
              placeholder="0.01" 
            />
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部支付按钮 -->
    <view class="btn-box">
      <button class="pay-btn" :loading="buttonLoading" @click="handlePay">立即支付</button>
    </view>
    
    <u-toast ref="uToast" />
  </view>
</template>

<script>
var jweixin = require('jweixin-module');

export default {
  data() {
    return {
      orderId: '',
      orderInfo: {
        "billContent": "测试商品",
        "billHeader": null,
        "billReceiverEmail": null,
        "billReceiverPhone": null,
        "billType": 0,
        "id": "",
        "orderSn": "",
        "totalAmount": 1, // 1分钱
      },
      payAmount: "0.01",
      paymentMethods: [
        { label: "订单不分账", value: 0 },
        { label: "支付完成自动分账", value: 1 },
        { label: "手动分账", value: 2 }
      ],
      buttonLoading: false,
      officialAccount: {
        appid: '',
        appsecret: 'ca307cfb6c94e8ac015e26cfd717a91c',
      },
      code: '',
      openId: '',
    }
  },
  onLoad(option) {
    let appIdPublic = uni.getStorageSync('appIdPublic');
    this.officialAccount.appid = appIdPublic || '';
    
    if (option.id) {
      this.orderId = option.id;
    }
    
    // 生成随机订单号
    this.generateRandomOrderSn();
    
    // 获取openId
    let res = uni.getStorageSync('openId');
    if (res) {
      this.openId = res;
    } else {
      // #ifdef H5
      let code = this.getUrlCode('code')
      if (code || this.code) {
        this.code = code;
        this.getOpenidAndUserinfo(code);
      } else {
        console.log("当前网址", window.location.href)
        this.getH5Code()
      }
      // #endif
    }
  },
  methods: {
    // 生成随机订单号
    generateRandomOrderSn() {
      const timestamp = new Date().getTime();
      const random = Math.floor(Math.random() * 10000);
      this.orderInfo.orderSn = `M${timestamp}${random}`;
    },
    
    handlePay() {
      // 处理支付逻辑
      console.log("支付");
      
      // 转换金额为分
      const amountInCents = Math.round(parseFloat(this.payAmount) * 100);
      this.orderInfo.totalAmount = amountInCents;
      
      if (this.openId) {
        this.buttonLoading = true;
        
        // 调用支付API
        this.$api.orderApi.addPayOrder({
          orderId: this.orderInfo.id || this.orderInfo.orderSn,
          channelExtra: JSON.stringify({'openid': this.openId}),
          wayCode: 'LKL_WX_JSAPI',
          amount: amountInCents,
          subject: this.orderInfo.billContent || '测试商品'
        }).then((res) => {
          console.log("获取支付详情", res)
          this.buttonLoading = false;
          
          if (res.code == 200 && res.data) {
            // 调用微信支付
            this.wxpay(res.data);
          } else {
            this.$refs.uToast.show({
              title: '获取支付参数失败',
              type: 'error',
            });
          }
        }).catch(() => {
          this.buttonLoading = false;
          this.$refs.uToast.show({
            title: '支付请求失败',
            type: 'error',
          });
        });
      } else {
        this.clearUrlCode();
        this.getH5Code();
        this.$refs.uToast.show({
          title: '获取支付信息失败，请重试',
          type: 'error',
        });
      }
    },
    
    clearUrlCode() {
      // 清除URL中的code参数
      const url = window.location.href;
      const newUrl = url.split('?')[0]; // 去掉参数部分
      history.replaceState({}, '', newUrl);
    },
    
    getH5Code() {
      if (this.isWechat()) {
        // 微信授权获取code
        window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + this.officialAccount
          .appid + '&redirect_uri=' + encodeURIComponent(window.location.href) +
          '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect';
      }
    },
    
    getUrlCode(name) {
      return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
        ''])[1].replace(/\+/g, '%20')) || null;
    },
    
    isWechat() {
      return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
    },
    
    getOpenidAndUserinfo(code) {
      console.log("code换openid");
      this.$api.orderApi.getWxOpenid({
        code: code
      }).then((res) => {
        console.log("获取openid", res);
        if (res.code == 200) {
          if (res.data.openid) {
            this.openId = res.data.openid;
            uni.setStorageSync('openId', res.data.openid);
            this.clearUrlCode();
          } else {
            this.clearUrlCode();
            this.getH5Code();
          }
        }
      }).catch(() => {
        this.clearUrlCode();
        this.getH5Code();
      });
    },
    
    wxpay(data) {
      jweixin.config({
        debug: false,
        appId: data.appId,
        timestamp: data.timestamp,
        nonceStr: data.nonceStr,
        signature: data.signature,
        jsApiList: ['chooseWXPay']
      });
      
      this.onBridgeReady(data);
    },

    onBridgeReady(data) {
      jweixin.invoke(
        'getBrandWCPayRequest', {
          "appId": data.appId,
          "timeStamp": data.timeStamp,
          "nonceStr": data.nonceStr,
          "package": data.package,
          "signType": data.signType,
          "paySign": data.paySign
        },
        (res) => {
          // 支付成功
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            this.$refs.uToast.show({
              title: '支付成功',
              type: 'success',
            });
          }
          // 支付过程中用户取消
          if (res.err_msg == "get_brand_wcpay_request:cancel") {
            this.$refs.uToast.show({
              title: '用户取消',
              type: 'error',
            });
          }
          // 支付失败
          if (res.err_msg == "get_brand_wcpay_request:fail") {
            this.$refs.uToast.show({
              title: '支付失败',
              type: 'error',
            });
          }
        }
      );
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 30rpx;
  padding-bottom: 150rpx;
}

.payment-card {
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
}

.header-image {
  width: 100%;
  height: auto;
}

.order-info {
  padding: 30rpx;
}

.info-item {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.value-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.value {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.refresh-btn {
  font-size: 24rpx;
  color: #2979ff;
  padding: 6rpx 20rpx;
  background: rgba(41, 121, 255, 0.1);
  border-radius: 30rpx;
}

.value-input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #eee;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 30rpx;
  color: #333;
  background-color: #f9f9f9;
}

.price-container {
  display: flex;
  align-items: center;
  border: 1px solid #eee;
  border-radius: 10rpx;
  background-color: #f9f9f9;
  padding-left: 20rpx;
}

.currency {
  font-size: 32rpx;
  color: #ff6b00;
  font-weight: 600;
}

.price-input {
  flex: 1;
  border: none;
  background: transparent;
  font-weight: 600;
  color: #ff6b00;
}

.radio-group {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.radio-item {
  display: flex;
  align-items: center;
  gap: 15rpx;
  font-size: 28rpx;
  color: #333;
  padding: 15rpx;
  border-radius: 10rpx;
  transition: background-color 0.3s;
}

.radio-item:active {
  background-color: #f5f5f5;
}

.radio-item.active {
  background-color: rgba(41, 121, 255, 0.05);
}

.radio-circle {
  width: 36rpx;
  height: 36rpx;
  border-radius: 50%;
  border: 2rpx solid #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
}

.radio-item.active .radio-circle {
  border-color: #2979ff;
}

.radio-inner {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #2979ff;
}

.btn-box {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  padding: 20rpx 30rpx;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.pay-btn {
  width: 100%;
  height: 90rpx;
  background: linear-gradient(to right, #2979ff, #5e9dff);
  color: #fff;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>