<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <wk-nav-bar title="商机统计" />

      <view class="filter-tab">
        <view class="filter-box user" @click="handleOpenFilter('userOrDept')">
          <text class="text">
            {{ filterDataTypeLabel }}
          </text>
          <text class="icon" />
        </view>
        <view class="line" />
        <view class="filter-box time" @click="handleOpenFilter('time')">
          <text class="text">
            {{ filterTimeLabel }}
          </text>
          <text class="icon" />
        </view>
      </view>

      <scroll-view
        scroll-y
        class="container">
        <view class="statistics">
          <view class="row">
            <view class="column">
              <view class="text">
                <text class="number yellow">
                  {{ statisticsData.businessMoney }}
                </text>
              </view>
              <view class="desc">
                商机总金额
              </view>
            </view>
            <view class="line" />
            <view class="column">
              <view class="text">
                <text class="number">
                  {{ statisticsData.allBusiness }}
                </text>
                <text class="unit">
                  个
                </text>
              </view>
              <view class="desc">
                商机总数
              </view>
            </view>
          </view>

          <view class="row">
            <view class="column">
              <view class="text">
                <text class="number">
                  {{ statisticsData.endBusiness }}
                </text>
                <text class="unit">
                  个
                </text>
              </view>
              <view class="desc">
                赢单
              </view>
            </view>
            <view class="line" />
            <view class="column">
              <view class="text">
                <text class="number">
                  {{ statisticsData.loseBusiness }}
                </text>
                <text class="unit">
                  个
                </text>
              </view>
              <view class="desc">
                输单
              </view>
            </view>
          </view>
        </view>

        <view class="section-item">
          <view class="section-title">
            <view class="left">
              <image :src="$static('images/home/icon_funnel.png')" class="icon" />
              <text class="text">
                销售漏斗
              </text>
            </view>
            <wk-drop
              v-if="dropOptions.length > 0"
              v-model="dropVal"
              :list="dropOptions"
              @change="handleDropChange" />
          </view>

          <view class="chart-core">
            <!--#ifdef MP-ALIPAY -->
            <canvas
              id="funnelChart"
              canvas-id="funnelChart"
              class="charts"
              :width="cWidth*pixelRatio"
              :height="cHeight*pixelRatio"
              :style="{'width':cWidth+'px','height':cHeight+'px'}"
              @touchstart="touchPie" />
            <!--#endif-->
            <!--#ifndef MP-ALIPAY -->
            <canvas
              id="funnelChart"
              :style="{
                width: cWidth + 'px',
                height: cHeight + 'px'
              }"
              canvas-id="funnelChart"
              type="2d"
              class="charts"
              @touchstart="touchPie" />
            <!--#endif-->
          </view>

          <view class="info-box">
            <view class="box">
              <text class="info" style="color: #FF7300">
                {{ funnelData.winSingle || '0.00' }}元
              </text>
              <text class="mini-title">
                赢单金额
              </text>
            </view>
            <view class="box">
              <text class="info">
                {{ funnelData.loseSingle || '0.00' }}元
              </text>
              <text class="mini-title">
                输单金额
              </text>
            </view>
          </view>
        </view>
      </scroll-view>

      <uni-popup
        ref="filterPopup"
        :mask-click="filterPopupMaskFlag"
        radius="20rpx 20rpx 0 0"
        type="bottom"
        @mask-close="filterMaskClick">
        <workbench-filter
          ref="workbenchFilter"
          :filter-data="filterObj"
          :default-tab="filterDefaultTab"
          @popup-change="childPopupChange"
          @change="handleChangeFilter"
          @close="handleCloseFilter" />
      </uni-popup>
    </view>
  </view>
</template>

