<template>
  <div class="cash">
    <inner-header title="资金提现"></inner-header>
    <section class="content">
      <h2 v-if="isIdCard">提现到银行卡（
        <span v-if="userInfo.bankAccount">{{userInfo.bankAccount}}</span>
        <span v-else><a href="/wo/account_manage">去绑定银行卡</a></span>
        ）</h2>
      <h2 v-else>提现到支付宝（{{userInfo.alipay}}）</h2>
      <div class="input-box">
        <el-input class="cash-input" placeholder="最少提现10元，每日上限3万元" v-model="coins"></el-input>
        <span class="input-icon">¥</span>
        <el-button type="text" class="get-all" @click="doGetAll">全部提现</el-button>
      </div>
      <div class="balance">
        可用余额
        <span>￥{{(+userCanWithdrawAmount) || 0}}</span>元
      </div>
      <el-button @click="doGet" class="get-btn" type="primary">提现</el-button>
      <p class="remind-time">预计3~5个工作日到账</p>
      <p>提现说明</p>
      <!--银行卡-->
      <div class="reminds" v-if="isIdCard">
        <div>1.只有整包项目、云端工作项目薪酬，才支持提现到银行卡</div>
        <div>
          2.请确认银行卡账号和实名认证信息保持一致，如需修改银 行卡账号，请前往
          <a href="/setting/user">实名个人信息</a>
        </div>
        <div>3.提现成功后，会在3-5个工作日内到账，节假日可能会稍有延时，请耐心等待，如长时间未到账( 超过5个工作日),可联系在线客服
          <!--<a href="/setting/user">在线客服</a>-->
        </div>
      </div>

      <!--支付宝-->
      <div class="reminds" v-else>
        <div>1.提现非客栈转入的资金需要收取{{rate}}的手续费</div>
        <div>2.提现成功后，会在3-5个工作日内到账，节假日可能会稍有延时，请耐心等待</div>
        <div>
          3.请确认支付宝账号和实名认证信息保持一致，如需修改支付宝账号，请前往
          <a href="/setting/user">实名个人信息</a>
        </div>
        <div>4.如提现失败，或长时间未到账( 超过5个工作日),可联系在线客服</div>
        <div>5.为防止非法套现，充值的金额30个工作日后方可提现。</div>
      </div>
    </section>
    <el-dialog title="手机验证码确认" :visible.sync="dialogShow">
      <h1 class="dialog-h1">已向您的手机{{userinfo.mobile}}发送验证码</h1>
      <div class="ver-input">
        请输入验证码
        <el-input v-model="ver"></el-input>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="doDialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <SuccessToast :isShowToast="isShowToastSuccess" @close="isShowToastSuccess=false"/>

    <el-dialog @close="qrcodeClose" title="温馨提示" :visible.sync="centerDialogVisible" width="350px" center>
        <p class="qrcode-tips">请打开支付宝扫码以下二维码</p>
        <div class="qrcode-img">
            <img :src="qrcodeBase64" />
        </div>
    </el-dialog>

  </div>
</template>

<script>
import InputVer from "@/components/input/ver";
import InnerHeader from "@/components/inner_header";
import SuccessToast from "@/components/wo/successToast";
const Max_Money = 30000
const Min_Money = 10
import QRCode from "qrcode";

