<template>
  <div class="Wallet">
    <Title class="page-title" title="余额提现" titleColor="#000" @goback="goback" show_back="true" arrowColor="black"></Title>
    <div class="wallet_container">
      <div class="wallet_content">
        <div class="wallet_money">
          账户余额<span class="money_num">{{this.money_num|moneyFormatter}}</span><span
          style="color:#8a8a8a;">元</span>
        </div>
        <div
          class="wallet_money"
          style="margin-top:0.6rem">
          提现金额
        </div>
        <div class="money_input">
          <span class="dollar">￥</span>
          <input
            type="text"
            v-bind:placeholder="`可提现到微信钱包${MoneyNum}元`"
            v-model="cash_money_num"
            @input="checkMoney"
            @blur="refreshPage"
          >
          <span
            class="get_all"
            @click="cashAll"
          >全部</span>
        </div>
        <div class="seprate_line"></div>
        <div class="desc">
          单次提现金额至少0.3元,最多100元
        </div>
        <div class="cash_button" @click="cashMoney"></div>
      </div>
      <div class="wallet_text_btn">
        <div class="kefu_btn" @click="concatCustom">联系客服</div>
        <div class="line"></div>
        <div class="cash_list_btn" @click="toRedpackLog">提现明细</div>
      </div>
      <div class="ad_banner" @click="toggleRedpack" v-if="!open_platform">
        <div class="ad_avatar">
          <img :src="userData.avatar" alt="">
        </div>
        <div class="ad_msg">
          <div class="ad_title">恭喜你获得一个红包</div>
          <div class="ad_desc">点击立即领取！</div>
        </div>
        <div class="ad_btn">
          领取
        </div>
      </div>
    </div>
    <!--<div class="concat_custom">-->
    <!--<span-->
    <!--class="concat"-->
    <!--@click="concatCustom"-->
    <!--&gt;联系客服</span>-->
    <!--</div>-->
    <div class="promote">
    </div>
    <div class="modal" v-if="modalShown">
      <Modal v-on:close="closeModal" v-on:confirmModal="closeModal" v-bind:title="modalTitle" v-bind:desc="modalDesc"
             :option="modalOption"></Modal>
    </div>
    <Loading v-if="isLoading"></Loading>
    <FollowDialog :isKefu="isKefu" v-if="isShowFollow" @close="toggleFollowDialog"></FollowDialog>
    <RedpackDialog v-if="isShowRedpack" @close="toggleRedpack" :withdrawData="withdrawData"
                   :type="redpackType"></RedpackDialog>
  </div>
</template>

<style scoped>
  .ad_banner {
    width: 6.9rem;
    height: 1.4rem;
    display: flex;
    align-items: center;
    background: #fff;
    padding: .2rem;
    position: absolute;
    bottom: .5rem;
    left: 50%;
    margin-left: -3.65rem;
  }

  .ad_avatar {
    width: 1rem;
    height: 1rem;
    margin-right: .2rem;
  }

  .ad_avatar img {
    width: 100%;
    height: 100%;
  }

  .ad_msg {
    flex: 1;
  }

  .ad_title {
    font-size: .32rem;
    color: rgba(51, 51, 51, 1);
    margin-bottom: .16rem;
    text-align: left;
  }

  .ad_desc {
    font-size: .28rem;
    color: rgba(165, 165, 165, 1);
    text-align: left;
  }

  .ad_btn {
    width: 1.3rem;
    height: .72rem;
    border: .02rem solid rgba(237, 195, 101, 1);
    border-radius: .12rem;
    display: flex;
    justify-content: center;
    align-items: center;
    color: rgba(237, 195, 101, 1);
    font-size: .32rem;
  }

  .wallet_text_btn {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: .5rem;
  }

  .kefu_btn, .cash_list_btn {
    color: rgba(87, 107, 149, 1);
    font-size: 0.3rem;
    margin: 0 .25rem;
  }


  .line {
    width: .02rem;
    height: .22rem;
    background: rgba(204, 204, 204, 1);
  }
</style>

