mentoring.js 14.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
// packageCrew/pages/mentoring/mentoring.js
const IMG_URL = 'https://img02.glsx.com.cn/weapp/resource/miniprogram/supervisor-miniprogram/'
import api from '~/api/crew/index'
import indexApi from '~/api/index/index'
import studyApi from '~/api/learningCenter/index'
import { uploadImg } from '~/api/api'
import dayjs from 'dayjs'
Page({

  /**
   * 页面的初始数据
   */
  data: {
		IMG_URL,
		navBarHeight: 84,
		orderObj: {
			teachingSceneCode: 1,
			teachingMethodCode: '',
			teachingMethodName: '',
			teachingTopicCode: '',
			teachingTopicName: '',
			teachingTime: '',
			merchantList: [],
			participantList: [],
			taskContext: '',
			imageList: [],
			courseList: []
		},
		formItems: [{
			label: '带教场景',
			value: 'teachingSceneCode',
			type: 'radio'
		}, {
			label: '带教时间',
			value: 'teachingTime',
			type: 'timePicker'
		}, {
			label: '带教方式',
			value: 'teachingMethodCode',
			valueText: 'teachingMethodName',
			itemValue: 'itemValue',
			itemName: 'itemName',
			optionsName: 'teachingMethod',
			type: 'select',
			title: '方式选择',
			selectHeight: '55%'
		}, {
			label: '推送课程',
			value: 'courseList',
			itemValue: 'bcCourseId',
			itemName: 'bcCourseName',
			optionsName: 'course',
			type: 'select',
			hide: true,
			selectMultiple: true,
			title: '课程选择',
			unit: '课'
		}, {
			label: '带教主题',
			value: 'teachingTopicCode',
			valueText: 'teachingTopicName',
			itemValue: 'itemValue',
			itemName: 'itemName',
			optionsName: 'teachingTopic',
			type: 'select',
			title: '主题选择'
		}, {
			label: '带教门店',
			value: 'merchantList',
			itemValue: 'merchantId',
			itemName: 'merchantName',
			optionsName: 'merchant',
			type: 'select',
			selectMultiple: true,
			title: '门店选择',
			unit: '个'
		}, {
			label: '参与人员',
			value: 'participantList',
			itemValue: 'participantPhone',
			itemName: 'participantName',
			optionsName: 'participant',
			type: 'select',
			selectMultiple: true,
			title: '人员选择',
			unit:'人'
		}],
		currentDate: dayjs().valueOf()
	},
	
	navbarReady(e) {
    let navBarHeight = e.detail.height
    this.setData({
      navBarHeight
    })
	},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
		// 任务列表进入
		if (options.id) {
			this.getDetail(options.id)
		} else {
			// 获取线上带教方式字典数据
			this.getDictList('teaching_method_1')
			// 获取线下带教方式字典数据
			this.getDictList('teaching_method_2')
			// 获取带教主题字典数据
			this.getDictList('teaching_topic')
			// 获取门店列表
			this.getMerchantList()
			// 获取课程列表
			this.getCourseList()
		}
		// 获取带教场景字典数据
		this.getDictList('teaching_scene')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

	},
	
	back() {
		wx.navigateBack()
	},
	getDictList(typeCode) {
		api.getMentorDictList({typeCode, businessCode: 'supervisor'}).then(res => {
			this.setData({
				[`${typeCode}_list`]: res.data || []
			})
		})
	},
	getStaffList() {
		let { orderObj } = this.data
		let params = {
			pageNum: 1,
			pageSize: 9999,
			merchantIdList: orderObj?.merchantList?.map(val => {return val.merchantId})
		}
		api.getParticipantOptions(params).then(res => {
			let { code, data, message } = res
			if (code == 0) {
				data?.list?.forEach(val => {
					val.participantName = val.staffName,
					val.participantPhone = val.staffPhone
				})
				this.setData({
					participantList: data?.list || []
				})
			} else {
				wx.$util.showToast(message)
			}
		})
	},
	getMerchantList() {
		indexApi.getSupervisorMerchantList({}).then(res => {
			let { code, data, message } = res
			if (code == 0) {
				this.setData({
					merchantList: data || []
				})
			} else {
				wx.$util.showToast(message)
			}
		})
	},
	getCourseList() {
		let userInfo = wx.$util.getUserInfo()
		let params = {
      pageNum: 1,
      pageSize: 9999,
      staffPhone: userInfo?.phone,
      sortType: 0,
      sortOrder: 'desc'
		}
		studyApi.getRecommendedCourseList(params).then(res => {
			let { code, data, message } = res
			if (code == 0) {
				data?.list?.forEach(val => {
					val.bcCourseId = val.courseId
					val.bcCourseName = val.title
				})
				this.setData({allCourseList: data?.list || []})
			} else {
				wx.$util.showToast(message)
			}
		})
	},
	filterBusiness(data) {
		let names = ['', '延保', '轻改', '权益']
		if (!data) return '-'
		let bizArray = data?.split(',')?.map(item => item.trim()).filter(item => item !== '')
		let result = bizArray.map(index => names[parseInt(index)]).filter(name => name !== '').join(',')
		return result
	},
	// 获取带教任务详情
	getDetail(id) {
		let { formItems} = this.data
		indexApi.getTaskDetail({id}).then(res => {
			let { code, data, message } = res
			if (code == 0) {
				data = {
					...data,
					...data.teachingDetail,
					courseList: data.taskCourseList || [],
					merchantList: data.taskMerchantList || [],
					imageList: data.taskImageList || []
				}
				let taskContextLength = data?.taskContext.length
				if (data?.teachingSceneCode == 1 && data?.teachingMethodCode == 3) {
					let index = formItems?.findIndex(val => val.value == 'courseList')
					this.setData({
						[`formItems[${index}].hide`]: false
					})
				}
				this.setData({
					taskContextLength
				}, () => {
					this.setData({
						orderObj: data || {}
					})
				})
			} else {
				wx.$util.showToast(message)
			}
		})
	},

	changeScene(e) {
		let { formItems, orderObj } = this.data
		if (orderObj.taskStatus == 2) return
		let { value } = e.currentTarget.dataset
		// 切换带教场景 清空带教方式和推送课程
		this.setData({
			['orderObj.teachingMethodCode']: '',
			['orderObj.teachingMethodName']: '',
			['orderObj.courseList']: [],
			'orderObj.teachingSceneCode': value
		})
		// 切换带教场景 隐藏推送课程字段
		let index = formItems?.findIndex(val => val.value == 'courseList')
		this.setData({
			[`formItems[${index}].hide`]: true
		})
	},

	chooseSelect(e) {
		let { item } = e.currentTarget.dataset
		let { orderObj, merchantList, allCourseList, teaching_topic_list, teaching_method_1_list, teaching_method_2_list, participantList } = this.data
		if (orderObj.taskStatus == 2) return
		if (item.optionsName == 'teachingMethod' && !orderObj.teachingSceneCode) return wx.$util.showToast('请先选择带教场景')
		if (item.optionsName == 'participant' && !orderObj?.merchantList?.length) return wx.$util.showToast('请先选择带教门店')
		const selectSources = {
			'teachingMethod': orderObj.teachingSceneCode == 1 ? teaching_method_1_list : teaching_method_2_list,
			'merchant': merchantList,
			'course': allCourseList,
			'teachingTopic': teaching_topic_list,
			'participant': participantList
		}
		this.setData({
			selectType: item.optionsName,
			showSelectPopup: true,
			selectOptions: selectSources[item.optionsName],
			selectTitle: item.title,
			selectMultiple: item.selectMultiple || false,
			labelKey: item.itemName,
			valueKey: item.itemValue,
			selectValue: item.selectMultiple ? orderObj[item.value]?.map(val => { return val[item.itemValue] }) : [orderObj[item.value]],
			selectValues: item.selectMultiple ? orderObj[item.value]?.map(val => { return val[item.itemValue] }) : [orderObj[item.value]],
			selectPopupHeight: item.selectHeight || '85%'
		})
	},

	handlePopupConfirm(e) {
		let { values, items } = e.detail
		let { selectType, formItems, orderObj } = this.data
		let obj = formItems?.find(val => val.optionsName == selectType)
		if (obj.selectMultiple) {
			this.setData({
				[`orderObj.${obj.value}`]: items
			})
		} else {
			this.setData({
				[`orderObj.${obj.value}`]: values[0],
				[`orderObj.${obj.valueText}`]: items[0] && items[0][obj.itemName]
			})
		}
		// 切换带教方式 清空推送课程
		if (selectType == 'teachingMethod' && values[0] != 3) this.setData({['orderObj.courseList']: []})
		// 带教场景为线上 带教方式为推送课程时显示推送课程
		let index = formItems?.findIndex(val => val.value == 'courseList')
		this.setData({
			[`formItems[${index}].hide`]: !(orderObj.teachingSceneCode == 1 && orderObj.teachingMethodCode == 3)
		})
		// 切换带教门店 清空参与人员选项 获取参与人员数据
		if (selectType == 'merchant') {
			this.setData({
				['orderObj.participantList']: []
			}, () => {
				orderObj.merchantList?.length && this.getStaffList()
			})
		}
		this.hideSelectPopup()
	},

	removeMultiSelected(e) {
		if (this.data.orderObj.taskStatus == 2) return
		const field = e.currentTarget?.dataset?.field
		const index = e.currentTarget?.dataset?.index
		if (!field && field !== 0) return
		const list = Array.isArray(this.data.orderObj?.[field]) ? this.data.orderObj[field].slice() : []
		if (index === null || index === undefined || index < 0 || index >= list.length) return
		list.splice(index, 1)

		const payload = {
			[`orderObj.${field}`]: list
		}

		if (field === 'merchantList') {
			payload['orderObj.participantList'] = []
			payload['participantList'] = []
		}

		this.setData(payload, () => {
			if (field === 'merchantList') {
				const nextMerchants = this.data.orderObj?.merchantList || []
				if (nextMerchants.length) this.getStaffList()
			}
		})
	},

	hideSelectPopup() {
		this.setData({
			showSelectPopup: false
		})
	},

	chooseTime() {
		let { orderObj } = this.data
		if (orderObj.taskStatus == 2) return
		const ts = this._parseTimeToTimestamp(orderObj?.teachingTime) || this.data.currentDate || dayjs().valueOf()
		this.setData({ dateShow: true, currentDate: ts, selectedDate: ts })
	},

	_parseTimeToTimestamp(timeStr) {
		if (!timeStr) return null
		const normalized = String(timeStr).trim().replace(/-/g, '/')
		const d = dayjs(normalized)
		return d.isValid() ? d.valueOf() : null
	},

	_normalizePickerTimestamp(raw) {
		if (raw === null || raw === undefined || raw === '') return null
		const v = raw?.value ?? raw?.detail?.value ?? raw
		if (typeof v === 'number') return Number.isFinite(v) ? v : null
		const s = String(v).trim()
		if (!s) return null
		const n = Number(s)
		if (Number.isFinite(n)) return n
		const normalized = s.replace(/-/g, '/')
		const d = dayjs(normalized)
		return d.isValid() ? d.valueOf() : null
	},

	// 取消
	cancel() {
		this.setData({
			dateShow: false
		})
	},
	// 年月日确认
	confirm() {
		const selectedDate = this._normalizePickerTimestamp(this.data.selectedDate) || this._normalizePickerTimestamp(this.data.currentDate) || dayjs().valueOf()
		this.setData({
			dateShow: false,
			currentDate: selectedDate,
			['orderObj.teachingTime']: dayjs(selectedDate).format('YYYY-MM-DD HH:mm')
		});
	},
	onChange(event) {
		const ts = this._normalizePickerTimestamp(event?.detail?.value ?? event?.detail)
		if (!ts) return
		this.setData({ selectedDate: ts })
	},
	onInput(event) {
		// 防止选择之后,取消选择,导致日期不变
		const ts = this._normalizePickerTimestamp(event?.detail?.value ?? event?.detail)
		if (!ts) return
		this.setData({ selectedDate: ts })
	},

	taskContextInput(e) {
		let val = e.detail.value || ""
    if (val.length > 1000) {
      val = val.substring(0, 1000)
    }
    this.setData({ 
      'orderObj.taskContext': val, 
      taskContextLength: val.length 
    })
	},

	handleImageUpload() {
		let _this = this
		let { orderObj } = _this.data
		wx.chooseImage({
			count: 1,
			sourceType: ['album', 'camera'],
      success(res) {
				let [tempFiles] = res.tempFilePaths
				for (const file of res.tempFiles) {
					if (file.size > 10 * 1024 * 1024) {
						return wx.showToast({
							title: '图片上传最大10MB',
							icon: 'none'
						})
					}
				}
        let imgType = tempFiles.split('.')[1]
        let type = imgType == 'unknown' ? 'jpg' : imgType
        wx.getFileSystemManager().readFile({
          filePath: tempFiles, //选择图片返回的相对路径
          encoding: 'base64', //编码格式
          success(_res) {
            wx.$util.showLoading('上传中...')
            uploadImg({
              file: `${type}@${_res.data}`
            }).then(img => {
              wx.$util.hideLoading()
              let { code, data, message } = img
              if (code == 0) {
                orderObj.imageList.push({imageUrl: data})
                _this.setData({
                  orderObj
                })
              } else {
                wx.$util.showToast(message)
              }
            })
          }
        })
      }
    })
	},

	previewImage(e) {
    let { url, index } = e.currentTarget.dataset
    wx.previewImage({
      urls: url?.map(val => {return val.imageUrl}),
      current: url[index].imageUrl
    })
  },

	delPhoto(e) {
		let { index } = e.currentTarget.dataset
		let { orderObj } = this.data
		orderObj.imageList.splice(index, 1)
		this.setData({
			'orderObj.imageList': orderObj.imageList
		})
	},

	submit() {
		let { orderObj, formItems, teaching_scene_list } = this.data
		let requiredList = [
			...formItems?.filter(val => !val.hide),
			{value: 'taskContext'},
			{value: 'imageList'}
		]
		const hasInvalidItem = requiredList?.some((item) => {
			const value = orderObj[item.value]
			return !value || (Array.isArray(value) && value.length === 0);
		});
		
		if (hasInvalidItem) {
			return wx.$util.showToast('请完成所有必填项')
		}
		let params = {
			teachingDetail: {
				teachingSceneCode: orderObj?.teachingSceneCode,
				teachingSceneName: teaching_scene_list?.find(val => val.itemValue == orderObj?.teachingSceneCode)?.itemName,
				teachingTime: orderObj?.teachingTime,
				teachingMethodCode: orderObj?.teachingMethodCode,
				teachingMethodName: orderObj?.teachingMethodName,
				teachingTopicCode: orderObj?.teachingTopicCode,
				teachingTopicName: orderObj?.teachingTopicName
			},
			courseList: orderObj.courseList?.map(val => {return {bcCourseId: val.bcCourseId, bcCourseName: val.bcCourseName}}),
			merchantList: orderObj?.merchantList?.map(val => { return {merchantId: val.merchantId, merchantName: val.merchantName} }),
			participantList: orderObj?.participantList?.map(val => {return {participantPhone: val.participantPhone, participantName: val.participantName}}),
			taskContext: orderObj.taskContext,
			imageList: orderObj.imageList
		}
		wx.$util.showLoading()
		api.submitMentorData(params).then(res => {
			wx.$util.hideLoading()
			let { code, message } = res
			if (code == 0) {
				wx.$util.showToast('操作成功')
				this.back()
			} else {
				wx.$util.showToast(message)
			}
		}).catch(() => {
			wx.$util.hideLoading()
		})
	},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})