<template>
  <view class="chart-body">
    <view class="chart-core">
      <!--#ifdef MP-ALIPAY -->
      <canvas
        id="contractChart"
        canvas-id="contractChart"
        type="2d"
        class="charts"
        :width="cWidth*pixelRatio"
        :height="cHeight*pixelRatio"
        :style="{'width':cWidth+'px','height':cHeight+'px'}"
        @touchstart="touchMix"
        @touchmove="moveMix"
        @touchend="touchEndMix" />
      <!--#endif-->
      <!--#ifndef MP-ALIPAY -->
      <canvas
        id="contractChart"
        :style="{
          width: cWidth + 'px',
          height: cHeight + 'px'
        }"
        canvas-id="contractChart"
        type="2d"
        class="charts"
        :disable-scroll="true"
        @touchstart="touchMix"
        @touchmove="moveMix"
        @touchend="touchEndMix" />
      <!--#endif-->
    </view>
  </view>
</template>

<script>
  import { crmInstrumentSalesTrend } from 'API/crm/work'
  import uCharts from '@/components/u-charts/u-charts.js'

  let contractChart = null

  // 合同金额目标及完成情况
  export default {
    name: 'ChartContract',
    props: {
      params: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        loading: false,

        cWidth: '',
        cHeight: '',
        pixelRatio: 1,
        serverData: ''
      }
    },
    watch: {
      params: {
        handler() {
          this.getData()
        },
        deep: true
      }
    },
    mounted() {
      const _self = this;
      // #ifdef MP-ALIPAY
      uni.getSystemInfo({
        success: function(res) {
          if (res.pixelRatio > 1) {
            // 正常这里给2就行，如果pixelRatio=3性能会降低一点
            // _self.pixelRatio =res.pixelRatio;
            _self.pixelRatio = 2;
          }
        }
      });
      // #endif
      this.cWidth = uni.upx2px(646);
      this.cHeight = uni.upx2px(450);
      this.gaugeWidth = uni.upx2px(30);
      this.getData();
    },
    methods: {
      getData() {
        if (this.loading) return
        this.loading = true
        crmInstrumentSalesTrend({
          ...this.params,
          type: 1
        }).then(res => {
          this.loading = false
          console.log('合同金额目标及完成情况：', res)
          if (res[0].type.length >= 8) {
            this.forMatter(res)
          }
          const list = res || []
          this.initChart('contractChart', list)
        }).catch(() => {
          this.loading = false
        })
      },

      forMatter(res) {
        res.forEach(item => {
          item.type = item.type.split(' ')[0]
        })
      },

      initChart(canvasId, chartData) {
        const _self = this
        const options = {
          $this: _self,
          canvasId: canvasId,
          width: _self.cWidth * _self.pixelRatio,
          height: _self.cHeight * _self.pixelRatio,
          type: 'column',
          pixelRatio: _self.pixelRatio,
          background: '#FFFFFF',
          fontSize: 11,
          animation: true,
          dataLabel: false,
          padding: [15, 0, 0, 0],
          legend: { // 图例
            show: true,
            position: 'bottom',
            float: 'center',
            padding: 10,
            lineHeight: 11,
            margin: 0
          },
          xAxis: {
            labelCount: 5,
            axisLine: false,
            disableGrid: true,
            itemCount: 3,
            scrollShow: true,
            scrollAlign: 'left'
          },
          yAxis: {
            gridType: 'dash',
            min: 0
          },
          enableScroll: true,
          extra: {
            column: {
              type: 'group',
              width: 15
            }
          },
          categories: chartData.map(o => o.type),
          series: [
            {
              name: '合同金额',
              color: '#6ca2ff',
              data: chartData.map(o => o.money),
              type: 'column'
            }
          ]
        }

        if (
          this.params &&
          !this.$isEmpty(this.params.type) &&
          [
            'quarter',
            'lastQuarter',
            'year',
            'lastYear'
          ].includes(this.params.type)
        ) {
          options.type = 'mix'
          options.series.push({
            name: '目标合同金额',
            color: '#ff7474',
            data: chartData.map(o => o.achievement),
            type: 'line'
          })
        }

        // #ifdef MP-WEIXIN
        this.$nextTick(function() {
          const query = uni.createSelectorQuery().in(this)
          query.select('#' + canvasId)
            .fields({ node: true, size: true })
            .exec(res => {
              // console.log('res: ', res[0])
              const data = res[0]
              const canvas = res[0].node
              const ctx = canvas.getContext('2d')
              options.context = ctx
              options.canvas2d = true
              const dpr = wx.getSystemInfoSync().pixelRatio
              options.width = _self.cWidth * dpr
              options.height = _self.cHeight * dpr
              options.pixelRatio = dpr
              options.extra.column.width = options.extra.column.width * dpr
              canvas.width = options.width
              canvas.height = options.height
              // eslint-disable-next-line new-cap
              contractChart = new uCharts(options)
            })
        })
        // #endif
        // #ifndef MP-WEIXIN
        // eslint-disable-next-line new-cap
        contractChart = new uCharts(options)
        // #endif
      },
      touchMix(e) {
        contractChart.scrollStart(e);
      },
      moveMix(e) {
        contractChart.scroll(e);
      },
      touchEndMix(e) {
        contractChart.scrollEnd(e);
        contractChart.touchLegend(e);
        // 下面是toolTip事件，如果滚动后不需要显示，可不填写
        contractChart.showToolTip(e, {
          format: function(item, category) {
            // console.log(item)
            return category + ' ' + item.name + '：' + item.data + '元'
          }
        });
      }
    }
  }
</script>

<style scoped lang="scss">
.chart-body {
  .charts {
    width: 100%;
    height: 450rpx;
  }
}
</style>
