const PAGE_PATH = '/subPackages/sub_workbench/workbench_code'
const STORAGE_KEY = 'qr_preview_payload'

/**
 * 打开通用二维码预览页（与 PC SalespersonQrCodePreview / QrCodePreview 传参对齐）
 * @param {{ type?: string, payload?: object, title?: string }} options
 */
export function openQrCodePreview(options = {}) {
  const type = options.type || 'doctor'
  const payload = options.payload != null ? options.payload : {}
  uni.setStorageSync(STORAGE_KEY, {
    type,
    payload,
    title: options.title || '',
  })
  uni.navigateTo({
    url: `${PAGE_PATH}?type=${encodeURIComponent(type)}`,
  })
}

export function consumeQrPreviewPayload() {
  const raw = uni.getStorageSync(STORAGE_KEY)
  uni.removeStorageSync(STORAGE_KEY)
  return raw || null
}

export function buildSalespersonQrPayload(info) {
  if (!info) return { type: 'salesperson', payload: {} }
  return {
    type: 'salesperson',
    payload: {
      nick_name: (info.salesperson && info.salesperson.nick_name) ? info.salesperson.nick_name : '',
      qr_code: {
        qr_code: info.qr_code || '',
        store: info.store || {},
      },
    },
  }
}

export function buildClinicQrPayload(store) {
  if (!store) return { type: 'clinic', payload: {} }
  const province = (store.province && store.province.name) ? store.province.name : ''
  const city = (store.city && store.city.name) ? store.city.name : ''
  const position = store.position || ''
  return {
    type: 'clinic',
    payload: {
      title: store.name || '',
      address: `${province}${city}${position}`,
      qr_code: store.qr_code || '',
    },
  }
}
