<template>
  <div>

<!--    <div class="box-infinity">-->
<!--      <div ref="numberSlide" class="number-slide" :style="`font-size:${option.fontSize}px;color:${option.color}`">-->
<!--        <i v-for="item in numberList" :style="'transform:translateY(-' +item + 'em)'" :key="item.key">{{item}}</i>-->
<!--      </div>-->
<!--    </div>-->

    <div class="FlipClock">
      <template v-for="(item,index) in currentData">
        <Flipper
          v-show="item!=='.'"
          :height="option.height"
          :width="option.width"
          :font-color="option.color"
          :font-size="option.fontSize"
          :border-radius="option.borderRadius"
          :bg-color="option.bgColor"
          :bg-gradient-color="option.bgGradientColor"
          :ref="'flip'+index"/>
        <span v-if="formatter(currentData,index)"
              :style="{color:option.color,fontSize: option.fontSize+'px'}">,</span>
        <span v-if="item==='.'"
              :style="{color:option.color,fontSize: option.fontSize+'px'}">.</span>
      </template>

    </div>
  </div>
</template>


<script>

import CountFlop from './flip.vue';
import * as report from "@/api/report/report";
import func from "../../util/func";
import {commonFiled, param} from '@/option/config'
import countTo from 'vue-count-to';
import Flipper from './flip/Flipper.vue'

