<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="card-header-title">
        <span class="blue-block blue-block-goods-title"></span>操作提现
      </div>

      <el-form ref="assetForm" :model="assetForm" size="small" :rules="rules" label-width="150px" class="ruleFormshop">
        <el-form-item label="当前余额：">
          {{ currentBalance }} 元
        </el-form-item>

        <el-form-item label="可提现金额：">
          {{ withdrawalBalance }} 元
        </el-form-item>

        <el-form-item label="提现中的金额：">
          {{ withdrawalProgress }} 元
        </el-form-item>

        <el-form-item label="提现至：" prop="bank_id">
          <el-select v-model="assetForm.bank_id" placeholder="选择到账银行卡" style="width:420px;">
            <el-option v-for="item in bankList" :key="item.id" :label="formatBankName(item.bank_name,item.bank_account_sn)" :value="item.id"></el-option>
          </el-select>
          <span class="withdraw-tip">
            您还没有账户，<span class="spe-span-a" @click="goToAddBank">去添加</span>
          </span>
        </el-form-item>

        <el-form-item label="提现金额：">
          <el-input v-model="withdrawalBalance" disabled placeholder="全部提现金额" style="width:420px;"/>
          <span class="withdraw-tip">
            不允许手动输入，提现金额为全部的可提现余额，手续费将从您的提现金额中扣除，以实际到账为准（开票以实际到账金额开具）。
            提现金额至少为100元才可以操作提现
          </span>
          <p class="withdraw-tip-spe">当前提现手续费为：0 元</p>
        </el-form-item>

        <el-form-item label="提现密码：" prop="pay_pass">
          <el-input v-model="assetForm.pay_pass" type="password" placeholder="请输入提现密码" style="width:420px;"/>
          <span class="withdraw-tip">
            忘记提现密码？<span class="spe-span-a" @click="goToSetting">重新设定</span>
          </span>
        </el-form-item>

        <el-form-item label="短信验证码：" prop="code" class="spe-code-con-item">
          <el-input v-model="assetForm.code" placeholder="验证码" style="width:420px;">
            <template slot="append">
              <span v-show="show" @click="getCheckCode" style="padding:10px 0;">获取验证码</span>
              <span v-show="!show" class="count">{{count}} s</span>
            </template>
          </el-input>
        </el-form-item>

      </el-form>

      <div class="footer-btn">
        <el-button type="primary" @click="submitForm" :disabled="inSureCashOut" style="margin-right:20px;">确 定</el-button>
        <!--        <el-button @click="resetAssetForm">取 消</el-button>-->
      </div>
    </el-card>
  </div>
