<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="form" :rules="rules" ref="form" label-width="140px">
      <el-form-item label="姓名：" prop="userName">
        <el-input
          v-model.trim="form.userName"
          placeholder="请输入姓名"
          clearable
          :readonly=true
        />
      </el-form-item>
      <el-form-item label="手机号码：" prop="userPhone">
        <el-input
          v-model.trim="form.userPhone"
          placeholder="请输入手机号码"
          clearable
          maxlength="11"
          minlength="11"
          type="text"
          onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
        />
      </el-form-item>
      <el-form-item label="充值金额：" prop="money">
        <el-input  v-model.trim="form.money"  placeholder="请输入充值金额" type="tel"   @input="inputMoney" min="0.10" />
        <!-- <el-input

          v-model.trim="form.money"
          placeholder="请输入充值金额"
          clearable
          onkeyup="value=value.replace(/^(0+)|[^\d]+/g,'')"
        /> -->
      </el-form-item>
      <el-form-item label="充值到账比例：" prop="proportion">
        <el-input
          v-model.trim="form.proportion"
          placeholder="请输入充值到账比例"
          clearable
          :readonly=true
        />
      </el-form-item>

      <el-form-item label-width="0" style="margin-top:50px;" class="payTypeClass" prop="payType">
        <img src="../../../assets/images/xj.png" alt="" @click="form.payType = 1" v-if="form.payType !== 1">
        <img src="../../../assets/images/xj-c.png" alt="" v-if="form.payType === 1">
        <img src="../../../assets/images/wx.png" alt="" @click="form.payType = 2" v-if="form.payType !== 2">
        <img src="../../../assets/images/wx-c.png" alt="" v-if="form.payType === 2">
        <img src="../../../assets/images/zfb.png" alt="" @click="form.payType = 3" v-if="form.payType !== 3">
        <img src="../../../assets/images/zfb-c.png" alt="" v-if="form.payType === 3">
      </el-form-item>
      <el-form-item label-width="0" style="margin-top:50px;">
        <el-button type="primary" @click="submitForm" style="width:100%">充值</el-button>
      </el-form-item>
    </el-form>
    <div class="qrcode" ref="qrCodeUrl"></div>
    <!-- <img :src="codeUrl" alt="请扫描二维码支付" v-if="codeUrl" title="请扫描二维码支付"> -->
  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import { order, topScanPayApi } from "@/api/recharge/userRecharge";
import { validatePhone } from "@/utils/validate2";
export default {
  name: "admin",
  data() {
    return {
      loading:true,
      // 表单参数
      form: {
        userPhone:'',
        userName:'',
        money:'',
        proportion:'',
        payType:0,
        userId:undefined,
        scene:1
      },
      formSubmit:{
        userPhone:'',
        userName:'',
        money:'',
        payType:0,
        userId:undefined,
        scene:1
      },
      codeUrl:null,
      // 表单校验
      rules: {
        userPhone: [
          { required: true, message: "手机号码不能为空", trigger: "blur",  },
          { validator: validatePhone,  trigger: "blur" },

        ],
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        money: [
          { required: true, message: "充值金额不能为空", trigger: "blur" },
        ],
        proportion: [
          { required: true, message: "充值到账比例不能为空,请返回页面绑定比例关系", trigger: "blur" }
        ],
        payType: [
          { required: true, message: "请选择支付方式", trigger: "blur" }
        ],
      }
    };
  },
  created(){
    if(localStorage.getItem("chongzhi")){
      this.loading = false
      let obj = JSON.parse(localStorage.getItem("chongzhi"))
      this.form.userName = obj.name
      this.form.proportion = obj.proportion
      this.form.userId = obj.sid
      this.form.userPhone = obj.contacts
      localStorage.removeItem('chongzhi')
    }else{
      this.$message.error('请从人员信息充值入口进入该页面')
      setTimeout(() =>{
        this.$router.push({path:'personnel'})
      },1500)
    }
  },
  methods: {
    creatQrCode(url) {
      var qrcode = new QRCode(this.$refs.qrCodeUrl, {
          text: url, // 需要转换为二维码的内容
          width: 250,
          height: 250,
          colorDark: '#000000',
          colorLight: '#ffffff',
          correctLevel: QRCode.CorrectLevel.H
      })
      this.msgSuccess("已生成支付二维码，请扫描二维码进行支付。");
      this.loading = false
    },
    inputMoney(e){ //金额充值效验
      var val = e.replace(/(^\s*)|(\s*$)/g, "")
      if (!val) {
        this.form.money = '';
        return
      }
      var reg = /[^\d.]/g
      // 只能是数字和小数点，不能是其他输入
      val = val.replace(reg, "")
      // // 保证第一位只能是数字，不能是点
      val = val.replace(/^\./g, "");
      // // 小数只能出现1位
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      // // 小数点后面保留2位
      val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
      if(val.indexOf("0") == 0){
        if(val.length == 2){
          val = "0."
        }
      }
      this.$nextTick(() => {
          this.form.money = val;
      })
	  },
    forceUpdate(){ //重置form
      this.form = JSON.parse(JSON.stringify(this.form));
    },

    /** 提交按钮 */
    submitForm(row) {

      if(this.form.money == 0){
        this.msgError("充值金额不能为0元")
      }else{
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(!this.form.payType) return this.msgError("请选择支付方式");
            this.loading = true

            this.formSubmit.userPhone = this.form.userPhone
            this.formSubmit.userName = this.form.userName
            this.formSubmit.money = Number(this.form.money).toFixed(2)
            this.formSubmit.payType = this.form.payType
            this.formSubmit.userId = this.form.userId
            this.formSubmit.userId = this.form.userId
            if (this.form.payType === 1) { //后台现金
              order(this.formSubmit).then(response => {
                this.msgSuccess("已生成支付订单");
                this.codeUrl = '';
                this.loading = false
              });
            } else {

              //移除二维码
              var div = document.getElementsByClassName("qrcode")[0];
              // 获取 div 标签下的所有子节点
              var pObjs = div.childNodes;
              for (var i = pObjs.length - 1; i >= 0; i--) { // 一定要倒序，正序是删不干净的，可自行尝试
                div.removeChild(pObjs[i]);
              }
              topScanPayApi(this.formSubmit).then(response => {
                this.creatQrCode(response.msg)
              })
              // scanPayQr(this.form).then(response => {
              //   this.codeUrl = "data:image/gif;base64," + response.msg;
              //   this.msgSuccess("已生成支付二维码，请扫描二维码进行支付。");
              //   this.loading = false
              // });
            }
            // this.reset()
          }
        })
      }
    },
    // 表单重置
    reset() {
      this.form = {
        userPhone:'',
        userName:'',
        money:'',
        payType:0,
      };
      this.resetForm("form");
    },
  },
}
</script>

<style lang="scss" scoped>
.app-container{
  padding-top: 50px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.payTypeClass{
  img{
    width: 120px;
    height: 90px;
    margin: 0 10px;
  }
}
</style>