<script>
  import { crmInstrumentSellFunnel, QueryDataInfo } from 'API/crm/work'
  import { BusinessStatusOptions } from 'API/crm/business'

  import WorkbenchFilter from '@/components/base/workbench-filter.vue'

  import mixins from './mixins.js'
  import uCharts from '@/components/u-charts/u-charts.js'

  let funnelStatisticsChart = null

  export default {
    name: 'BusinessStatistics',
    components: {
      WorkbenchFilter
    },
    mixins: [mixins],
    data() {
      return {
        statisticsData: {},

        funnelChart: null,
        funnelData: {},

        dropVal: null,
        dropOptions: []
      }
    },
    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(710);
      this.cHeight = uni.upx2px(380);
      this.getBusinessOptions();
    },
    methods: {
      getBusinessOptions() {
        if (this.loading) return
        this.loading = true
        BusinessStatusOptions().then(res => {
          console.log(res, 'res', true)
          this.loading = false
          if (res.length > 0) {
            this.handleDropChange(res[0].flowId)
            this.dropOptions = res.map(item => {
              return {
                label: item.flowName,
                value: item.flowId
              }
            })
          }
        }).catch(() => {
          this.loading = false
        })
      },

      getData() {
        if (this.loading) return
        this.loading = true

        QueryDataInfo({
        ...this.filterData
        }).then(res => {
          this.loading = false
          this.statisticsData = res
        }).catch(() => {
          this.loading = false
        })

        crmInstrumentSellFunnel({
        ...this.filterData,
        typeId: this.dropVal
        }).then(res => {
          this.loading = false
          console.log('销售漏斗：', res)
          res.forEach(item => {
            if (item.settingName == '赢单') {
              this.funnelData['winSingle'] = item.businessMoney
            } else if (item.settingName == '输单') {
              this.funnelData['loseSingle'] = item.businessMoney
            }
          })
          this.initChart('funnelChart', res || [])
        }).catch(() => {
          this.loading = false
        })
      },

      handleDropChange(typeId) {
        console.log('handleDropChange', typeId)
        this.dropVal = typeId
        this.getData()
      },

      initChart(canvasId, chartData) {
        const _self = this
        const seriesData = chartData.map((o, i) => {
          return {
            name: o.settingName,
            data: o.businessNum,
            money: o.businessMoney
          }
        })
        const options = {
          $this: _self,
          canvasId: canvasId,
          width: _self.cWidth * _self.pixelRatio,
          height: _self.cHeight * _self.pixelRatio,
          type: 'funnel',
          pixelRatio: _self.pixelRatio,
          background: '#FFFFFF',
          fontSize: 12,
          animation: false,
          dataLabel: true,
          extra: {
            funnel: {
              border: true,
              activeWidth: 5,
              borderWidth: 2,
              borderColor: '#FFFFFF'
            },
            tooltip: {}
          },
          series: seriesData
        }
        // #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
              canvas.width = options.width
              canvas.height = options.height
              // eslint-disable-next-line new-cap
              funnelStatisticsChart = new uCharts(options)
            })
        })
        // #endif
        // #ifndef MP-WEIXIN
        // eslint-disable-next-line new-cap
        funnelStatisticsChart = new uCharts(options)
        // #endif

        console.log('funnelChart', funnelStatisticsChart)
      },

      touchPie(e) {
        funnelStatisticsChart.showToolTip(e, {
          textList: [
            { text: '' },
            { text: '' }
          ],
          format: function(item, category) {
            console.log('item', item)
            console.log('category', category)
            this.textList = [
              { text: `${item.name}(${item.data})`, color: item.color },
              { text: `金额：${item.money}元`, color: null }
            ]
            return this.textList
          }
        })
      }
    }
  }
</script>

<style scoped lang="scss">
@import "./style.scss";

.info-box {
  width: 100%;
  @include center;
  .box {
    width: 40%;
    color: $dark;
    flex-direction: column;
    @include center;
    .info {
      font-weight: 500;
      font-size: 30rpx;
    }
    .mini-title {
      font-size: 24rpx;
      margin-top: 10rpx;
    }
  }
}
</style>