export default {
  components: {
    InputVer,
    InnerHeader,
    SuccessToast
  },
  data() {
    return {
      alipayInfo: {},
      dialogShow: false,
      // 提现金额
      coins: "",
      // 验证码
      ver: "",
      // 费率
      rate: "",
      isIdCard: false, //是否是提现到银行卡
      isShowToastSuccess: false, //是否展示成功后的提示
      qrcodeBase64: "",
      centerDialogVisible:false,

      timer:null,
    };
  },
  computed: {
    coinInfo() {
      return this.alipayInfo && this.alipayInfo.coinInfo || {};
    },
    userCanWithdrawAmount() {
      const {balance=0, incomeTaxBalance=0} = this.alipayInfo && this.alipayInfo.coinInfo || {}
      return this.isIdCard ? incomeTaxBalance : balance
    },
    userInfo() {
      return this.alipayInfo && this.alipayInfo.userInfo || {};
    }
  },
  created() {
    console.log('this.$route.query', this.$route.query)
    //type 1-支付宝 2-银行卡 默认是1
    const {type=1} = this.$route.query || {}
    this.isIdCard = Number(type) === 2
  },
  mounted() {
    this.getAlipayInfo();
    this.getRate();
  },
  methods: {
    /**
     * 全部提现
     */
    doGetAll() {
      this.coins = this.userCanWithdrawAmount;
      if (this.coins > Max_Money) {
        this.$message.info("每日最多可提现3万元")
        this.coins = Max_Money
      }
    },
    /**
     * 获取支付宝信息
     */
    async getAlipayInfo() {
      let res = await this.$axios.$post("/api/user/get_cash_info");
      console.log(res);
      if (res) {
        this.alipayInfo = res.data;
        const {alipay, bankAccount} = res.data.alipayInfo || {}
        //银行卡提现，但没绑定时 提示
        if (!bankAccount && this.isIdCard === 2) {
          this.$message.info("请前往程序员客栈APP绑定银行卡！")
        }
      }
    },
    /**
     * 获取费率
     */
    async getRate() {
      let res = await this.$axios.$post(`/api/pay/get_withdraw_rate`);
      console.log(res);
      if (res) {
        this.rate = res.data.withdraw_rate;
      }
    },
    /**
     * 点击提现
     */
    async doGet() {
      if (!(this.coins + "").replace(/[^\d\.]/g, "")) {
        this.$message("请输入提现金额");
        return;
      }
      //最少
      if (Min_Money > this.coins) {
        this.$message(`单次最少提现${Min_Money}元`);
        return;
      }
      //最多
      if (this.coins > Max_Money) {
        this.$message.info("每日最多可提现3万元")
        this.coins = Max_Money
      }
      //最多允许提现2位小数
      let docRight = (this.coins + "").split(".")[1]
      console.log("docRight", docRight)
      if (docRight && docRight.length > 2) {
        this.$message(`最多允许输入2位小数`);
        return;
      }
      // 错误处理
      let coinsNum = +(this.coins + "").replace(/[^\d\.]/g, "");
      if (
        !coinsNum ||
        !(this.coins + "").match(/^\d+(\.\d{1,2}){0,1}$/) ||
        coinsNum <= 1
      ) {
        this.$message("请输入正确的提现金额");
        return;
      }
      //余额不足
      if (coinsNum > this.userCanWithdrawAmount) {
        this.$message("可提现余额不足");
        return;
      }

      // 判断是否已过人脸
      let resutCheckUserCertInfo = await this.$axios.$post("/uapi/user/realName/check");


      if(resutCheckUserCertInfo.status != 1){
        this.$message.error(resutCheckUserCertInfo.info)
        return
      }

      let isFace = resutCheckUserCertInfo.data.is_face === 1
      let isNameCert = resutCheckUserCertInfo.data.type === 1

      if(!isNameCert){
        // 如果没有实名，跳到实名认证页，并需要过人脸
        location.href = '/frontend/name_cert?is_face_check=1'
        return
      }

      if(!isFace) {

        // 询问是否是否人脸认证
        let res = await this.isFaceComfirmByAsync()
        
        if(!res){
          return
        }
        // 请求二维码
        await this.callFaceQrcode()
        // 启动定时器
        let resutByTimer = await this.startCheckIsFaceTimer()

        if(resutByTimer){
          // 关闭二维码框
          this.centerDialogVisible = false
        }
      }

      this.dialogShow = true;
      let res = await this.$axios.$post("/api/user/send_mobile_auth_code", {
        mobile: this.userinfo.mobile,
        type: 3
      });
    },

    // 提示框async 包装
    async isFaceComfirmByAsync(){
      let that = this;
      return new Promise(function(resolve) {
        that.$confirm('为了您的资金安全，本次操作需要进行人脸认证。', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          resolve(true)
        })
        .catch(() => {
          resolve(false)
        })
      })
    },
    /**
     * 检查是否完成人脸认证
     */
    async checkIsFace(){
      try{
        let res = await this.$axios.$post("/uapi/user/realName/check");
        if(res.status == 1 && res.data.is_face === 1){
          return true
        }else{
          return false
        }

      }catch(e){
        return false
      }
    },
    /**
     * 关闭二维码回调
     */
    qrcodeClose(){
      clearInterval(this.timer)
      this.timer = null
    },
    /**
     * 检查是否过人脸定时器
     */
    startCheckIsFaceTimer(){
      let that = this
      return new Promise(function(resolve){
        that.timer = setInterval(async () => {
          let isFace = await that.checkIsFace()
          // console.log("请求验证")
          if(isFace){
            clearInterval(that.timer)
            that.timer = null
            resolve(true)
          }
        },3000)
      })
    },
  /**
     * 获取人脸二维码
     */
     async callFaceQrcode(){
      try{

         let res = await this.$axios.$post("/uapi/user/realName/face");
        let qrcode = res.data.kezhan_url;


        // let qrcode = "http://baidu.com"
        let that = this;
        QRCode.toDataURL(
            qrcode, {
                errorCorrectionLevel: "H",
                margin: 1,
                width: 300
            },
            function (err, url) {
                that.qrcodeBase64 = url;
                that.centerDialogVisible = true
            }
        );

      }catch(e){
        return false
      }
    },

    /**
     * 点击验证码
     */
    doDialogConfirm() {
      if (!this.ver.trim()) {
        this.$message("请输入验证码");
        return;
      }
      this.$confirm("确定要进行取现操作吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        this.withdrawFn()
      });
    },

    /** 提现到支付宝 **/
    async withdrawFn() {
      let res = null
      if (this.isIdCard) {
        res = await this.$axios.$post("/api/account/takeSalary", {
          coins: +this.coins,
          auth_code: this.ver
        });
      } else {
        res = await this.$axios.$post("/api/account/take_coins_to_alipay", {
          coins: +this.coins,
          payee_real_name: this.userinfo.realname,
          alipay_account: this.userInfo.alipay,
          auth_code: this.ver
        });
      }
      if (res && Number(res.status) === 1) {
        this.$message({
          type: "success",
          message: res.info || "提现成功"
        });
        this.dialogShow = false
        setTimeout(() => {
          this.isShowToastSuccess = true
          this.getAlipayInfo()
          this.coins = 0
        }, 1000);
      }
    }
  }
};
</script>

<style scoped>
.cash {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* height: 590px; */
  background: white;
  padding-bottom: 20px;
}
h2 {
  margin: 64px 0 8px;
  font-size: 14px;
}
.input-box {
  position: relative;
  width: 396px;
}
.cash-input {
  width: 396px;
}
.input-icon,
.get-all {
  position: absolute;
}
.input-icon {
  top: 10px;
  left: 16px;
  font-size: 20px;
}
.get-all {
  top: 0;
  right: 20px;
}
.balance {
  color: #999;
  font-size: 13px;
  margin: 6px 0 24px;
}
.balance span {
  color: #ffa81a;
}
.get-btn {
  width: 244px;
}
.remind-time {
  color: #999;
  font-size: 12px;
  margin: 8px 0 28px;
}
.reminds {
  width: 396px;
  color: #919aa7;
  margin-top: 6px;
  line-height: 32px;
}
.ver-input {
  display: flex;
  align-items: center;
  justify-content: center;
}
.ver-input .el-input {
  margin-left: 10px;
  width: 280px;
}
.dialog-h1 {
  margin: 10px 0;
  text-align: center;
}
.qrcode-tips{
  text-align: center;
}
</style>
