<template>
  <div>
    <div v-if="data.length > 0 " class="bettingTable">
      <div>
        <div v-for="(item,index) in data" :key="index" style="border-bottom:.02rem solid #bbb" >
          <div class="list-header row item-center allAlignment list">
            <p class="br05 row center" style="padding:.05rem .1rem;background:#F00;">{{item.playName}}</p>
            <div @click="deleteList(index,item.id,item.p_code)" class="row center"
              style="width:.26rem;height:.26rem; border-radius:50%;background:#F76649;"  >
              <img src="@/assets/st-imges/del.png">
            </div>
          </div>
          <div class="list-body list" >
            <div class="condition row item-center">
              <span >{{item.name}}</span>
              <span v-if="item.p_code != 'capot'" style="padding-left:.1rem;">{{item.condition}}</span>
              <p style="padding-left:.1rem;">
                @
                <span style="color:#F76649">{{item.odds}}</span>
              </p>
              <!-- <span> <i>01 / 04</i></span> -->
            </div>
            <div class="duel row item-center">
              <p>{{item.home_team}}</p>
              <span style="color:#F76649;font-size:.12rem;">&emsp;vs&emsp;</span>
              <p>{{item.guest_team}}</p>&nbsp;
            </div>
          </div>
          <div class="list-input row item-center allAlignment list">
            <div class="br05" style="border:.01rem solid #F76649;position: relative;">
              <input type="text" @click="activation(index)" oncopy="return false" onpaste="return false"  @keyup="keyMatch($event,index)" v-model=" item.money "  placeholder="投注额">
              <img @click="removeData(index)"
                style="position: absolute;width:.2rem;height:.2rem;right:.1rem;top:.05rem;"
                src="@/assets/st-imges/delbetting.png"
              >
            </div>
            <div class="br05 canWin row item-center" >{{item.money ? (item.money*item.odds).toFixed(2) :'可赢额' }}</div>
          </div>
          <div class="prompt-status" v-if="item.msg">
            <img src="@/assets/st-imges/warning.png" style="width:0.2rem;vertical-align:middle;margin-right:0.1rem"/>
            <span>{{item.msg}}</span>
          </div>
          <div v-show="state == index" class="key">
            <div>
              <div class="row average item-center">
                <p @click ="addNum(index,100)">+100</p >
                <p @click ="addNum(index,500)">+500</p>
                <p @click ="addNum(index,1000)">+1000</p>
              </div>
              <div class="row average item-center">
                <p @click ="addNum(index,5000)">+5000</p>
                <p @click ="addNum(index,10000)">+10000</p>
                <p @click ="addNum(index,50000)">+50000</p>
              </div>
            </div>
          </div>
          <!-- <p style="font-size:.14rem;color:#777">最低限额：10</p> -->
        </div>
      </div>
      <div class="statistics">
        <div class="statistics-list">
          <p class="row allAlignment">
            <span>
              <i style="color:#F76649">{{data.length}}</i>&emsp;所有投注：
            </span>
            <span>{{investment?investment :'0.00' }}RMB</span>
          </p>
          <p class="row allAlignment">
            <span>可赢金额：</span>
            <span style="color:#F76649;font-size:.16rem;">{{profit?profit:'0.00'}}RMB</span>
          </p>
        </div>

        <!-- <div
          style="height:.5rem;background:#A83131;padding-left:.2rem;margin-top:.2rem;"
          class="row item-center"
        >
          <img style="width:.17rem;height:.15rem;" src="@/assets/st-imges/warning.png">&nbsp;
          <p style="color:#fff;font-size:.14rem;">您的余额不足。 请您先进行存款</p>
        </div> -->

        <!-- <div class="row center" style="height:.5rem;background:rgb(247, 102, 73);color:#fff;margin-top:.2rem;font-size:.14rem;">赔率信息已更改，请重新投注</div> -->
        
        <div class="statistics-btn">
          <!-- <div class="row center" style="color:#F00;font-size:.16rem;">投注失败</div> -->
          <div class="row center" v-if="!login" style="font-size:.16rem;color:#999">请先登陆再进去投注</div>
          <div class="row center" v-else style="background:#F76649;color:#fff;" @click='submit'>投注</div>
          <div class="row center" @click="cancel()" style="background:#CCC;color:#666;">取消</div>
        </div>
      </div>
      
    </div>
  </div>
</template>

