<template>
  <view class="uni-app">
    <view class="status-bar" />
    <view class="main-container">
      <view class="header linear-gradient">
        <view class="header-title">
          首页
        </view>
        <!-- #ifndef MP-WEIXIN -->
        <view class="avatar-box">
          <wk-avatar :name="userInfo.realname" :avatar="userInfo.img" :size="12" class="avatar" />
        </view>
        <!-- #endif -->
      </view>

      <view
        v-if="showTopFilter"
        class="filter-sticky">
        <view class="title">
          仪表盘
        </view>
        <view class="filter-box user" @click="handleOpenFilter('userOrDept')">
          <text class="text">
            {{ filterDataTypeLabel }}
          </text>
          <text class="icon" />
        </view>
        <view class="filter-box time" @click="handleOpenFilter('time')">
          <text class="text">
            {{ filterTimeLabel }}
          </text>
          <text class="icon" />
        </view>
      </view>

      <wk-scroll-view
        :scroll-top="scrollTop"
        :show-empty="false"
        :load-more="false"
        :status="listStatus"
        class="container"
        @refresh="handleRefresh"
        @scroll="handleScrollFn">
        <view class="quick-wrapper">
          <view class="bg linear-gradient" />
          <view class="quick-list">
            <view
              v-for="item in quickList"
              :key="item.type"
              class="quick-list-item"
              @click="handleNavigateTo(item)">
              <image :src="$static(item.img)" class="img" />
              <text class="text">
                {{ item.label }}
              </text>
            </view>

            <view
              v-for="i in (4 - quickList.length)"
              :key="i"
              class="quick-list-item hidden" />
          </view>
        </view>

        <view class="common-section">
          <view class="section-header">
            <view class="left">
              常用功能
            </view>
            <view class="filter-box" @click="handleToggleConfigPopup">
              <text class="text">
                配置
              </text>
              <image :src="$static('images/icon/config.png')" class="pic" />
            </view>
          </view>

          <view class="common-list">
            <view
              v-for="item in commonList"
              :key="item.type"
              class="common-list-item"
              @click="handleNavigateTo(item)">
              <image :src="$static(item.icon)" class="img" />
              <text class="text">
                {{ item.label }}
              </text>
            </view>

            <template v-if="commonList.length % 4 !== 0">
              <view
                v-for="i in (4 - commonList.length % 4)"
                :key="i"
                class="common-list-item hidden" />
            </template>
          </view>
        </view>

        <view class="panel-section">
          <!-- @touchmove="handleTouchMove" -->
          <view class="section-header">
            <view class="left">
              仪表盘
            </view>
            <view class="filter-box user" @click="handleOpenFilter('userOrDept')">
              <text class="text">
                {{ filterDataTypeLabel }}
              </text>
              <text class="icon" />
            </view>
            <view class="filter-box time" @click="handleOpenFilter('time')">
              <text class="text">
                {{ filterTimeLabel }}
              </text>
              <text class="icon" />
            </view>
          </view>

          <view class="section-item scroll-view-hook">
            <view class="section-title">
              <view class="left">
                <image :src="$static('images/home/icon_sales.png')" class="icon" />
                <text class="text">
                  销售简报
                </text>
              </view>
            </view>
            <view class="report-list">
              <view
                v-for="(item, index) in reportList"
                :key="index"
                class="report-list-item"
                @click="handleReportTo(item)">
                <view class="text">
                  {{ item.label }}
                </view>
                <view class="num">
                  {{ item.unit || '' }}{{ item.num }}
                </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>
            <chart-contract :params="filterData" />
          </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>
            <chart-refund :params="filterData" />
          </view>

          <view class="section-item">
            <view class="section-title">
              <view class="left">
                <image :src="$static('images/home/icon_slices.png')" class="icon" />
                <text class="text">
                  业绩指标完成率（{{ performanceText }}）
                </text>
              </view>
              <!-- <wk-drop
								v-model="performanceVal"
								:list="performanceOptions"
								@change="handlePerformanceChange" /> -->
              <view class="drop-control" @click="handleOpenDrop('performance')">
                <view class="drop-label">
                  {{ performanceText }}
                </view>
                <view ref="icon" class="drop-icon">
                  <text class="wk wk-arrow-right icon" />
                </view>
              </view>
            </view>
            <chart-performance ref="performance" :params="filterData" />
          </view>

          <view class="section-item rank">
            <view class="section-title">
              <view class="left">
                <image :src="$static('images/home/icon_ranking.png')" class="icon" />
                <text class="text">
                  排行榜
                </text>
              </view>
              <view class="right">
                <!-- <wk-drop
									v-model="rankVal"
									:list="rankOptions"
									@change="handleRankChange" /> -->

                <view class="drop-control" @click="handleOpenDrop('rank')">
                  <view class="drop-label">
                    {{ rankText }}
                  </view>
                  <view ref="icon" class="drop-icon">
                    <text class="wk wk-arrow-right icon" />
                  </view>
                </view>
              </view>
            </view>
            <chart-ranking ref="rank" :params="filterData" />
          </view>
        </view>
      </wk-scroll-view>
    </view>

    <wk-tabbar v-model="footerIndex" :list="mixinFooterNav" />

    <uni-popup ref="popup" :mask-click="false" type="dialog">
      <wk-popup-expiration />
    </uni-popup>

    <uni-popup
      ref="popupBottom"
      radius="10rpx 10rpx 0 0"
      type="bottom">
      <wk-action-sheet
        :list="configPopupList"
        label="label"
        @select="handleSelectConfig" />
    </uni-popup>

    <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>

    <!-- 小程序scroll-view中fixed定位有问题 -->
    <uni-popup
      ref="dropPopup"
      radius="10rpx 10rpx 0 0"
      type="bottom">
      <view class="filter-popup">
        <view class="popup-header">
          <view class="text">
            筛选
          </view>
          <text class="wk wk-close icon" @click="handleCloseDrop" />
        </view>
        <view class="popup-content">
          <view class="list">
            <view
              v-for="item in dropList"
              :key="item.value"
              :class="{active: dropVal === item.value}"
              class="list-item"
              @click="handleDropSelect(item)">
              <text class="text">
                {{ item.label }}
              </text>
              <text v-show="dropVal === item.value" class="wk wk-check icon" />
            </view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
  import {
    crmInstrumentQueryBulletin
  } from 'API/crm/work'

  import WorkbenchFilter from '@/components/base/workbench-filter.vue'
  import ChartContract from './components/chartContract'
  import ChartRefund from './components/chartRefund'
  import ChartPerformance from './components/chartPerformance'
  import ChartRanking from './components/chartRanking'

  import tabbar from '@/mixins/tabbar.js'
  import { getQuickList, getCommonNavList, timeOptions } from '@/utils/data.js'
  import { deepCopy } from '@/utils/lib.js'
  import { DEFAULT_NAV_CONFIG } from '@/config.js'
  import {
    mapGetters
  } from 'vuex'

  export default {
    name: 'HomeIndex',
    components: {
      WorkbenchFilter,
      ChartContract,
      ChartRefund,
      ChartPerformance,
      ChartRanking
    },
    mixins: [tabbar],
    data() {
      return {
        reportList: [
          {
            label: '新增客户',
            key: 'customerCount',
            num: 0,
            type: 'customer'
          },
          {
            label: '新增联系人',
            key: 'contactsCount',
            num: 0,
            type: 'contacts'
          },
          {
            label: '新增商机',
            key: 'businessCount',
            num: 0,
            type: 'business'
          },
          {
            label: '新增合同',
            key: 'contractCount',
            num: 0,
            type: 'contract'
          },
          {
            label: '合同金额',
            key: 'contractMoney',
            num: 0,
            unit: '￥',
            type: 'contract_money'
          },
          {
            label: '商机金额',
            key: 'businessMoney',
            num: 0,
            unit: '￥',
            type: 'business_money'
          },
          {
            label: '回款金额',
            key: 'receivablesMoney',
            num: 0,
            unit: '￥',
            type: 'receivables_money'
          },
          {
            label: '新增跟进记录',
            key: 'recordCount',
            num: 0,
            type: 'record'
          },
        ],

        performanceVal: 1,
        performanceOptions: [
          { label: '回款金额', value: 2 },
          { label: '合同金额', value: 1 }
        ],
        rankVal: 1,
        rankOptions: [
          { label: '合同金额', value: 1 },
          { label: '回款金额', value: 2 },
          { label: '合同数', value: 3 },
          { label: '新增客户', value: 4 },
          { label: '新增联系人', value: 5 },
          { label: '新增跟进记录', value: 8 }
        ],

        dropVal: null,
        dropType: '',
        dropList: [],

        filterData: {
          dateFilter: 'month',
          dataType: 2
        },
        filterObj: null,
        filterDefaultTab: 'userOrDept',
        loading: false,
        filterPopupMaskFlag: true,

        configPopupList: [
          { label: '快速入口设置', url: '/pages/home/quickConfig' },
          { label: '常用功能设置', url: '/pages/home/commonConfig' }
        ],
        filterDataTypeOptions: [
          { label: '仅本人', value: 1 },
          { label: '本人及下属', value: 2 },
          { label: '仅本部门', value: 3 },
          { label: '本部门及下属部门', value: 4 },
          { label: '自定义', value: 0 }
        ],

        scrollMin: 0, // 显示顶部filter距离阀值
        showTopFilter: false,

        oldScrollTop: 0,
        scrollTop: 0,
        listStatus: '',

        mousePageY: 0
      }
    },
    computed: {
			...mapGetters({
				userInfo: 'user/userInfo',
				showExpiration: 'user/showExpiration',
				navConfig: 'user/navConfig'
			}),

			quickList() {
				const config = this.$isEmpty(this.navConfig) ? {} : this.navConfig
				const arr = this.$isEmpty(config.quick) ? DEFAULT_NAV_CONFIG.quick : config.quick
				return getQuickList(arr)
			},

			commonList() {
				const config = this.$isEmpty(this.navConfig) ? {} : this.navConfig
				const arr = this.$isEmpty(config.common) ? DEFAULT_NAV_CONFIG.common : config.common
				return getCommonNavList(arr)
			},

			// 筛选范围label
      filterDataTypeLabel() {
        const dataType = this.filterData.dataType || null
        if (!dataType || dataType === -1) {
          // const data = this.filterObj.userOrDeptData
          // const flag = data.type === 1
          // return flag ? data.data[0].name : data.data[0].realname
          return '自定义'
        } else {
          const findRes = this.filterDataTypeOptions.find(o => o.value === dataType)
          if (findRes) {
            return findRes.label
          }
        }
        return ''
      },
			// 筛选时间label
      filterTimeLabel() {
        const type = this.filterData.dateFilter
        if (!type || type === -1 || type === 'custom') {
          // const startTime = this.filterObj.startTime.replace(/-/g, '.')
          // const endTime = this.filterObj.endTime.replace(/-/g, '.')
          const startTime = this.filterObj.startDate
          const endTime = this.filterObj.endDate
          return `${startTime}~${endTime}`
        } else {
          const findRes = timeOptions.find(o => o.value === type)
          if (findRes) {
            return findRes.label
          }
        }
        return ''
      },

			hasToken() {
				return !!(uni.getStorageSync('token') || null)
			},
			performanceText() {
				return this.performanceOptions.find(o => o.value === this.performanceVal).label
			},
			rankText() {
				return this.rankOptions.find(o => o.value === this.rankVal).label
			}
    },
    watch: {
      showExpiration: {
        handler() {
          if (this.showExpiration) {
            this.$nextTick(function() {
              this.$refs.popup.open()
            })
          }
        },
        immediate: true,
        deep: true
      }
    },
    onBackPress(evt) {
      if (evt.from === 'backbutton' && this.showFilter) {
        this.showFilter = !this.showFilter
        return true // 返回值为 true 时，表示不执行默认的返回
      }
      return false
    },
    mounted() {
      if (this.hasToken) {
        const cache = uni.getStorageSync('homeFilterConfig') || null
        if (cache) {
          this.filterObj = cache.obj
          this.filterData = cache.data
        }
        this.getData()
        this.handlePerformanceChange(this.performanceVal)
        this.handleRankChange(this.rankVal)
      } else {
        this.$Router.reLaunch('/pages/login/index')
      }
      this.$nextTick(function() {
        this.setScrollMin()
      })
    },
    methods: {
      // handleTouchMove(e) {
      // 	// console.log('www move', e)
      // 	const targetId = e.target.id
      // 	if (!targetId.endsWith('Chart')) return
      // 	const pageY = e.touches[0].pageY

      // 	this.scrollTop = this.oldScrollTop
      // 	this.$nextTick(() => {
      // 		this.scrollTop = this.oldScrollTop + ((this.mousePageY - pageY) * 3)
      // 		this.mousePageY = e.touches[0].pageY
      // 	})
      // },
      handleRefresh() {
        this.listStatus = 'loading'
        this.getData()
        this.filterData = deepCopy(this.filterData)
        this.handlePerformanceChange(this.performanceVal)
        // this.handleRankChange(this.rankVal)
      },
      getData() {
        if (this.loading) return
        this.loading = true
        crmInstrumentQueryBulletin(this.filterData).then(res => {
          this.loading = false
          let obj = res[6] || null
          if (!obj) return
          this.reportList.forEach(item => {
            item.num = obj[item.key] || 0
          })
          this.listStatus = 'noMore'
        }).catch(() => {
          this.loading = false
        })
      },

      /**
       * 设置滚动距离阀值
       */
      setScrollMin() {
        const that = this
        const query = uni.createSelectorQuery().in(this)
        query.select('.scroll-view-hook')
          .boundingClientRect(data => {
            that.scrollMin = data.top - uni.upx2px(88)
          }).exec()
      },

      /**
       * 滚动回调
       * @param {Object} evt
       */
      handleScrollFn(evt) {
        this.oldScrollTop = evt.detail.scrollTop
        // console.log('oldScrollTop', this.oldScrollTop)
        const flag = this.oldScrollTop >= this.scrollMin
        if (flag !== this.showTopFilter) {
          this.showTopFilter = flag
          // const step = (flag ? 1 : -1) * uni.upx2px(88)
          // this.scrollTop = this.oldScrollTop + step

          // console.log('-----', step, this.oldScrollTop)
          // this.scrollTop = this.oldScrollTop
          // this.$nextTick(() => {
          // 	this.scrollTop = this.oldScrollTop + step
          // })
        }
      },

      /**
       * 筛选
       */
      handleOpenFilter(tab) {
        this.filterDefaultTab = tab
        this.$refs.filterPopup.open()
      },
      handleCloseFilter() {
        this.$refs.filterPopup.close()
      },
      filterMaskClick() {
        if (!this.filterPopupMaskFlag) {
          this.$refs.workbenchFilter.closeChildPopup()
        }
      },
      childPopupChange(flag) {
        this.filterPopupMaskFlag = !flag
      },

      handleChangeFilter(filterObj, data) {
        console.info('handleChangeFilter: ', filterObj, data)
        this.filterObj = filterObj
        this.filterData = filterObj
        // uni.setStorageSync('homeFilterConfig', {
        //   obj: filterObj,
        //   data: data
        // })
        this.getData()
        this.handlePerformanceChange(this.performanceVal)
        this.handleRankChange(this.rankVal)
      },

      handleToggleConfigPopup(type) {
        this.$refs.popupBottom.open()
      },

      handleSelectConfig(index, item, next) {
        next()
        this.$Router.navigateTo(item.url)
      },

      handleOpenDrop(type) {
        this.dropType = type
        this.dropVal = this[`${type}Val`]
        this.dropList = deepCopy(this[`${type}Options`])
        this.$refs.dropPopup.open()
      },
      handleCloseDrop() {
        this.$refs.dropPopup.close()
      },
      handleDropSelect(item) {
        this.dropVal = item.value
        this[`${this.dropType}Val`] = item.value
        this.handleCloseDrop()
        if (this.dropType === 'performance') {
          this.handlePerformanceChange(this.dropVal)
        } else if (this.dropType === 'rank') {
          this.handleRankChange(this.dropVal)
        }
        this.dropType = ''
        this.dropVal = null
      },

      /**
       * 跳转
       */
      handleNavigateTo(item) {
        if (item.auth && !this.$auth(item.auth)) {
          this.$toast('权限不足')
          return
        }
        this.$Router.navigateTo({
          url: item.url,
          query: item.query || {}
        })
      },

      handleReportTo(item) {
        if (item.type !== 'record') {
          this.$Router.navigateTo({
            url: '/pages_crm/homeReport/report',
            query: {
              module: item.type,
							...this.filterData
            }
          })
        } else {
          this.$Router.navigateTo({
            url: '/pages_crm/homeReport/recordCountList',
            query: this.filterData
          })
        }
      },

      handlePerformanceChange(val) {
        this.$nextTick(() => {
          this.$refs.performance.getData(val)
        })
      },
      handleRankChange(val) {
        this.$nextTick(() => {
          this.$refs.rank.getData(val)
        })
      }
    }
  }
