<template>
  <div class="app-container">
     <el-tabs v-model="activeName"  >
      <el-tab-pane label="在线充值" name="first">
           <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="当前余额"  >
             <span style="font-size:20px;color:red;">{{money}}</span>元
          </el-form-item>
           <el-form-item v-if="showRedPacket" label="红包余额"  >
             <span style="font-size:20px;color:red;">{{redMoney}}</span>元
           </el-form-item>
          <el-form-item label="充值金额" prop="money">
            <el-input-number  v-model="form.money" style="width:200px" placeholder="请输入充值金额" />
          </el-form-item>
          <el-form-item label="支付方式" prop="payType">
               <div class="radio">
                 <div class="radio-item">
                     <el-radio v-model="form.payType" :label=1><img class="radio-img" src="../../../assets/image/WeChat_icon30.png">微信</el-radio>
                 </div>
               </div>
            </el-form-item>
            <div class="footer-btn">
              <el-button type="primary" @click="submitForm">充值</el-button>
            </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>
    <el-dialog :title="payTitle" :visible.sync="payVisible" top="10vh" width="550px" class="my-dialog" @close="handleDialogClose">
      <div class="pay-dialog-cont">
        <div class="price">
          <span class="label">应付金额</span>
          <span class="unit">¥</span>
          <span class="num">{{form.money}}</span>
        </div>
        <div class="order-sn">订单编号：{{orderNo}}</div>
        <div class="code-box">
          <div class="qrcode" ref="qrCodeUrl"></div>
        </div>
        <div class="tip-box">
          <span>请使用<span class="orange">微信</span>扫一扫</span>
          <span>二维码完成支付</span>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listCompanyRecharge, getCompanyRecharge, delCompanyRecharge, addCompanyRecharge, updateCompanyRecharge, exportCompanyRecharge } from "@/api/company/companyRecharge";
import { getCompanyInfo } from "@/api/company/company";
import { getConfigByKey } from '@/api/system/config'
import {queryOrder, weixinPay, wxQrPay} from "@/api/company/pay";
import QRCode from 'qrcodejs2'

export default {
  name: "CompanyRecharge",
  data() {
    return {
      qrLoading: false,
      qrPayUrl: '',
      orderNo:"",
      showRedPacket: false,
      payVisible: false,
      payTitle: '微信支付',
      toPayFlag:true,
      activeName:"first",
      timer: null,
      money:0,
      redMoney:0,
      form: {
        payType:1,
      },
      rules: {
        money: [
          { required: true, message: "金额不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value === '' || value === undefined || value === null) {
                callback();
                return;
              }
              const numValue = Number(value);
              if (isNaN(numValue)) {
                callback(new Error('请输入有效的金额'));
                return;
              }
              if (numValue < 0.01) {
                callback(new Error('最小充值金额为0.01元'));
                return;
              }
              if (numValue > 10000) {
                callback(new Error('最大充值金额为10000元'));
                return;
              }
              if (!/^\d+(\.\d{1,2})?$/.test(value.toString())) {
                callback(new Error('金额最多支持两位小数'));
                return;
              }
              callback();
            },
            trigger: 'blur'
          }
        ],
      }
    };
  },
  created() {

    this.getDicts("company_pay_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("company_pay_type").then((response) => {
      this.payTypeOptions = response.data;
    });
    getConfigByKey("course.config").then(response => {
      if(response.data && response.data.configValue) {
        const  config = JSON.parse(response.data.configValue);
        if( config.isRedPackageBalanceDeduction && config.isRedPackageBalanceDeduction==1){
          this.showRedPacket=true
        }
      } else {
        this.showRedPacket = false;
      }
    });
    getCompanyInfo().then(response => {
      this.money = response.data.money;
      this.redMoney = response.data.redPackageMoney;
    });

    redMoney
  },
  beforeDestroy() {
    this.clearTimer();
  },
  methods: {
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    /**
     * 创建二维码
     * @param {string} url - 二维码内容URL
     */
    creatQrCode(url) {
      // 首先清空容器，避免重复创建
      if (this.$refs.qrCodeUrl) {
        this.$refs.qrCodeUrl.innerHTML = '';
      }

      // 使用nextTick确保DOM已更新
      this.$nextTick(() => {
        try {
          if (this.$refs.qrCodeUrl) {
            new QRCode(this.$refs.qrCodeUrl, {
              text: url, // 需要转换为二维码的内容
              width: 200,
              height: 200,
              colorDark: '#000000',
              colorLight: '#ffffff',
              correctLevel: QRCode.CorrectLevel.H
            });
            console.log('二维码创建成功');
          } else {
            console.error('二维码容器不存在');
            this.$message.error('二维码生成失败：容器不存在');
          }
        } catch (error) {
          console.error('二维码创建失败:', error);
          this.$message.error('二维码生成失败，请重试');
        }
      });
    },
    handleDialogClose(){
      clearInterval(this.timer);
      this.timer=null;
    },
    /** 提交按钮 */
    submitForm() {
      var that=this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          that.toPayFlag=false;
          wxQrPay({
            amount: this.form.money
          }).then(res=>{
            if(res.code === 200) {
              this.payVisible = true;
              this.creatQrCode(res.data.qrLink);
              this.orderNo = res.data.orderNo;


              // 轮询订单是否完成
              this.timer = setInterval(()=>{
                queryOrder(res.data.orderNo).then(res=>{
                  if(res.code === 200 && res.data.transactionId != null) {
                    this.$message.success("支付成功！");
                    clearInterval(this.timer);
                    this.timer=null;
                    setTimeout(()=>{
                      window.location.reload()
                    },2000)
                  }
                })
              },1000)
            }
          })
        }
      });
    },
  }
};
</script>
<style  lang="scss" scoped>
.el-radio{
  margin-right: 0px;
}
.radio{
  display: flex;
  align-items: center;


}
.radio-item{
  padding-right:15px;
  .radio-img{
    margin-right: 10px;
  }
  .el-radio{
    display: flex;
    align-items: center;
    .el-radio__label{
      display: flex;
      align-items: center;
    }
  }
}
.footer-btn{
  padding-top: 30px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
}
.pay-dialog-cont{
    padding: 5px 0 50px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .price{
      display: flex;
      align-items: flex-end;
      .label{
        font-size: 14px;
        color: #666666;
        margin-right: 10px;
        line-height: 20px;
      }
      .unit{
        font-size: 16px;
        font-weight: bold;
        color: #FF6633;
        margin-right: 5px;
        line-height: 20px;
      }
      .num{
        font-size: 24px;
        font-weight: bold;
        color: #FF6633;
      }
    }
    .order-sn{
      font-size: 14px;
      color: #666666;
      line-height: 1;
      margin-top: 20px;
    }
    .code-box{
      width: 200px;
      height: 200px;
      margin-top: 40px;
      img{
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .tip-box{
      margin-top: 30px;
      display: flex;
      align-items: center;
      flex-direction: column;
      font-size: 14px;
      color: #333333;
      line-height: 22px;
      .orange{
        color: #FF6633;
      }
    }
  }
</style>