<script>
import "@/css/index.css";
export default {
  name: "oddBettingTable",
  data() {
    return {
      data:[],
      cacheData:[],
      dataMoney:[],// 
      state:0,//激活数
      login:false,
      investment:'',//投注资金
      profit:'',//利润（可赢额）
      isSubmit:true,
      interisvalId:'',
      isInterisval:true,
    };
  },
  /***
  * 方法
  */
  methods: {
     /**************检测玩法是否失效***************/
    checkFailure(data,type){
      this.$http.post(this.$ports.VerOddsScore, {
        data:JSON.stringify(data)
      }).then(res=>{
        if(res.status == 200){
          if(res.data.status == 1){
            if(res.data.data != 'ok' ){
              res.data.data.forEach(e=>{
                this.$set(this.data[e.sort],'msg',e.ver_mark);
                this.data[e.sort].status = e.status;
              })
            } 
          }
        }
      })
    },

    /*-------------------------------------*/
    //切换激活状态
    activation(index){
      this.state = index;
      //console.log(this.data)
    },

    /*-------------------------------------*/
    //小键盘加法
    addNum(index,num){
      let money =  this.data[index].money ? this.data[index].money * 1 : 0;
      //console.log(money)
       if(money*1 > 999999999){
        money = 999999999
      }
      this.$set(this.data[index],'money', (money*1 + num*1 ) < 999999999 ?  money*1 + num*1 :999999999 )
      this.calculateMoney();
    },

    /*---------------------------------------*/
    //数据提交
    submit(){
      if(!this.isSubmit) return
      for(let i in  this.data){
        if(this.data[i].status >2){
          this.$dialog.alert({ mes: "赔率变法或盘口关闭不能投注" });
          return false;
        }
      }
      let list  =[],dataList=[],objData = [];
      let money = 0;
      let limit = JSON.parse(this.$public.getItem('limit'));
      this.data.forEach(e =>{
        if(e.money*1 >= 1){
          list.push(e);
          money += e.money*1;
        }
      })
      list.forEach((res,index) =>{
        dataList.push({
          type: "1",
          index: index,
          bet_amount: res.money
        })
      })
      // dataList.push(objData);
      dataList.push(list);
      if (list.length > 0 ) {
        if(limit.lower_limit*1 <= money  && limit.upper_limit >= money ){
          let token = localStorage.getItem("token");
           this.isSubmit = false;
          this.$http.post(this.$ports.betOrder.Bet, {
            data: dataList,
            token,
            bet_money:money
          }).then(res => {
            //console.log('数据',res.data);
            if (res.data.status == 1) {
              // this.alldel();
              this.$store.dispatch("SET_BETTING",[]);
              this.cash = (this.cash - this.dataNumbe * 1).toFixed(2);
              this.$dialog.alert({ mes: "亲！您已经投注成功啦。" });
            } else if (res.data.status == "-4001") {
              // this.isLogin = false;
              this.login = false;
              this.$dialog.alert({ mes: "亲！您的登陆已过期。" });
            } else if (res.data.status == "4204") {
              this.$dialog.alert({ mes: "亲！您的余额不足。" });
            }else if(res.data.status == '7027' ){
              this.$dialog.alert({ mes: "亲！赔率发生变法，请重新选择。" });
              // this.alldel();
              this.$store.dispatch("SET_BETTING",[]);
            }else if(res.data.status == '3406') {
              this.$dialog.alert({mes: "亲！投注金额不能小于10"})
            }else if(res.data.status == '7051') {
                this.$dialog.alert({mes: "亲！赔率发生变化，请重新选择。"})
            }
            else{
              this.$dialog.alert({ mes: "错误代码:"+res.data.status});
            }
            this.isSubmit = true;
          });
        }else if(limit.lower_limit*1  > money ){
          this.$dialog.alert({ mes: `亲！投注额小于最低投注额${limit.lower_limit}元` });
        }else if(limit.upper_limit*1 < money ){
          this.$dialog.alert({ mes: `亲！投注额大于最高投注额${limit.upper_limit}元` });
        }
      } else {
        this.$dialog.alert({ mes: "亲！您还未输入投注金额啦。" });
        this.isSubmit = true;
      }
      
    },
    /*--------------------------------------*/
    //限制输入内容
    keyMatch(e,index) {
      e.currentTarget.value = e.currentTarget.value.replace(/[^0-9]/g, "");
      if(e.currentTarget.value.length > 9){
        e.currentTarget.value = 999999999
      }
     
      this.$set(this.data[index],'money',e.currentTarget.value);
      this.calculateMoney();
    },

    /*-------------------------------------*/
    //删除一条数据
    deleteList(index,id,code){
      let  betting= this.$store.getters.getBetting
      for(let i=0;i < betting.length ;i++ ){
        if(code == betting[i].title){
          for(let j = 0;j < betting[i].data.length ; j++){
            if(id == betting[i].data[j].id){
              this.data[index].money ='';
              betting[i].data.splice(j,1);
              break;
            }
          }
          break;
        }
      }
      this.$store.dispatch("DEL_TYPE", id);
      this.$store.dispatch("SET_BETTING",[]);
      this.$store.dispatch("SET_BETTING",betting);
      //console.log(betting);
    },

    /*----------------------------------*/
    //清除数据
    removeData(index){
      this.$set(this.data[index],'money','')
      this.calculateMoney();
    },

    /*----------------------------------*/
    //计算可赢额和投注金额
    calculateMoney(){
      let investment = 0
      let profit = 0
      this.data.forEach(e=>{
        if(e.money){
          investment +=e.money*1;
          profit += e.money*1 * e.odds*1
        }
      })
      this.investment = investment;
      this.profit = profit.toFixed(2);
    },
    
    /*----------------------------------*/
    // 取消
    cancel(){
      this.$store.dispatch("SET_BETTING",[]);
    },
  },
  /**
  * 计算属性
  */
  computed: {
    getBetting(){
      let bettingData = this.$store.getters.getBetting
      // console.log(bettingData)
      return this.$store.getters.getBetting
    },
    // 判断登录状态
    getToken(){
      return this.$store.getters.getToken
    }
  },
  /**
   * 监听器
   */
  watch: {
    getBetting(val){
      let dataList = [];
      console.log(val)
      if(this.$store.getters.getLimit > 0){
        val.forEach(e =>{
          dataList = dataList.concat(e.data)
        })
      }
      // 清除v-model 的数据
      if(this.data.length  > dataList.length){
        this.data.forEach((e,index)=>{
          let isDel = false;
          dataList.forEach(res=>{
            if( e.mark == res.mark ){
              isDel = true;
            }
          })
          if(!isDel){
            this.data[index].money ='';
          }
        })
      }
      this.data = [];
      this.data  = dataList


      if( this.data.length > 0){
        if(this.isInterisval){
          this.isInterisval = false;
          this.intervalId = setInterval(e=> {
            let newArray=[];
            this.data.forEach(res=>{
              newArray.push({
                game_code:res.ballId,
                match_id:res.match_id,
                home_score:0,
                guest_score:0,
                odds_only:res.odds_only,
              })
            })
            this.checkFailure(newArray);
          }, 1000*3);
        }
      }else{
        this.isInterisval = true;
        clearTimeout(this.intervalId);
      }
      //console.log(this.data);
    },
    // 获取登录状态，判断登录
    getToken(val){
      this.login = val? true: false
    }
  },
  mounted(){
    if(localStorage.getItem("token")){
      this.login = true;
    }
  }, 
};
</script>