</template>
<script>
  import { getMyAssetListData, getCheckCodeData,applyWithdraw } from '@/api/module/bankcard'

  export default {
    name: "withdrawlog",
    data() {
      return {
        //倒计时
        show: true,
        inSureCashOut: false,
        count: '',
        timer: null,

        chargeCount: 0, // 手续费
        seller_id: 0,
        currentBalance: 0,
        withdrawalBalance: 0,
        withdrawalProgress: 0,
        bankList: [],
        assetForm: {
          bank_id: '',
          pay_pass: '',
          code: ''
        },
        // 表单校验
        rules: {
          bank_id: [{required: true, message: "请选择要提现的银行卡", trigger: "change"}],
          code: [{required: true, message: "短信验证码不能为空", trigger: "blur"}],
          pay_pass: [{required: true, message: "提现密码必须填写", trigger: "blur"}]
        },
      };
    },
    created() {
      /** 唯一 商家 id */
      this.seller_id = this.$store.state.user.sellerid;
      /** 我的资产 所有数据 */
      this.getMyAssetList()
    },
    methods: {
      /** 我的资产 所有数据 */
      getMyAssetList() {
        getMyAssetListData( {seller_id:this.seller_id} ).then(res=> {
          if(res.code == 1 && res.data) {
            // 账号资产
            if(res.data.account_info ) {
              this.withdrawalBalance = Number(res.data.account_info.new_balance) / 100;
              this.withdrawalProgress = Number(res.data.account_info.new_frozen_money) / 100;
              this.currentBalance = this.add(this.withdrawalBalance,this.withdrawalProgress);
              this.chargeCount = Number(res.data.account_info.service_fee) / 100;
            }
            // 账户管理
            if(res.data.bank_list) {
              this.bankList = res.data.bank_list;
            }
          }else {
            let msg = res.message ? res.message : '获取数据失败'
            this.$message({type:'error',message: msg});
          }
        });
      },

      // 自定义高精度浮点数运算
      // 加法
      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)
        }
      },
      /** 获取 短信验证码 */
      getCheckCode() {
        let numRegExp = /^[0-9]+(.[0-9]{2})?$/;

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

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

        // 倒计时效果
        this.getCode()

        // 获取验证码接口
        getCheckCodeData().then(res => {
          if (res.code == 1) {
            this.$message({type:'success',message: '验证码发送成功'});
          }else {
            this.$message({type:'error',message: res.message ? res.message : '发送失败'});
          }
        });
      },

      /** 去 资产 首页 添加账户 */
      goToAddBank() {
        this.$router.push({ path: "/system/asset/myAsset" });
      },

      /** 去 设置 密码 */
      goToSetting() {
        this.$router.push({ path: "/system/settings/setpsd" });
      },

      // 暂时 无用
      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);
        }
      },

      // 表单重置
      resetAssetForm() {
        this.$refs['assetForm'].resetFields();
      },

      /** 提交按钮 */
      submitForm() {
        if( Number(this.withdrawalBalance) < 100) {
          this.$message({type: 'warning',message: '提现金额至少为100才可操作提现'});
          return;
        }

        this.$refs["assetForm"].validate(valid => {
          if (valid) {
            applyWithdraw(this.assetForm).then(res => {
              if (res.code == 1) {
                this.getMyAssetList()
                this.resetAssetForm();
                this.$message({type: 'success',message: '提现成功'});
              } else {
                this.$message({type: 'error',message: res.message ? res.message : '提现失败'});
              }
            });
          }
        });
      },

      /** 提现 银行卡名称 + ***后四位卡号 */
      formatBankName(name,num) {
        let newBnakName = '';
        let newNum = '';
        // 为了以防万一，先将num转为字符串
        let numStr = num + '';
        if(numStr && numStr.length > 4) {
          newNum = '****' + numStr.substring(numStr.length-4)
        }else {
          newNum = numStr
        }
        newBnakName = name + ' (' + newNum + ')'

        return newBnakName
      }
    } //methods结束
  };
</script>
<style scoped>
  /deep/ .el-card__body{
    height: 100%;
    overflow: hidden;
  }

  .ruleFormshop {
    height: calc(100% - 110px);
    padding: 20px;
    overflow-y: auto;
  }

  .ruleFormshop .el-form-item {
    margin-bottom: 26px;
  }

  /deep/ .spe-code-con-item .el-input-group__append {
    cursor: pointer;
  }

  .card-header-title {
    height: 45px;
    line-height: 35px;
    font-size: 18px;
    color: #000;
    font-weight: bold;
    border-bottom: 1px solid #eee;
  }

  .blue-block {
    display: inline-block;
    width: 5px;
    height: 24px;
    background: #3A84FF;
    margin: 0 9px 0 0;
    border-radius: 2px;
    vertical-align: middle;
  }

  .footer-btn {
    width: calc(100% + 40px);
    margin-left: -20px;
    padding-top: 20px;
    height:65px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    box-shadow: 0 -8px 9px 1px rgba(51, 51, 51, 0.06);
  }

  .withdraw-tip-spe {
    font-size:12px;
    color: #999;
    margin: 0;
  }

  .withdraw-tip {
    font-size:12px;
    color: #999;
    margin: 5px;
    line-height: 26px;
  }

  .spe-span-a {
    color: #409EFF;
    cursor: pointer;
  }

  .spe-span-a:hover {
    /*color: #46a6ff;*/
  }
</style>
