teachApplyCreate.js 9.81 KB
import api from '~/api/api'
import {
  formatDirectorNames,
  isStrategyApiSuccess,
  parseStrategyShopMerchantList,
  parseStrategyShopMerchantStaffList,
  parseStrategyShopMerchantSupervisorList,
} from '~/utils/teachApplyItem'

const BUSINESS_OPTIONS = [
  { businessType: 1, businessName: '延保' },
  { businessType: 2, businessName: '轻改' },
  { businessType: 3, businessName: '权益' },
]

const DESCRIPTION_MAX_LENGTH = 200

Page({
  data: {
    navBarHeight: 0,
    merchantId: '',
    merchantName: '',
    businessType: '',
    businessName: '',
    staffList: [],
    staffNames: '',
    supervisorName: '',
    supervisorDisplayText: '选择门店和业务后自动填充',
    supervisorLoading: false,
    description: '',
    descriptionMaxLength: DESCRIPTION_MAX_LENGTH,
    submitting: false,
    merchantPopupShow: false,
    merchantKeyword: '',
    merchantList: [],
    merchantIndex: null,
    merchantLoading: false,
    staffPopupShow: false,
    staffOptions: [],
    staffLoading: false,
  },

  navbarReady(e) {
    this.setData({ navBarHeight: e.detail.height })
  },

  onBack() {
    wx.navigateBack()
  },

  pickMerchant() {
    this.setData(
      {
        merchantPopupShow: true,
        merchantKeyword: '',
        merchantIndex: null,
      },
      () => this.loadMerchantList()
    )
  },

  onMerchantKeywordInput(e) {
    this.setData({ merchantKeyword: e.detail.value || '' })
  },

  clearMerchantKeyword() {
    this.setData({ merchantKeyword: '' }, () => this.loadMerchantList())
  },

  searchMerchant() {
    this.loadMerchantList()
  },

  async loadMerchantList() {
    this.setData({ merchantLoading: true, merchantList: [], merchantIndex: null })
    try {
      const kw = (this.data.merchantKeyword || '').trim()
      const params = {}
      if (kw) params.keyword = kw
      const res = await api.getStrategyShopMerchantList(params)
      const merchantList = parseStrategyShopMerchantList(res)
      if (!merchantList.length && !isStrategyApiSuccess(res)) {
        wx.showToast({ title: res?.message || '加载失败', icon: 'none' })
        this.setData({ merchantList: [], merchantIndex: null })
        return
      }
      const { merchantId } = this.data
      let merchantIndex = null
      if (merchantId) {
        merchantIndex = merchantList.findIndex(
          (item) => String(item.merchantId) === String(merchantId)
        )
        if (merchantIndex < 0) merchantIndex = null
      }
      this.setData({ merchantList, merchantIndex })
    } catch (e) {
      console.error('loadMerchantList', e)
      wx.showToast({ title: '网络异常', icon: 'none' })
    } finally {
      this.setData({ merchantLoading: false })
    }
  },

  chooseMerchant(e) {
    const { index } = e.currentTarget.dataset
    this.setData({ merchantIndex: index })
  },

  cancelMerchantPopup() {
    this.setData({ merchantPopupShow: false })
  },

  async confirmMerchantPopup() {
    const { merchantList, merchantIndex } = this.data
    if (merchantIndex == null || !merchantList[merchantIndex]) {
      wx.showToast({ title: '请选择归属门店', icon: 'none' })
      return
    }
    const { merchantId, merchantName } = merchantList[merchantIndex]
    this.setData({
      merchantPopupShow: false,
      merchantId,
      merchantName,
      staffList: [],
      staffNames: '',
      supervisorName: '',
      supervisorDisplayText: '选择门店和业务后自动填充',
    })
    this.tryLoadSupervisorDisplay()
  },

  tryLoadSupervisorDisplay() {
    const { merchantId, businessType } = this.data
    if (merchantId === '' || merchantId == null) return
    if (businessType === '' || businessType == null || businessType === undefined) {
      return
    }
    this.loadSupervisorDisplay()
  },

  async loadSupervisorDisplay() {
    const { merchantId, businessType } = this.data
    this.setData({
      supervisorLoading: true,
      supervisorName: '',
      supervisorDisplayText: '加载中...',
    })
    try {
      const res = await api.getStrategyShopMerchantSupervisor({
        merchantId,
        businessType: Number(businessType),
      })
      const list = parseStrategyShopMerchantSupervisorList(res)
      const supervisorName = formatDirectorNames(list)
      this.setData({
        supervisorName,
        supervisorDisplayText: supervisorName || '暂无督导',
        supervisorLoading: false,
      })
      if (!supervisorName && !isStrategyApiSuccess(res)) {
        wx.showToast({ title: res?.message || '获取督导失败', icon: 'none' })
      }
    } catch (e) {
      console.error('loadSupervisorDisplay', e)
      wx.showToast({ title: '网络异常', icon: 'none' })
      this.setData({
        supervisorName: '',
        supervisorDisplayText: '获取失败',
        supervisorLoading: false,
      })
    }
  },

  pickBusiness() {
    wx.showActionSheet({
      itemList: BUSINESS_OPTIONS.map((o) => o.businessName),
      success: (res) => {
        const item = BUSINESS_OPTIONS[res.tapIndex]
        if (!item) return
        this.setData(
          {
            businessType: item.businessType,
            businessName: item.businessName,
            supervisorName: '',
            supervisorDisplayText: '选择门店和业务后自动填充',
          },
          () => this.tryLoadSupervisorDisplay()
        )
      },
    })
  },

  pickStaff() {
    const { merchantId } = this.data
    if (!merchantId && merchantId !== 0) {
      wx.showToast({ title: '请先选择归属门店', icon: 'none' })
      return
    }
    this.setData({ staffPopupShow: false }, () => {
      this.setData({ staffPopupShow: true }, () => this.loadStaffList())
    })
  },

  async loadStaffList() {
    const { merchantId, staffList } = this.data
    this.setData({ staffLoading: true, staffOptions: [] })
    try {
      const res = await api.getStrategyShopMerchantStaffList({ merchantId })
      const selectedPhones = new Set(
        (staffList || []).map((s) => String(s.userPhone))
      )
      const staffOptions = parseStrategyShopMerchantStaffList(res).map((item) => ({
        ...item,
        checked: item.userPhone
          ? selectedPhones.has(String(item.userPhone))
          : false,
      }))
      if (!staffOptions.length && !isStrategyApiSuccess(res)) {
        wx.showToast({ title: res?.message || '加载人员失败', icon: 'none' })
      }
      this.setData({ staffOptions })
    } catch (e) {
      wx.showToast({ title: '加载人员失败', icon: 'none' })
    } finally {
      this.setData({ staffLoading: false })
    }
  },

  toggleStaff(e) {
    const { index } = e.currentTarget.dataset
    const staffOptions = [...(this.data.staffOptions || [])]
    if (!staffOptions[index]) return
    staffOptions[index] = {
      ...staffOptions[index],
      checked: !staffOptions[index].checked,
    }
    this.setData({ staffOptions })
  },

  cancelStaffPopup() {
    this.setData({ staffPopupShow: false })
  },

  confirmStaffPopup() {
    const staffList = (this.data.staffOptions || []).filter((item) => item.checked)
    if (!staffList.length) {
      wx.showToast({ title: '请选择需带教驻店人员', icon: 'none' })
      return
    }
    this.setData({
      staffPopupShow: false,
      staffList: staffList.map(({ userPhone, userName }) => ({
        userPhone,
        userName,
      })),
      staffNames: staffList.map((s) => s.userName).join(','),
    })
  },

  onDescInput(e) {
    this.setData({ description: e.detail.value || '' })
  },

  async submit() {
    const {
      merchantId,
      merchantName,
      businessType,
      staffList,
      description,
      supervisorName,
      supervisorLoading,
      submitting,
    } = this.data
    if (submitting) return

    if (!merchantId && merchantId !== 0) {
      wx.showToast({ title: '请选择归属门店', icon: 'none' })
      return
    }
    if (!businessType && businessType !== 0) {
      wx.showToast({ title: '请选择归属业务', icon: 'none' })
      return
    }
    if (!staffList?.length) {
      wx.showToast({ title: '请选择员工', icon: 'none' })
      return
    }
    if (supervisorLoading) {
      wx.showToast({ title: '督导信息加载中', icon: 'none' })
      return
    }
    if (!supervisorName) {
      wx.showToast({ title: '暂无归属区域督导', icon: 'none' })
      return
    }

    const content = (description || '').trim()
    if (!content) {
      wx.showToast({ title: '请填写申请描述', icon: 'none' })
      return
    }
    if (content.length > DESCRIPTION_MAX_LENGTH) {
      wx.showToast({ title: `申请描述不能超过${DESCRIPTION_MAX_LENGTH}字`, icon: 'none' })
      return
    }

    const invalidStaff = staffList.some(
      (s) => !(s.userName || '').trim() || !(s.userPhone || '').trim()
    )
    if (invalidStaff) {
      wx.showToast({ title: '驻店人员信息不完整', icon: 'none' })
      return
    }

    this.setData({ submitting: true })
    wx.showLoading({ title: '提交中', mask: true })
    try {
      const res = await api.submitTeachingApplication({
        merchantId: Number(merchantId),
        merchantName,
        businessType: Number(businessType),
        staffListJson: JSON.stringify(
          staffList.map((s) => ({
            userPhone: String(s.userPhone).trim(),
            userName: String(s.userName).trim(),
          }))
        ),
        description: content,
      })
      if (res?.code !== '0' && res?.code !== 0) {
        wx.showToast({
          title: res?.message || '提交失败',
          icon: 'none',
        })
        return
      }
      wx.showToast({ title: '提交成功', icon: 'success' })
      this.notifyRefresh()
      setTimeout(() => wx.navigateBack(), 1000)
    } catch (e) {
      wx.showToast({ title: '提交失败', icon: 'none' })
    } finally {
      wx.hideLoading()
      this.setData({ submitting: false })
    }
  },

  notifyRefresh() {
    const eventChannel = this.getOpenerEventChannel()
    eventChannel?.emit?.('refreshList')
  },
})