</script>

<style scoped lang="scss">
.main-container {
  position: relative;
  .header {
    width: 100%;
    height: 88rpx;
    padding: 0 32rpx;
    @include left;

    .header-title {
      flex: 1;
      font-size: 34rpx;
      color: white;
    }

    .avatar-box {
      width: 64rpx;
      height: 64rpx;

      .avatar {
        width: 100%;
        height: 100%;
      }
    }
  }

  .filter-sticky {
    position: relative;
    z-index: 1;
    width: 100%;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
    background-color: white;
    padding: 15rpx 20rpx;
    @include left;

    .title {
      flex: 1;
      font-size: 30rpx;
      font-weight: bold;
      color: $dark;
    }

    .filter-box {
      @include center;
      &.user {
        margin-right: 15rpx;
      }
      .icon {
        width: 0;
        height: 0;
        border-left: 10rpx solid transparent;
        border-right: 10rpx solid transparent;
        border-top: 10rpx solid $gray;
        margin-left: 10rpx;
      }
      .text {
        font-size: 24rpx;
      }
    }
  }

  .container {
    flex: 1;
    overflow: hidden;

    .quick-wrapper {
      position: relative;
      width: 100%;
      padding: 10rpx 20rpx 0;

      .bg {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 128rpx;
      }

      .quick-list {
        position: relative;
        width: 100%;
        height: 188rpx;
        box-shadow: 0px 6rpx 50rpx rgba(148, 153, 181, 0.38);
        border-radius: 24rpx;
        background: #FFFFFF;
        padding: 0 32rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .quick-list-item {
          width: 20%;
          flex-direction: column;
          padding: 20rpx 0;
          @include center;

          &.hidden {
            visibility: hidden;
          }

          .img {
            width: 64rpx;
            height: 64rpx;
          }

          .text {
            font-size: 24rpx;
            margin-top: 10rpx;
          }
        }
      }
    }

    .section-header {
      margin-top: 30rpx;
      margin-bottom: 20rpx;
      @include left;

      .left {
        flex: 1;
        font-size: 30rpx;
        font-weight: bold;
        color: $dark;
      }

      .filter-box {
        background-color: white;
        padding: 10rpx 15rpx;
        border-radius: 12rpx;
        @include center;

        &.user {
          margin-right: 15rpx;
        }

        .pic {
          width: 32rpx;
          height: 32rpx;
          margin-left: 15rpx;
        }

        .icon {
          width: 0;
          height: 0;
          border-left: 10rpx solid transparent;
          border-right: 10rpx solid transparent;
          border-top: 10rpx solid $gray;
          margin-left: 10rpx;
        }

        .text {
          font-size: 24rpx;
        }
      }
    }

    .common-section {
      padding: 0 20rpx;
      overflow: hidden;

      .common-list {
        width: 100%;
        display: flex;
        justify-content: space-between;
        flex-wrap: wrap;

        .common-list-item {
          width: 164rpx;
          height: 144rpx;
          background-color: white;
          box-shadow: 0px 3rpx 9rpx rgba(210, 212, 220, 0.77);
          border-radius: 16rpx;
          margin-bottom: 12rpx;
          flex-direction: column;
          @include center;

          &.hidden {
            visibility: hidden;
          }

          .img {
            width: 60rpx;
            height: 60rpx;
          }

          .text {
            font-size: 24rpx;
            margin-top: 10rpx;
          }
        }
      }
    }

    .panel-section {
      padding: 0 20rpx;
      overflow: hidden;

      .section-header {
        margin-top: 20rpx;
      }

      .section-item {
        width: 100%;
        background-color: white;
        border: 1rpx solid $border-color;
				border-top: 4rpx solid $theme-color;
        border-radius: 4rpx;
        padding: 25rpx 20rpx;
        margin-bottom: 15rpx;

        .section-title {
          width: 100%;
          @include left;

          .left {
            flex: 1;

            .icon {
              width: 40rpx;
              height: 40rpx;
              vertical-align: middle;
              margin-right: 10rpx;
            }

            .text {
              font-size: 28rpx;
              font-weight: bold;
              color: #212121;
              vertical-align: middle;
            }
          }
        }

        &.rank {
          padding-bottom: 15rpx;
        }
      }

      .report-list {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        margin-bottom: 10rpx;

        .report-list-item {
          width: 48.5%;
          height: 120rpx;
          flex-direction: column;
          background-color: #EEF0F4;
          border-radius: 6rpx;
          padding: 0 24rpx;
          margin-top: 15rpx;
          @include center;
          .text {
            width: 100%;
            font-size: $wk-font-base;
            color: $gray;
          }
          .num {
            width: 100%;
            font-size: $wk-font-large;
            font-weight: bold;
          }

        }
      }
    }
  }
}

