const util = require('../../utils/util.js');
Component({
  options: {
    addGlobalClass: true
  },
  properties: {
    show:{
      type: Boolean,
      observer: function (newVal) {
        this.setData({ show: newVal,second:this.data.time });
        if (newVal) {
          this.countDown()
        }else{
          clearInterval(this.data.timer)
        }
      }
    },
    time:{
      type: Number,
      observer: function (newVal) {
        this.setData({ time: newVal,second:newVal });
      }
    },
    taskId:{
      type: String,
      observer: function (newVal) {
        this.setData({ taskId: newVal });
      }
    },
  },
  data: {
    show:false,
    time:0,
    second:0,
    taskId:'',
    timer:null,
    finished:false,
    coin:0
  },
  methods: {
    countDown(){
      let second=this.data.time,that=this;
      if (second>0&&this.data.show) {
        let timer = setInterval(() => {
          if (second>0) {
            second--;
            that.setData({second})
          } else {
            clearInterval(timer)
            that.finish()
            // that.triggerEvent('finishedTime',)
          }
        }, 1000);
        this.setData({timer})
      }
    },
    finish(){
      let that=this;
      if (!util.isEmpty(this.data.taskId)) {
        util.finishCoinTask(this.data.taskId,true).then(res=>{
          if (typeof res === 'number') {
            this.setData({coin:res})
          } else {
            util.showTips(res);
            that.triggerEvent('finishedTime',)
          }
          this.setData({finished:true})
        })
      }
    },
    jumpPage(){
      this.triggerEvent('finishedTime');
      wx.redirectTo({
        url: '/pages/account/monetaryCenter/index',
      })
    }
  }
})