export default {
  name: 'new-flip',
  components: {CountFlop, countTo, Flipper},
  data() {
    return {
      growValue:1234,
      numberList:[],
      startVal: 0,
      endVal: 0,
      key: 1,
      val: 0,
      text: this.option.text,
      newtext: this.option.text,
      form: {},
      param: JSON.parse(JSON.stringify(param)),
      intervalInvorkTimmer: null,
      headerdata: {},
      optionStyle: {},
      oldFlopData: [],
      flopData: [],
      currentData: [],
      timer: null,
      flipObjs: [],
    }
  },
  props: ["option", 'config', "modalSet", "index", "site", 'scale'],
  computed: {
    commonParam() {
      return this.$store.state.common.commonParam;
    },
  },
  watch:{
    growValue(n,old){
      this.creatNumber()
    }
  },
  created() {
    let that = this
    window.formatter = function (num) {
      if (!that.option.formatBit || !that.option.formatSymbol) return num;
      var result = [], counter = 0;
      num = (num || 0).toString().split('');
      for (var i = num.length - 1; i >= 0; i--) {
        counter++;
        result.unshift(num[i]);
        if (!(counter % that.option.formatBit) && i != 0) {
          result.unshift(that.option.formatSymbol);
        }
      }
      return result.join('');
    }
  },
  mounted() {
    this.creatNumber()
  },
  destroyed() {
    clearInterval(this.intervalInvorkTimmer);
    clearInterval(this.timer);
  },
  methods: {
    creatNumber(){
      let arr = String(this.growValue).split('');
      this.numberList = arr;
    },
    addNumber(step){
      if((this.growValue + step) > 0){
        this.growValue += step;
      }
    },
    initList() {
      this.startVal = this.endVal;
      if (this.option.text) {
        this.loadDynamicText();
      } else {
        this.loadApiData();
      }
    },
    loadDynamicText() {
      this.oldFlopData = this.flopData;
      this.currentData = this.oldFlopData;
      this.setFlipObjs();
      this.initFlip();
      var str = this.option.text;
      XEUtils.objectEach(commonFiled, (item, key) => {
        let reg = "/@" + key + "@/g";
        if (XEUtils.has(this.commonParam, 'month')) {
          if (key == 'month') {
            item = XEUtils.toDateString(this.commonParam[key], 'M');
            this.param[key] = XEUtils.toDateString(this.commonParam.month, 'yyyyMM');
          }
          if (key == 'quarter') {
            item = XEUtils.toDateString(this.commonParam.month, 'q');
            this.param[key] = XEUtils.toDateString(this.commonParam.month, 'yyyy') + XEUtils.toDateString(this.commonParam.month, 'q');
          }
          if (key == 'year') {
            item = XEUtils.toDateString(this.commonParam.month, 'yyyy');
            this.param[key] = item
          }
          if (key == 'date') {
            item = XEUtils.toDateString(this.commonParam.month, 'd');
          }
        }
      })
      var cparam = this.commonParam
      if (this.isSearch) {
        let txt = ''
        if (cparam.date.startTime && cparam.date.endTime !== param.month) {
          if (cparam.date.type == 'MONTH') {
            txt = `${moment(cparam.date.startTime).format('YYYY.MM')} - ${moment(cparam.date.endTime).format('YYYY.MM')}; `
          } else {
            txt = `${moment(cparam.date.startTime).format('YYYY')}季度 - ${moment(cparam.date.endTime).format('YYYY')}季度; `
          }
        }
        if (cparam.day && cparam.day.last30 !== param.lart30) {
          txt += `${moment(cparam.day.last30).format('YYYY.MM.DD')} - ${moment(cparam.day.today).format('YYYY.MM.DD')}; `
        }
        if (cparam.AREA) {
          txt += `${cparam.AREA.toString()}; `
        }
        if (cparam.CATEGORYNAME) {
          let a = ''
          XEUtils.arrayEach(XEUtils.uniq(XEUtils.flatten(cparam.CATEGORYNAME)), (item, key) => {
            let txtt = XEUtils.find(XEUtils.toTreeArray(this.contain.DIC.catoptions), itemm => itemm.CID === item)
            a += `${txtt.CNAME},`
          })
          txt += `${a}; `
        }
      }
      let apikey = this.option.apiKey
      let isapikey = true
      if (!apikey) {
        isapikey = false
      }
      if (XEUtils.isArray(apikey)) {
        if (apikey.length < 1) {
          isapikey = false
        }
        apikey = apikey[1]
      }

      if (isapikey) {
        var month = XEUtils.locat().hashQuery.month
        if (!XEUtils.isUndefined(month)) {
          this.param = {
            date: moment(month).format('YYYYMM'),
            month: moment(month).format('YYYYMM'),
            themonth: moment(month).format('YYYYMM'),
            quarter: String(moment(month).year()) + moment().quarter() - 1,
            year: String(moment(month).year()),
            today: moment(month).format('YYYYMMDD'),
            lart30: moment(month).subtract('days', 30).format('YYYYMMDD'),
          }
        }

        // this.param.abc = ` DTYPE = 'MONTH' AND THEDVALUE >= ${this.param.month} AND THEDVALUE <= ${this.param.month} `
        report.openurl(apikey, this.param).then((res) => {
          this.filedList = res.data.data[0]
          XEUtils.objectEach(this.filedList, (item, key) => {
            var reg = "/@" + key + "@/g";
            str = g.replaceAll(str, eval(reg), item, true)
          })
          this.newtext = str;
          this.endVal = parseFloat(str);

          const nowData = [];
          for (let i = 0; i < str.length; i++) {
            nowData.push(str[i]);
          }
          if (this.oldFlopData.length === 0) {
            this.oldFlopData = nowData;
          }
          this.flopData = nowData;
          this.currentData = this.flopData;
          this.setFlipObjs();
          //this.initFlip();

        });
      }
    },
    loadApiData() {

    },
    init() {
      this.oldFlopData = this.flopData;
      this.currentData = this.oldFlopData;
      this.setFlipObjs();
      this.initFlip();
      this.endVal = parseFloat(this.tabledata);
      const nowData = [];
      for (let i = 0; i < this.tabledata.length; i++) {
        nowData.push(this.tabledata[i]);
      }
      if (this.oldFlopData.length === 0) {
        this.oldFlopData = nowData;
      }
      this.flopData = nowData;
      this.currentData = this.flopData;
      this.setFlipObjs();
    },
    formatter(num, index) {
      if (!this.option.formatBit || !this.option.formatSymbol) return false;
      const numCopy = JSON.parse(JSON.stringify(num));
      num = num.join('');
      var result = [], counter = 0;
      num = (num || 0).toString().split('');
      for (var i = num.length - 1; i >= 0; i--) {
        counter++;
        result.unshift(num[i]);
        if (!(counter % this.option.formatBit) && i != 0) {
          result.unshift(this.option.formatSymbol);
        }
      }
      if (index + 1 < numCopy.length && result[index + 1] === this.option.formatSymbol)
        return true;
      return false;
    },
    // 初始化数字
    initFlip() {
      for (let i = 0; i < this.flipObjs.length; i++) {
        if (this.currentData[i] !== '.')
          this.flipObjs[i].setFront(this.getValue(this.currentData, i));
      }
    },
    // 开始计时
    run() {
      this.timer = setInterval(() => {
        for (let i = 0; i < this.flipObjs.length; i++) {
          let nowTimeStr = this.getValue(this.oldFlopData, i);
          let nextTimeStr = this.getValue(this.flopData, i);
          if (nowTimeStr === nextTimeStr) {
            continue
          }
          if (nowTimeStr === '.' || nextTimeStr === '.') {
            continue
          }
          this.flipObjs[i].flipDown(
            nowTimeStr,
            nextTimeStr
          )
        }
      }, 1000)
    },
    getValue(data, i) {
      return data[i];
    },
    setFlipObjs() {
      this.flipObjs = [];
      for (let i = 0; i < this.currentData.length; i++) {
        if (this.$refs['flip' + i]) {
          this.flipObjs.push(this.$refs['flip' + i][0]);
        }
      }
    },
    update(data) {
      this.tabledata = data[0][this.config.indexParamList[0].columnTitle]
      // this.growValue = data[0][this.config.indexParamList[0].columnTitle]
      //
      // console.log(data)
      this.run();
      this.init()
    }
  }
}
</script>


<style>

div{box-sizing: border-box;}
.box-infinity{height:auto;display:flex;justify-content: center;align-items:center;flex-direction: column;}
.box-infinity input{width:100%;box-sizing: border-box;}
.number-slide {
  overflow: hidden;
  line-height:1;
  width: 100%;
}
.number-slide i{
  font-style: normal;
  position: relative;
  display: inline-block;
  transition: all 1.2s ease 0s;
}
.number-slide i::after{
  content:'0 1 2 3 4 5 6 7 8 9';
  position:absolute;
  color:currentColor;
  font-weight: normal;
  display: block;
  top: 0;
}

.FlipClock {
  text-align: left;
}

.FlipClock .M-Flipper {
  margin: 0 3px;
}

.FlipClock em {
  display: inline-block;
  line-height: 102px;
  font-size: 66px;
  font-style: normal;
  vertical-align: top;
}
</style>
