<template>
  <div class="container">
    <div class="time-box flex">
      <div class="time line" :class="{ active: timeShare }" @click="updateTime1">
        <!-- 分时 -->
        {{ $t('exchange.l60') }}
      </div>
      <div class="time line" v-for="(item, index) in timeOptions" :key="index" @click="updateTime(item)" :class="{ active: timeSign == item.time && !timeShare }">
        {{ item.text }}
      </div>
      <van-popover
          v-model="showTimePop"
          placement="bottom"
          trigger="click"
        >
        <div class="popover-body">
          <div class="pop-item" :class="{active: timeSign == 60}" @click="updateTime({time: 60})">
            <div>60{{ $t('exchange.l74') }}</div>
          </div>
        </div>
        <template #reference>
          <div class="time line" :class="{ active: timeSign == 60 }">
            {{ (timeSign == 60) ? timeSign : '' }}{{ $t('exchange.l61') }}
            <div class="border"></div>
          </div>
        </template>
      </van-popover>
    </div>
    <div id="simple_chart1" :style="{'height': height}" />
    <div class="ul flex" v-if="chartSign">
      <div class="li" :class="{active: ma}" @click="switchMA">MA</div>
      <div class="li" v-for="(val, item) in indicatorObj" :key="item" :class="{active: val}" @click="switchIndicator(item, val)">{{ item == 'VOL' ? $t('exchange.l75') : item }}</div>
    </div>
  </div>
