employeeRanking.js 6.47 KB
// pages/tab/crew/components/employeeRanking/employeeRanking.js
const DEFAULT_CONFIG = {
  performance: {
    sortOptions: [
      { label: '产值', key: '1', type: 'number' },
      { label: '客单价', key: '2', type: 'number' },
      { label: '转化率', key: '3', type: 'percent' }
    ],
    metrics: [
      { label: '个人产值', key: 'personalOutput', dotKey:'outputWarningLevel', type: 'number', width: '234rpx' },
      { label: '个人客单价', key: 'personalUnitPrice', dotKey:'unitPriceWarningLevel', type: 'number', width: '216rpx'},
      { label: '转化率', key: 'personalConversion', dotKey:'conversionWarningLevel', type: 'percent', width: '192rpx' }
    ]
  },
  behavior: {
    sortOptions: [
      { label: '成交数', key: '4', type: 'number' },
      { label: '战败数', key: '5', type: 'number' },
      { label: '录音数', key: '6', type: 'number' }
    ],
    metrics: [
      { label: '成交数', key: 'dealCount', type: 'number' },
      { label: '战败数', key: 'defeatCount', type: 'number' },
      { label: '录音数', key: 'recordingCount', type: 'number' },
      { label: '录音缺失率', key: 'missingRate', type: 'percent' }
    ]
  },
  training: {
    sortOptions: [
      { label: '学习时长', key: '1', type: 'duration' },
      { label: '完成课程数', key: '2', type: 'number' },
      { label: '带教次数', key: '3', type: 'number' }
    ],
    metrics: [
      { label: '学习时长', key: 'studyHours', type: 'duration', width: '234rpx' },
      { label: '完成课程数', key: 'completedCourses', type: 'number', width: '216rpx' },
      { label: '带教次数', key: 'coachingTimes', type: 'number', width: '192rpx' }
    ]
  }
}

const toNumber = (v) => {
  if (v === null || v === undefined) return null
  if (typeof v === 'number') return isNaN(v) ? null : v
  const s = String(v).trim()
  if (!s) return null
  const n = Number(s.replace(/[,%\s]/g, ''))
  return isNaN(n) ? null : n
}

const formatThousands = (v) => {
  const s = String(v)
  if (!s) return s
  const isNeg = s[0] === '-'
  const raw = isNeg ? s.slice(1) : s
  const [intPart, decPart] = raw.split('.')
  const intFmt = String(intPart || '0').replace(/\B(?=(\d{3})+(?!\d))/g, ',')
  const res = decPart ? `${intFmt}.${decPart}` : intFmt
  return isNeg ? `-${res}` : res
}

const formatNumber = (v) => {
  const n = toNumber(v)
  if (n === null) return '-'
  const str = String(n).includes('.') ? n.toFixed(2).replace(/\.?0+$/, '') : String(n)
  return formatThousands(str)
}

const formatPercent = (v) => {
  const n = toNumber(v)
  if (n === null) return '-'
  const str = n.toFixed(2).replace(/\.?0+$/, '')
  return `${formatThousands(str)}%`
}

Component({
  properties: {
    title: { type: String, value: '员工排行' },
    titleIcon: { type: String, value: '' },
    mode: { type: String, value: 'performance' },
    employeeList: { type: Array, value: [] },
    initialSortKey: { type: String, value: '' },
    initialSortOrder: { type: String, value: 'desc' },
		localSort: { type: Boolean, value: false },
		scene: Number
  },

  data: {
    sortOptions: [],
    metrics: [],
    sortKey: '',
    sortOrder: 'desc',
		keyword: '',
		displayList: [],
		dotMaps: {
			0: 'red',
			1: 'yellow',
			2: 'green'
		}
  },

  observers: {
    'mode, employeeList, initialSortKey, initialSortOrder': function () {
      this.sync()
    }
  },

  lifetimes: {
    attached() {
      this.sync()
    }
  },

  methods: {
		input(e) {
			let { value } = e.detail
			this.setData({ keyword: value })
		},
		search() {
			this.applySearch()
		},
		clear() {
			this.setData({keyword: ''}, () => {
				this.applySearch()
			})
		},
		initLoad() {
			let { mode } = this.data
			this.setData({
				sortKey: mode == 'behavior' ? '4' : '1',
				sortOrder: 'desc'
			})
		},
    getConfig() {
      return DEFAULT_CONFIG[this.data.mode] || DEFAULT_CONFIG.performance
    },

    sync() {
      const cfg = this.getConfig()
      const sortKey = this.data.sortKey || cfg.sortOptions[0].key
      const sortOrder = this.data.sortOrder || this.data.initialSortOrder || 'desc'
      const metrics = cfg.metrics || []
      const metricWidth = `${(100 / Math.max(1, metrics.length)).toFixed(2)}%`
			const displayList = this.buildDisplayList(this.getFilteredEmployeeList(this.properties.employeeList), metrics)
      this.setData(
        {
          sortOptions: cfg.sortOptions || [],
          metrics,
          sortKey,
          sortOrder,
          metricWidth,
          displayList,
        }
      )
    },

    openHelp() {
      this.setData({ helpVisible: true })
    },

    closeHelp() {
      this.setData({ helpVisible: false })
    },

    onTapSort(e) {
      const key = e.currentTarget?.dataset?.key
      if (!key) return
      let nextOrder = 'desc'
      if (this.data.sortKey == key) {
        nextOrder = this.data.sortOrder === 'desc' ? 'asc' : 'desc'
      }

      this.setData(
        {
          sortKey: key,
          sortOrder: nextOrder
        },
        () => {
          this.triggerEvent('sortChange', { rankfield: key, rankType: nextOrder })
        }
			)
    },

    onTapEmployee(e) {
			if (this.data.scene == 0) return // 全业务不支持跳转详情
      const idx = e.currentTarget?.dataset?.index
      const employee = Array.isArray(this.data.displayList) ? this.data.displayList[idx] : null
      this.triggerEvent('employeeTap', { employee })
    },

    formatMetricValue(metric, employee) {
      const v = employee?.[metric.key]
      if (metric.type === 'percent') return formatPercent(v)
      return formatNumber(v)
    },

    buildDisplayList(employeeList, metrics) {
      if (!Array.isArray(employeeList) || !Array.isArray(metrics)) return []
      return employeeList.map((emp) => {
        const metricDisplay = {}
        metrics.forEach((m) => {
          metricDisplay[m.key] = this.formatMetricValue(m, emp)
        })
        return {
          ...emp,
          metricDisplay,
        }
      })
    },

		applySearch() {
			const metrics = Array.isArray(this.data.metrics) ? this.data.metrics : this.getConfig().metrics || []
			const displayList = this.buildDisplayList(this.getFilteredEmployeeList(this.properties.employeeList), metrics)
			this.setData({ displayList })
		},

		getFilteredEmployeeList(employeeList) {
			if (!Array.isArray(employeeList)) return []
			const keyword = String(this.data.keyword || '').trim()
			if (!keyword) return employeeList
			return employeeList.filter((emp) => {
				const name = String(emp?.employeeName || '').trim()
				return name.includes(keyword)
			})
		},
  }
})