.drop-control {
  font-size: 26rpx;
  background-color: #F5F5F5;
  border-radius: 4rpx;
  padding: 8rpx 15rpx;
  @include left;
  .drop-label {
    color: $gray;
    margin-right: 15rpx;
    line-height: 1;
  }
  .drop-icon {
    will-change: transform;
    transition: all ease .2s;
    @include center;
    .icon {
      line-height: 1;
      font-size: 24rpx;
      transform: rotate(90deg);
    }
    &.active {
      transform: rotate(180deg);
    }
  }
}
.filter-popup {
  padding: 10rpx 36rpx 20rpx;

  .popup-header {
    position: relative;
    @include center;
    .text {
      font-size: $wk-font-large;
    }
    .icon {
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      color: $gray;
      font-size: $wk-font-medium;
    }
  }

  .popup-content {
    width: 100%;
    min-height: 500rpx;
    max-height: 700rpx;
    overflow: auto;
    margin-top: 38rpx;

    .list {
      width: 100%;
      .list-item {
        color: $dark;
        font-size: $wk-font-base;
        border-bottom: 1rpx solid $border-color;
        padding: 22rpx 0;
        @include left;

        .text {
          flex: 1;
        }
        .icon {
          font-size: $wk-font-medium;
          color: inherit;
          line-height: 1;
        }

        &.active {
          color: $theme-color;
        }
      }
    }
  }
}
</style>
