<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.contractMoney }}
                </text>
              </view>
              <view class="desc">
                合同总金额
              </view>
            </view>
            <view class="line" />
            <view class="column">
              <view class="text">
                <text class="number yellow">
                  {{ statisticsData.receivablesMoney }}
                </text>
              </view>
              <view class="desc">
                回款总金额
              </view>
            </view>
          </view>

          <view class="row">
            <view class="column">
              <view class="text">
                <text class="number">
                  {{ statisticsData.allContract }}
                </text>
                <text class="unit">
                  个
                </text>
              </view>
              <view class="desc">
                签约合同数
              </view>
            </view>
            <view class="line" />
            <view class="column">
              <view class="text">
                <text class="number">
                  {{ statisticsData.dealCustomer }}
                </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.endContract }}
                </text>
                <text class="unit">
                  个
                </text>
              </view>
              <view class="desc">
                已到期的合同
              </view>
            </view>
            <view class="line" />
            <view class="column">
              <view class="text">
                <text class="number">
                  {{ statisticsData.expireContract }}
                </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_statis.png')" class="icon" />
              <text class="text">
                趋势分析
              </text>
            </view>
          </view>

          <view class="chart-core">
            <!--#ifdef MP-ALIPAY -->
            <canvas
              id="contractStatistics"
              canvas-id="contractStatistics"
              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="contractStatistics"
              :style="{
                width: cWidth + 'px',
                height: cHeight + 'px'
              }"
              canvas-id="contractStatistics"
              type="2d"
              class="charts"
              :disable-scroll="true"
              @touchstart="touchMix"
              @touchmove="moveMix"
              @touchend="touchEndMix" />
            <!--#endif-->
          </view>
        </view>

        <!-- <view class="section-item">
					<view class="section-title">
						<view class="left">
							<image :src="$static('images/home/icon_statis.png')" class="icon"></image>
							<text class="text">合同类型分析</text>
						</view>
					</view>

					<view class="section-body">
						<view class="cell">
							<view class="cell-left">直销合同</view>
							<view class="cell-right">5单(￥50052)</view>
						</view>
						<view class="cell">
							<view class="cell-left">代理合同</view>
							<view class="cell-right">155单(￥50052)</view>
						</view>
						<view class="cell">
							<view class="cell-left">服务合同</view>
							<view class="cell-right">15单(￥50052)</view>
						</view>
						<view class="cell">
							<view class="cell-left">快销合同</view>
							<view class="cell-right">32单(￥50052)</view>
						</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 { crmInstrumentSalesTrend, QueryDataInfo } from 'API/crm/work'
  import WorkbenchFilter from '@/components/base/workbench-filter.vue'

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

  let contractStatisticsChart = null

  export default {
    name: 'ContractStatistics',
    components: {
      WorkbenchFilter
    },
    mixins: [mixins],
    data() {
      return {
        statisticsData: {},
        chartInstance: null,
      }
    },
    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(686)
      this.cHeight = uni.upx2px(450)
      this.getData()
    },
    methods: {
      getData() {
        if (this.loading) return
        this.loading = true
        QueryDataInfo({
					...this.filterData
        }).then(res => {
          this.loading = false
          this.statisticsData = res
        }).catch(() => {
          this.loading = false
        })

        Promise.all([
          crmInstrumentSalesTrend({
						...this.filterData,
						type: 1 // 合同
          }),
          crmInstrumentSalesTrend({
						...this.filterData,
						type: 2 // 回款
          }),
        ]).then(resArr => {
          console.log('resArr', resArr)
          if (resArr[0][0].type.length >= 8) {
            this.forMatter(resArr)
          }
          this.loading = false
          const contractList = resArr[0]
          const refundList = resArr[1]
          const data = []
          contractList.forEach(item => {
            const findRes = refundList.find(o => o.type === item.type)
            if (findRes) {
              data.push({
                type: item.type,
                contractMoney: item.money,
                refundMoney: findRes.money
              })
            }
          })
          this.initChart('contractStatistics', data)
        }).catch(() => {
          this.loading = false
        })
      },
			
      forMatter(res) {
        res.forEach(item => {
          item.forEach(val => {
            val.type = val.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'
          },
          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.contractMoney),
              type: 'column'
            },
            {
              name: '回款总金额',
              color: '#FF7300',
              data: chartData.map(o => o.refundMoney),
              type: 'column'
            },
          ]
        }

        // #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
              contractStatisticsChart = new uCharts(options)
            })
        })
        // #endif
        // #ifndef MP-WEIXIN
        // eslint-disable-next-line new-cap
        contractStatisticsChart = new uCharts(options)
        // #endif
      },

      touchMix(e) {
        contractStatisticsChart.scrollStart(e);
      },
      moveMix(e) {
        contractStatisticsChart.scroll(e);
      },
      touchEndMix(e) {
        contractStatisticsChart.scrollEnd(e);
        contractStatisticsChart.touchLegend(e);
        // 下面是toolTip事件，如果滚动后不需要显示，可不填写
        contractStatisticsChart.showToolTip(e, {
          format: function(item, category) {
            // console.log(item)
            return category + ' ' + item.name + '：' + item.data + '元'
          }
        });
      }
    }
  }
</script>

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

	.section-body {
		padding-top: 15rpx;
		.cell {
			width: 100%;
			font-size: $wk-font-base;
			padding: 20rpx 0;
			@include left;
			.cell-left {
				width: 200rpx;
				color: $dark;
			}
			.cell-right {
				flex: 1;
				color: $gray;
				@include right;
			}
		}
	}

</style>