<style>
  .Wallet {
    width: 100%;
    height: 100%;
    background: #f1f1f1;
  }

  .Wallet .title_container {
    color: #282828;
    background: #ffffff;
    height: 0.9rem;
    position: fixed;
    top: 0;
    width: 100%;
  }

  .Wallet .title_container > div > a {
    color: #282828;
  }

  .big .Wallet {
    padding-top: 0.9rem;
  }

  .big .Wallet .title_container {
    height: 0.9rem;
  }

  .wallet_container{
    width: 100%;
    padding-top: 1.5rem;
  }

  .wallet_content {
    width: 6.9rem;
    /*height: 6.04rem;*/
    margin: 0 auto 0;
    padding: .8rem 0;
    /*margin-left: calc((100% - 6.9rem) / 2);*/
    background: #ffffff;
    /*padding: 0.5rem 0.4rem 0.6rem 0.4rem;*/
  }

  .wallet_content div {
    margin-left: .4rem;
  }

  .wallet_money {
    font-size: 0.28rem;
    color: #282828;
    text-align: left;
  }

  .wallet_content span.money_num {
    font-size: 0.48rem;
    color: #8a8a8a;
    display: inline-block;
    margin-left: 1rem;
  }

  .Wallet .money_input {
    height: 0.5rem;
    width: 6.1rem;
    margin-top: 0.6rem;
    text-align: left;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .Wallet .money_input span.dollar {
    font-size: 0.48rem;
    color: #282828;
    /*margin-bottom: .2rem;*/
  }

  .Wallet .money_input input {
    border: 0;
    outline: 0;
    font-size: 0.48rem;
    color: #282828;
    display: inline-block;
    /*margin-left: 0.4rem;*/
    width: 4rem;
  }

  .Wallet .money_input .get_all {
    float: right;
    color: rgba(87, 107, 149, 1);
    font-size: 0.3rem;
  }

  .Wallet .concat_custom {
    /*width: 100%;*/
    padding-top: .5rem;
    padding-right: 0.3rem;
    /*padding: 0.2rem;*/
    text-align: right;
    /*padding-bottom: 0;*/
  }

  .Wallet .concat_custom .concat {
    width: 100%;
    text-align: right;
    color: #52526e;
    font-size: 0.3rem;
  }

  ::-webkit-input-placeholder {
    color: #cccccc;
    font-size: 0.28rem;
  }

  .seprate_line {
    width: 6.1rem;
    border-bottom: 1px solid #e8e8e8;
    margin: 0.2rem 0;
  }

  .Wallet .desc {
    color: #8a8a8a;
    font-size: 0.24rem;
    text-align: left;
  }

  .Wallet .cash_button {
    width: 6.1rem;
    height: 0.8rem;
    background: url("../assets/btn_tx.png") 0 0 no-repeat;
    background-size: contain;
    margin-top: 0.4rem;
  }
</style>

<script>
  // 钱包
  import Title from "@/components/Title.vue";
  import Modal from "@/components/Modal.vue";
  import Loading from "@/components/Loading.vue";
  import FollowDialog from "@/components/FollowDialog.vue";
  import RedpackDialog from "@/components/RedpackDialog.vue";
  import {balanceQuery, balanceWithdraw, withdraw_img} from "@/components/axios/api";

  export default {
    name: "Wallet",
    components: {
      Title,
      Modal,
      Loading,
      FollowDialog,
      RedpackDialog
    },
    data() {
      return {
        isShowRedpack: false,
        isShowFollow: false,
        isKefu: 1,
        money_num: 0,
        cash_money_num: null,
        modalShown: false,
        appid: "",
        code: "",
        uid: "",
        loginFail: false,
        isLoading: false,
        userData: {},
        withdrawData: {},
        open_platform: true,
        redpackType: 1
      };
    },
    methods: {
      toRedpackLog() {
        this.$router.push({name: "RedpackLog"});
      },
      toggleRedpack() {
        this.isShowRedpack = !this.isShowRedpack
        if (!this.isShowRedpack) {
          if (this.redpackType == 1) {
            this.redpackType = 2
            this.getRedpackImg("task")
          }
        }
      },
      getRedpackImg(position) {
        withdraw_img(position).then(res => {
          if (res.code == 0) {
            this.withdrawData = res.data
            this.open_platform = res.data.open_platform
            if (this.redpackType == 1 && !this.open_platform) {
              this.toggleRedpack()
            }
          }
        })
      },
      toggleFollowDialog() {
        this.isShowFollow = !this.isShowFollow
      },
      refreshPage() {
        setTimeout(() => {
          const scrollHeight = document.documentElement.scrollTop || document.body.scrollTop || 0;
          window.scrollTo(0, Math.max(scrollHeight - 1, 0));
        }, 100);
      },
      goback() {
        this.$router.push({name: "UserCenter"})
      },
      cashAll() {
        // console.log('触发赋值',this.money_num);
        if (this.money_num > 100) {
          this.cash_money_num = 100;
        } else {
          this.cash_money_num = this.money_num;
        }
      },
      cashMoney() {
        console.log("提现操作");
        if (this.cash_money_num != 0 && !this.cash_money_num) {
          this.showModal("温馨提示", "请输入提现金额");
          return;
        }
        if (this.cash_money_num < 0.3) {
          this.showModal("温馨提示", "金额不足0.3元,无法提现");
          return;
        }
        this.isLoading = true;
        balanceWithdraw(this.cash_money_num)
          .then(result => {
            console.log(result);
            this.isLoading = false;
            if (result.code == 0) {
              this.cash_money_num = null;
              this.getBalanceQuery();
              this.showModal(
                "温馨提示",
                "提现申请成功，预计1-5个工作日内提到微信钱包"
              );
            } else {
              this.showModal("温馨提示", "提现失败，请稍后重试或联系客服");
            }
          })
          .catch(e => {
            this.showModal("温馨提示", "提现失败，请稍后重试或联系客服");
            this.isLoading = false;
          });
      },
      getBalanceQuery() {
        balanceQuery().then(result => {
          console.log(result);
          if (result.code == 0) {
            this.money_num = result.data.balance;
            if (result.data.withdraw_auth) {
              this.appid = result.data.withdraw_appid;
              // this.getOpenId();
            }
          }
        });
      },
      checkMoney(e) {
        console.log(e)
        let judge = this.money_num > 100 ? 100 : this.money_num;
        if (e.inputType != "deleteContentBackward") {
          this.cash_money_num = (this.cash_money_num + '').replace(/[^\d.]/g, "");
          this.cash_money_num = (this.cash_money_num + '').replace(/^\./g, "");
          this.cash_money_num = (this.cash_money_num + '').replace(/\.{2,}/g, ".");
          this.cash_money_num = (this.cash_money_num + '').replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
        }
        if (this.cash_money_num > judge) {
          this.cash_money_num = judge;
        }
        console.log("checkMoney", this.cash_money_num);
      },
      showModal(title, desc, option) {
        this.modalTitle = title || "";
        this.modalDesc = desc || "";
        this.modalOption = option || {}
        this.modalShown = true;
      },
      closeModal() {
        this.modalShown = false;
        if (this.loginFail) {
          this.loginFail = false;
          let oldHref = window.location.href;
          let newHref = oldHref.replace(window.location.search, "");
          newHref = newHref.replace(window.location.hash, "#/MyData");
          location.replace(newHref);
        }
      },
      getOpenId() {
        document.title = "微信授权中";
        var code = this.GetUrlParame("code"); // 截取code
        console.log(code);
        let local_hash = location.hash;
        window.localStorage.setItem("local_hash", local_hash);
        let redirect_uri = encodeURIComponent(
          `${location.origin}${location.pathname}${local_hash}`
        );
        let url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
          this.appid
          }&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
        console.log("url", url);
        if (!code) {
          location.replace(url);
        } else {
          console.log("拿到code", code);
          console.log("请求登录");
          balanceWithdraw("", code).then(result => {
            console.log(result);
            if (result.code != 0) {
              this.showModal("温馨提示", "服务器繁忙，请稍后重试");
              this.loginFail = true;
            }
          });
        }
      },
      // 截取code
      GetUrlParame(parameName) {
        /// 获取地址栏指定参数的值
        /// <param name="parameName">参数名</param>
        // 获取url中跟在问号后面的部分
        var parames = window.location.search;
        // 检测参数是否存在
        if (parames.indexOf(parameName) > -1) {
          var parameValue = "";
          parameValue = parames.substring(
            parames.indexOf(parameName),
            parames.length
          );
          // 检测后面是否还有参数
          if (parameValue.indexOf("&") > -1) {
            // 去除后面多余的参数, 得到最终 parameName=parameValue 形式的值
            parameValue = parameValue.substring(0, parameValue.indexOf("&"));
            // 去掉参数名, 得到最终纯值字符串
            parameValue = parameValue.replace(parameName + "=", "");
            return parameValue;
          }
          return "";
        }
      },
      concatCustom() {
        this.toggleFollowDialog()
        // window.location.href = "https://mp.weixin.qq.com/s/YFO5CA_iKSBdnXbxJZAC-Q"
      }
    },
    props: ["money"],
    computed: {
      MoneyNum() {
        let moneyNum = 0;
        if (this.money_num > 100) {
          moneyNum = 100;
        } else {
          if (this.money_num < 0.3) {
            moneyNum = 0;
          } else {
            moneyNum = this.money_num;
          }
        }
        return moneyNum;
      }
    },
    created() {
      this.getRedpackImg()
      this.getBalanceQuery();
      if (window["userData"]) {
        this.userData = window["userData"];
      } else {
        let localUserData = localStorage.getItem("userData");
        if (localUserData) {
          window["userData"] = JSON.parse(localUserData);
          this.userData = window["userData"];
        }
      }
    },
    filters: {
      moneyFormatter(val) {
        if (val && !isNaN(val)) {
          return Number(val).toFixed(2);
        } else {
          return "0.00";
        }
      }
    }
  };
</script>