<style scoped>
img {
  cursor: pointer;
}
.canWin{
  border:.01rem solid #BFE2B3;
  background:#E7FFDA;
  padding-left: .05rem;
}
.br05 {
  border-radius: 0.05rem;
}
.bettingTable {
  min-height: 0.8rem;
  background: #e5e5e5;
}
.dataNo {
  background: #777;
}
.list {
  width: 90%;
  margin: 0 auto;
}
.list img {
  width: 0.15rem;
  height: 0.15rem;
}
.list-header {
  min-height: 0.5rem;
}
.list-header p {
  font-size: 0.14rem;
  color: #fff;
}
.list-body {
  min-height: 0.6rem;
}
.list-body > div {
  min-height: 0.3rem;
}
.condition {
  font-size: 0.16rem;
  font-weight: bold;
  color: #666;
}
.duel {
  font-size: 0.14rem;
  color: #666;
}
.list-input {
  min-height: 0.6rem;
}
.list-input > div {
  width: 48%;
  height: 0.35rem;
  color: #999;
  font-size: 0.14rem;
}
.list-input > div input {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 0.05rem;
  background: #fff;
  padding-left: 0.05rem;
}
.key {
  min-height: 1rem;
  background: #ccc;
}
.key > div {
  width: 90%;
  margin: 0 auto;
}
.key > div > div {
  min-height: 0.5rem;
}
.key p {
  width: 30%;
  height: 0.34rem;
  background: #fff;
  border-radius: 0.05rem;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #f76649;
  font-size: 0.14rem;
  cursor: pointer;
   box-shadow: -2px 0px 5px 1px rgba(0, 0, 0, 0.05),
    0px -2px 5px 1px rgba(0, 0, 0, 0.05), 2px 0px 5px 1px rgba(0, 0, 0, 0.05),
    0px 2px 5px 1px rgba(0, 0, 0, 0.05);
}
.statistics {
  min-height: 1.9rem;
  background: #fff;
}
.statistics > div {
  width: 90%;
  margin: 0 auto;
  padding: 0.2rem 0;
}
.statistics-list {
  min-height: 0.6rem;
  font-size: 0.14rem;
}
.statistics-list > p {
  line-height: 0.3rem;
}
.statistics-btn > div {
  height: 0.34rem;
  border-radius: 0.05rem;
  margin-top: 0.1rem;
  cursor: pointer;
}
.prompt-status {
  height:0.3rem;
  line-height: 0.3rem;
  width:100%;
  text-align: center;
  background-color: #f76649;
  color: #ffffff;
  font-size: 0.15rem;
}
</style>