<template>

  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <p style="font-size: 18px; float:left;">提现申请</p>
      </div>
      <el-row>
        <el-col :span="24" class="card-box">
          <!-- <span>商户信息</span> -->
          <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="ruleFormshop">
            <el-form-item label="当前余额">
              {{sellerinfo.Balance}}元
            </el-form-item>
            <el-form-item label="提现中的金额">
              {{sellerinfo.FrozenMoney}}元
            </el-form-item>
            <el-form-item label="可提现金额">
              {{drawableCash}}元
            </el-form-item>
            <el-form-item label="手续费">
              当前手续费为{{newFee}}元
            </el-form-item>
            <el-form-item label="银行卡" prop="bank_id">
              <el-select v-model="form.bank_id" placeholder="选择到账银行卡" style="width:260px;">
                <el-option v-for="item in banklist" :key="item.Id"
                           :label="item.bank_name ? item.bank_name : item.bank_account_name"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="提现金额" prop="amount">
              <el-input v-model="form.amount"
                        @blur="onInputBlur($event)"
                        placeholder="提现金额大于等于100"
                        style="width:260px;"/>
            </el-form-item>
            <el-form-item label="短信验证码" prop="verifycode" class="spe-code-con-item">
              <el-input v-model="form.verifycode" placeholder="验证码" style="width:260px;">
                <template slot="append">
                  <span v-show="show" @click="getCheckCodeFn">获取验证码</span>
                  <span v-show="!show" class="count">{{count}} s</span>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="支付密码" prop="pwd">
              <el-input v-model="form.pwd" type="password" placeholder="请输入提现密码" style="width:260px;"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm" :disabled="inSureCashOut">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>