</template>
<script>
import { dispose, init } from 'klinecharts'
import { mapGetters } from 'vuex'
import { getPriceList } from '@/api/product'
import bus from '@/utils/bus'
export default {
  name: 'SimpleChart',
  props: {
    symbol: {},
    symbolInfo: {
      default() {
        return {}
      }
    },
    mdcShow: {
      default: false,
    },
    height: {
      default: '500px'
    }
  },
  components: {
  },
  data() {
    return {
      timeSign: '1D',
      loading: false,
      timeShare: false,
      showTimePop: false,
      indicatorObj: {
        BOLL: false,
        EMA: false,
        SAR: false,
        VOL: false,
        MACD: true,
        KDJ: false,
        BRAR: false,
      },
      ma: true,
      timeOptions: [
        // {
        //   text: '5分',
        //   time: '5',
        // },
        // {
        //   text: '15分',
        //   time: '15',
        // },
        {
          text: this.$t('product.l48'),
          time: '1D',
        },
        {
          text: this.$t('product.l49'),
          time: '7',
        },
        {
          text: this.$t('product.l50'),
          time: '31',
        },
        {
          text: this.$t('product.l51'),
          time: '365',
        },
        {
          text: '1' + this.$t('exchange.l74'),
          time: '1',
        },
        {
          text: '5' + this.$t('exchange.l74'),
          time: '5',
        },
        {
          text: '15' + this.$t('exchange.l74'),
          time: '15',
        },
        {
          text: '30' + this.$t('exchange.l74'),
          time: '30',
        }
      ],
      chart: null,
      chartDataList: [],
      initSign: false,
      startDate: null,
      priceSign: false,
      chartSign: false,
      PriceVolumePrecision: 2,
      timerSign: 0,
    }
  },
  beforeDestroy() {
    dispose('simple_chart1')
    bus.$off('updateChart', this.updateList)
  },
  computed: {
    ...mapGetters(['isLogin']),
  },
  mounted() {
    this.getPriceList()
    bus.$on('updateChart', this.updateList)
  },
  methods: {
    updateList(data) {
      if ((this.symbol == data.symbol)) {
        // if (new Date().getTime() - this.timerSign > 1000) {
          // this.timerSign = new Date().getTime()
          this.updateTradesPrice(data)
        // }
      }
    },
    updateTradesPrice(data) {
      if (!this.initSign) {
        return
      }
      if (this.chartDataList.length) {
        let time = this.gettimestamp()
        let a = {
          timestamp: time,
        }
        let oldList = this.chartDataList[this.chartDataList.length - 1]
        if (time == oldList.timestamp) {
          a.open = oldList.open
          a.high = +data.ask > oldList.high ? +data.ask : oldList.high
          a.low = +data.ask < oldList.low ? +data.ask : oldList.low
          a.close = +data.ask
          a.volume = (oldList.volume + (Number(data.volume) || 0))
          this.chartDataList[this.chartDataList.length - 1].high = a.high
          this.chartDataList[this.chartDataList.length - 1].low = a.low
        } else {
          a.open = oldList.close
          a.high = +data.ask
          a.low = +data.ask
          a.close = +data.ask
          a.volume = (Number(data.volume) || 0)
          this.chartDataList.push(a)
        }
        this.chart.updateData(a)
      }
    },
    updateTime(item) {
      this.showTimePop = false
      if (!this.timeShare) {
        if (this.timeSign == item.time) {
          return
        }
      }
      this.timeSign = item.time
      this.timeShare = false
      this.initSign = false
      this.getPriceList()
    },
    updateTime1() {
      if (this.timeShare) {
        return
      }
      this.timeSign = '1'
      this.timeShare = true
      this.initSign = false
      var startTime = this.getStartTime()
      this.getPriceList(startTime)
    },
    getPriceList(time) {
      this.loading = true;
      let data = {
        symbol: this.symbol,
        type: this.timeSign === '1D' ? 1440 : this.timeSign,
        endTime: parseInt(new Date().getTime()),
      }
      if (this.timeShare) {
        data.count = 499
        if (this.symbolInfo.market !== 'CFD') {
          data.startTime = time
        }
      } else {
        data.count = 100
      }
      getPriceList(data).then((res) => {
        let list = res || [];
        if (this.timeShare && list.length == 0) {
          this.getPriceList(time - (24*60*60*1000))
          return
        }
        this.chartDataList = list.map((item) => {
          return {
            timestamp: +item.datetime,
            open: +item.open, // 开盘
            high: +item.high, // 最高
            low: +item.low, // 最低
            close: +item.close, // 收盘
            volume: item.volume || 0, // 成交量
          }
        })
        if (this.priceSign) {
          this.chart.clearData()
        } else {
          this.initChart()
        }
        this.priceSign = true
        if (this.chartDataList.length === 0) {
          // this.$message({
          //   message: this.$t('quote.no-data'),
          //   type: 'error',
          //   duration: 1500,
          // })
        }
        this.chartSign && this.initData()
      }).catch(() => {
        this.loading = false
      })
    },
    initChart() {
      this.chart = init('simple_chart1', {
      })
      this.chart.setStyles({
        grid: {
          show: true,
          containLabel: false
        },
        xAxis: {
          show: false,
          axisLine: {
            show: false,
          },
          tickLine: {
            show: false,
          },
          tickText: {
            show: false
          }
        },
        crosshair: {
          horizontal: {
            line: {
              color: '#FE6F30'
            },
            text: {
              size: 10,
              color: '#FE6F30',
              borderColor: '#878787',
              backgroundColor: '#ffffff',
            }
          },
          vertical: {
            line: {
              style: 'solid',
              color: '#FE6F30',
            },
            text: {
              size: 10,
              color: '#FE6F30',
              borderColor: '#878787',
              backgroundColor: '#ffffff',
            }
          }
        },
        candle: {
          type: 'area',
          tooltip: {
            text: {
              size: 10
            },
            showRule: 'follow_cross',
            custom: [{ title: 'open', value: '{open}' }, { title: 'high', value: '{high}' }, { title: 'low', value: '{low}' }, { title: 'close', value: '{close}' }]
          },
          bar: {
            upColor: '#EA4A45',
            downColor: '#07AC3A',
            upBorderColor: '#EA4A45',
            downBorderColor: '#07AC3A',
            upWickColor: '#EA4A45',
            downWickColor: '#07AC3A',
          },
          area: {
            lineSize: 1,
            lineColor: '#FF6F30',
            backgroundColor: [{
              offset: 0,
              color: 'rgba(255, 111, 48, 0.01)'
            }, {
              offset: 1,
              color: 'rgba(255, 111, 48, 0.2)'
            }]
          },
          priceMark: {
            last: {
              upColor: '#EA4A45',
              downColor: '#07AC3A',
              text: {
                show: false
              }
            }
          }
        },
        yAxis: {
          inside: true,
          show: false,
          axisLine: {
            show: false,
          },
          tickLine: {
            show: false,
          },
          tickText: {
            show: false
          }
        },
        indicator: {
          ohlc: {
            upColor: '#EA4A45',
            downColor: '#07AC3A',
          },
          bars: [{
            upColor: '#EA4A45',
            downColor: '#07AC3A',
          }],
          tooltip: {
            text: {
              size: 10,
            }
          }
        },
        separator: {
          size: 1,
          color: '#F0F0F0',
          fill: true,
          activeBackgroundColor: 'rgba(230, 230, 230, .15)',
        },
      })
      this.chart.createIndicator('MACD', true, {
        id: 'MACD'
      })
      this.chart.setOffsetRightDistance(10)
      this.chartSign = true;
      this.initData()
      this.chart.loadMore(this.loadMore)
    },
    initData() {
      if (this.priceSign && this.chartSign) {
        this.loading = false;
        setTimeout(() => {
          this.chart.setStyles({
            candle: {
              type: this.timeShare ? 'area' : 'candle_up_stroke',
              priceMark: {
                last: {
                  text: {
                    show: this.timeShare
                  }
                }
              }
            },
            xAxis: {
              show: this.timeShare,
              tickText: {
                show: this.timeShare
              }
            },
            yAxis: {
              // type: this.timeShare ? 'percentage' : 'normal',
            }
          })
          this.chart.setZoomEnabled(!this.timeShare)
          if (this.timeShare) {
            this.chart.setBarSpace(4)
            this.chart.removeIndicator('candle_pane', 'MA')
          } else {
            this.chart.setBarSpace(8)
            if (this.ma) {
              this.chart.createIndicator('MA', false, { id: 'candle_pane' })
              this.chart.overrideIndicator({
                name: 'MA',
                calcParams: [5, 10],
              })
            }
          }
          this.chart.applyNewData(this.chartDataList)
          this.initSign = true;
          this.chart.setPriceVolumePrecision(this.symbolInfo.digits, 2)
        }, 1000)
      }
    },
    gettimestamp() {
      let now = new Date();
      var sign2 = ":";
      let a
      var year = now.getFullYear() // 年
      var month = now.getMonth() + 1; // 月
      var day = now.getDate(); // 日
      var hour = now.getHours(); // 时
      var minutes = now.getMinutes(); // 分
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      if (hour >= 0 && hour <= 9) {
        hour = "0" + hour;
      }
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      let m = new Date(year + '/' + month + '/' + day + " " + hour + sign2 + minutes + sign2 + '00').getTime()
      if (this.timeSign == '1') {
        a = m
      }
      if (this.timeSign == '5') {
        let test =  Math.floor(minutes / 5) * 5
        a = new Date(year + '/' + month + '/' + day + " " + hour + sign2 + (test > 10 ? test : ('0' + test)) + ':00').getTime()
      }
      if (this.timeSign == '15') {
        let test =  Math.floor(minutes / 15) * 15
        a = new Date(year + '/' + month + '/' + day + " " + hour + sign2 + (test > 0 ? test : '00') + ':00').getTime()
      }
      if (this.timeSign == '30') {
        a = new Date(year + '/' + month + '/' + day + " " + hour + sign2 + (Math.floor(minutes / 30) > 0 ? '30' : '00') + ':00').getTime()
      }
      if (this.timeSign == '60') {
        a = new Date(year + '/' + month + '/' + day + " " + hour + ':00:00').getTime()
      }
      if (this.timeSign == '1D') {
        a = new Date(year + '/' + month + '/' + day + " " + '00:00:00').getTime()
      }
      if (this.timeSign == '7') {
        let now = new Date();
        var week = now.getDay();
        var day = now.getDate();
        if (week) {
          now.setDate(day - week + 1)
        } else {
          now.setDate(day - 7)
        }
        var year = now.getFullYear() // 年
        var month = now.getMonth() + 1; // 月
        day = now.getDate();
        a = new Date(year + '/' + month + '/' + day + " " + '00:00:00').getTime()
      }
      if (this.timeSign == '31') {
        a = new Date(year + '/' + month + '/01 00:00:00').getTime()
      }
      if (this.timeSign == '365') {
        a = new Date(year + '/01/01 00:00:00').getTime()
      }
      return a
    },
    loadMore(time) {
      if (this.timeShare) {
        return
      }
      this.loding = true
      getPriceList({
        symbol: this.symbol,
        type: this.timeSign === '1D' ? 1440 : this.timeSign,
        count: 100,
        endTime: time,
      })
        .then((res) => {
          let list = res || []
          let chartDataList = []
          list.forEach(item => {
            if (+item.datetime != time) {
                chartDataList.push({
                timestamp: +item.datetime,
                open: +item.open, // 开盘
                high: +item.high, // 最高
                low: +item.low, // 最低
                close: +item.close, // 收盘
                volume: item.volume || 0, // 成交量
              })
            }
          })
          this.chart.applyMoreData(chartDataList, chartDataList.length > 80)
        })
        .finally(() => {
          this.loding = false
        }).catch(() => {})
    },
    switchIndicator(key, val) {
      this.indicatorObj[key] = !this.indicatorObj[key]
      if (!this.chart) {
        return
      }
      if (this.indicatorObj[key]) {
        this.chart.createIndicator(key, true, {
          id: key
        })
        for(var item in this.indicatorObj) {
          if (key !== item && this.indicatorObj[item]) {
            this.indicatorObj[item] = false
            this.chart.removeIndicator(item, item)
          }
        }
      } else {
        this.chart.removeIndicator(key, key)
      }
    },
    switchMA() {
      this.ma = !this.ma
      if (!this.chart) {
        return
      }
      if (this.ma && !this.timeShare) {
        this.chart.createIndicator('MA', false, { id: 'candle_pane' })
      } else {
        this.chart.removeIndicator('candle_pane', 'MA')
      }
    },
    getStartTime() {
      var nowTime = new Date();
      var offset = nowTime.getTimezoneOffset()/60;
      var beijingDate = new Date(nowTime.getTime() + ((offset + 8) * 60 * 60 * 1000));
      var year = beijingDate.getFullYear();
      var m = beijingDate.getMonth() + 1
      if (m < 10) {
        m = '0' + m
      }
      var d = beijingDate.getDate()
      if (d < 10) {
        d = '0' + d
      }
      return new Date(`${year}-${m}-${d}T${this.symbolInfo.market == 'US' ? '22:30:00' : '09:30:00'}+08:00`).getTime()
    }
  },
}
</script>
<style lang="less" scoped>
.time-box {
  border-bottom: 1px solid rgba(210,217,227,0.26);;
  column-gap: 12px;
  white-space: nowrap;
  overflow-x: auto;
  padding-left: 10px;
}
.time {
  padding-top: 13px;
  padding-bottom: 11px;
  position: relative;
  letter-spacing: 0;
  &.line {
    padding-bottom: 9px;
    border-bottom: 2px solid transparent;
  }
  &.active {
    color: #090909;
    &.line {
      border-bottom-color: var(--color-);
    }
  }
  .border {
    position: absolute;
    bottom: 0;
    right: -4px;
    border-right: 3px solid #D8D8D8;
    border-bottom: 3px solid #D8D8D8;
    border-top: 3px solid transparent;
    border-left: 3px solid transparent;
  }
}
.ul {
  .li {
    padding: 6px;
    color: #7C7C7C;
    font-size: 12px;
    cursor: pointer;
    &.active {
      color: var(--color-);
    }
  }
}
.pop-item {
  width: 63px;
  text-align: center;
  line-height: 39px;
  cursor: pointer;
  font-size: 14px;
  color: #737373;
  &.active {
    color: var(--color-);
  }
}
</style>