<script>
  import {getSellerInfo, getBankcardList, addWithdrawlog, getCheckCode} from '@/api/module/withdrawlog'

  export default {
    name: "withdrawlog",
    data() {
      return {
        //倒计时
        show: true,
        inSureCashOut: false,
        count: '',
        timer: null,
        //提现金额
        amount: 0,
        // 遮罩层
        loading: true,
        // 选中数组
        sellerId: 0,
        sellerinfo: {},
        banklist: [],
        //手续费
        newFee: 0,
        // 可提现金额
        drawableCash: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: true,
        // 表单参数
        form: {
          bank_id: '',
          amount: ''
        },
        // 表单校验
        rules: {
          bank_id: [{required: true, message: "请选择要提现的银行卡", trigger: "change"}],
          amount: [{required: true, message: "提现金额不能为空", trigger: "blur"}],
          verifycode: [{required: true, message: "短信验证码不能为空", trigger: "blur"}],
          pwd: [{required: true, message: "支付密码必须填写", trigger: "blur"}]
        }
      };
    },
    watch: {},
    created() {
      this.sellerId = this.$store.state.user.sellerid;
      this.getList();
    },
    methods: {
      //-----------
      // 自定义高精度浮点数运算
      // 加法
      add(arg1, arg2) {
        let r1, r2, m, result;
        try {
          //取小数位长度
          r1 = arg1.toString().split(".")[1].length;
          r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
          r1 = 0;
          r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));		//计算因子
        result = (arg1 * m + arg2 * m) / m;
        result = result.toFixed(2);
        return result;
      },
      // 减法
      minus(arg1, arg2) {
        return this.add(arg1, -arg2);
      },
      //-----------

      //倒计时
      getCode() {
        const TIME_COUNT = 60;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.show = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.show = true;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
      },
      getCheckCodeFn() {
        let numRegExp = /^[0-9]+(.[0-9]{2})?$/;
        let numberMoney = Number(this.form.amount);
        let numberCash = Number(this.drawableCash);

        if(this.form.bank_id === '') {
          this.$refs.form.validateField("bank_id");
          return;
        }
        if(this.form.amount === '') {
          this.$refs.form.validateField("amount");
          return;
        }

        if(!numRegExp.test(this.form.amount)) {
          this.$message({ type: 'warning',message: '提现金额只能输入大于 0 的数字'});
          return;
        }

        if (numberMoney > numberCash) {
          this.$message({type: 'warning',message:'提现金额不足'});
          return;
        } else if (numberMoney < 100) {
          this.msgError("提现金额必须大于等于100");
          return;
        }

        if (this.sellerId <= 0) {
          this.msgError("商户信息错误");
          return;
        }

        // 倒计时效果
        this.getCode()
        getCheckCode({sellerId: this.sellerId}).then(response => {
          if (response.code == 0) {
            this.msgSuccess(response.msg);
          }
        });

      },

      onInputBlur(event) {
        let fee = 0.006;
        this.form.amount = event.target.value;
        let numRegExp = /^[0-9]+(.[0-9]{2})?$/;
        let numberMoney = Number(this.form.amount);
        //debugger
        let numberCash = Number(this.drawableCash);
        if(this.form.amount !== '') {
          if(!numRegExp.test(this.form.amount)) {
            this.$message({ type: 'warning',message: '提现金额只能输入大于 0 的数字'});
            return;
          }

          if (Number(this.form.amount) > Number(this.drawableCash)) {
            this.$message({type: 'warning',message:'提现金额不足！'});
            return;
          }

          if (Number(this.form.amount) < 100) {
            this.$message({type: 'warning',message:'提现金额需大于或者等于 100'});
            return;
          }
          this.newFee = (this.form.amount * fee + 1).toFixed(2);
        }
      },
      //获取商户的信息
      getSellerInfoFn() {
        const sellerid = this.sellerId;
        getSellerInfo({sellerId: sellerid}).then(response => {
          this.sellerinfo = response.data;
          this.sellerinfo.Balance = response.data.Balance / 100;
          this.sellerinfo.FrozenMoney = response.data.FrozenMoney / 100;
          this.drawableCash = this.minus(this.sellerinfo.Balance, this.sellerinfo.FrozenMoney);
        });
      },
      //获取商户的银行卡列表
      getBankcardList() {
        getBankcardList({sellerId: this.sellerId}).then(response => {
          this.banklist = response.data.data;
          //debugger
        });
      },

      /** 查询商户提现列表 */
      getList() {
        this.getSellerInfoFn();
        this.getBankcardList();
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },

      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            let numberMoney = Number(this.form.amount);
            let numberCash = Number(this.drawableCash);
            let numberFee = Number(this.newFee);

            // 提现金额 + 手续费 <= 可提现金额
            // add   minus
            // 提现金额 + 手续费
            let feeAddAmount = this.add(numberFee,numberMoney);
            let isabled = Number(this.minus( numberCash, feeAddAmount) );

            this.form.sellerId = this.sellerId;
            // 再次校验 提现信息
            if(!this.form.sellerId) {
              this.$message({type: 'error',message: '商户信息有误！'});
              return;
            }
            if(numberMoney < 100 ) {
              this.$message({type: 'error',message: '提现金额不能小于100'});
              return;
            }
            if( (numberMoney > numberCash) ) {
              this.$message({type: 'error',message: '提现金额不足！'});
              return;
            }

            if( isabled < 0 ) {
              this.$message({type: 'error',message: '本次操作提现后，【当前余额】不足以支付本次提现的手续费用，请您重新输入提现金额'});
              return;
            }

            this.form.amount = Number(this.form.amount);

            // console.log(this.newFee);
            // console.log(feeAddAmount,isabled);
            //
            // return;
            addWithdrawlog(this.form).then(response => {
              if (response.code === 1) {
                this.msgSuccess(response.message);
                this.getList();
              }
              else {
                this.$message({type: 'error',message: response.message});
              }
            });
          }
        });
      },
    } //methods结束
  };
</script>
<style scoped >
  .ruleFormshop {
    width: 500px;
    margin: 20px 0 0 120px;
  }

  /deep/ .spe-code-con-item .el-input-group__append {
    cursor: pointer;
  }
  /deep/ .el-card__body{
    height :calc(100% - 50px);
    overflow-y: scroll;
  }
</style>
