user.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. import type { MemberVO } from '@/api/globals'
  2. import { defineStore } from 'pinia'
  3. import router from '@/router'
  4. interface userStroe {
  5. token: string
  6. /**
  7. * 用户登录信息
  8. */
  9. userInfo: MemberVO
  10. redirectName: string
  11. lat: number
  12. lng: number
  13. }
  14. export const useUserStore = defineStore('user', {
  15. state: (): userStroe => ({
  16. token: '',
  17. userInfo: {
  18. id: 0,
  19. channelId: 0,
  20. channelName: '',
  21. },
  22. redirectName: '',
  23. lat: 0,
  24. lng: 0,
  25. }),
  26. actions: {
  27. // H5 环境获取位置(使用 uni.getLocation,兼容微信浏览器)
  28. getLocationH5() {
  29. return new Promise((resolve, reject) => {
  30. uni.showLoading({ mask: true, title: '获取位置中...' })
  31. // if (navigator.geolocation) {
  32. // // 调用定位接口(enableHighAccuracy:是否高精度定位)
  33. // navigator.geolocation.getCurrentPosition(
  34. // // 定位成功回调(返回经纬度)
  35. // (position) => {
  36. // this.lat = Number(position.coords.latitude.toFixed(6))
  37. // this.lng = Number(position.coords.longitude.toFixed(6))
  38. // resolve(true)
  39. // uni.hideLoading()
  40. // },
  41. // // 定位失败回调(处理用户拒绝、设备无GPS等情况)
  42. // (error) => {
  43. // reject(error.code)
  44. // uni.hideLoading()
  45. // switch (error.code) {
  46. // case error.PERMISSION_DENIED:
  47. // console.log('用户拒绝了定位权限')
  48. // // 提示用户开启定位:引导打开手机系统定位 + 微信定位权限
  49. // useGlobalToast().show('请允许定位权限以获取当前位置')
  50. // break
  51. // case error.POSITION_UNAVAILABLE:
  52. // console.log('定位信息不可用')
  53. // useGlobalToast().show('无法获取定位,请检查设备GPS是否开启')
  54. // break
  55. // case error.TIMEOUT:
  56. // console.log('定位请求超时')
  57. // useGlobalToast().show('定位超时,请重试')
  58. // break
  59. // }
  60. // },
  61. // // 可选配置项
  62. // {
  63. // enableHighAccuracy: true, // 开启高精度(GPS定位,耗时稍长),关闭则用网络定位(更快但精度低)
  64. // timeout: 10000, // 超时时间(10秒)
  65. // maximumAge: 300000, // 缓存时间(5分钟内重复定位可复用之前结果)
  66. // },
  67. // )
  68. // }
  69. // else {
  70. // }
  71. uni.getLocation({
  72. type: 'wgs84',
  73. geocode: true,
  74. success: (res) => {
  75. uni.hideLoading()
  76. console.log('H5位置获取成功', res)
  77. this.lat = Number(res.latitude.toFixed(6))
  78. this.lng = Number(res.longitude.toFixed(6))
  79. // this.lat = 26.6643
  80. // this.lng = 106.625
  81. resolve(true)
  82. },
  83. fail: (err) => {
  84. uni.hideLoading()
  85. reject(new Error('获取位置失败'))
  86. console.log('H5获取位置失败', err)
  87. const errMsg = err.errMsg || ''
  88. if (errMsg.includes('auth deny') || errMsg.includes('authorize')) {
  89. useGlobalToast().show('请授权位置权限')
  90. }
  91. else if (errMsg.includes('timeout')) {
  92. useGlobalToast().show('获取位置超时,请重试')
  93. }
  94. else {
  95. useGlobalToast().show(`获取定位失败:${errMsg}`)
  96. }
  97. },
  98. })
  99. })
  100. },
  101. // 小程序环境获取位置
  102. getLocationMP() {
  103. uni.showLoading({ mask: true })
  104. // 1. 检查当前授权状态
  105. uni.getSetting({
  106. success: (res) => {
  107. const locationAuth = res.authSetting['scope.userLocation']
  108. // 2. 已授权 - 直接获取位置
  109. if (locationAuth) {
  110. this.fetchActualLocation()
  111. uni.hideLoading()
  112. }
  113. // 3. 未授权 - 尝试请求授权
  114. else {
  115. uni.authorize({
  116. scope: 'scope.userLocation',
  117. success: () => this.fetchActualLocation(),
  118. fail: () => this.showAuthGuide(), // 用户拒绝,显示引导
  119. complete: () => uni.hideLoading(),
  120. })
  121. }
  122. },
  123. })
  124. },
  125. // 实际获取位置的方法(小程序)
  126. fetchActualLocation() {
  127. uni.getLocation({
  128. type: 'wgs84',
  129. isHighAccuracy: true,
  130. altitude: true,
  131. success: (res) => {
  132. console.log('位置获取成功', res)
  133. this.lat = res.latitude
  134. this.lng = res.longitude
  135. },
  136. fail: (err) => {
  137. console.log(err, '获取位置失败')
  138. if (err.errMsg === 'getLocation:fail system permission denied') {
  139. useGlobalToast().show('手机定位权限未打开,请手动在设置里面打开定位')
  140. }
  141. else {
  142. useGlobalToast().show(`获取定位失败:${err.errMsg}`)
  143. }
  144. },
  145. })
  146. },
  147. // 显示授权引导(小程序)
  148. showAuthGuide() {
  149. uni.showModal({
  150. title: '需要位置权限',
  151. content: '请开启位置授权以使用完整功能',
  152. confirmText: '去设置',
  153. success: (res) => {
  154. if (res.confirm) {
  155. // 4. 用户点击确认后打开设置页
  156. uni.openSetting({
  157. success: (settingRes) => {
  158. // 5. 检查用户是否在设置页中开启了授权
  159. if (settingRes.authSetting['scope.userLocation']) {
  160. this.fetchActualLocation()
  161. }
  162. else {
  163. console.log('用户仍未授权')
  164. }
  165. },
  166. })
  167. }
  168. },
  169. })
  170. },
  171. /**
  172. *
  173. * @param _item 兑换的券
  174. */
  175. async handleExchange(_item: any) {
  176. uni.showLoading({ mask: true })
  177. try {
  178. const res = await Apis.app.get_smqjh_system_app_api_coupon_exchangepoints({ params: { couponId: _item.id } })
  179. uni.hideLoading()
  180. // 兑换成功,跳转成功页
  181. router.push({
  182. name: 'exchangeSuccess',
  183. params: {
  184. couponId: res.data?.id || _item.id,
  185. batchNo: res.data?.batchId || '',
  186. expireDays: res.data?.expirationDate || _item.expirationDate,
  187. discountMoney: res.data?.discountMoney || _item.discountMoney,
  188. amountMoney: res.data?.amountMoney || _item.amountMoney,
  189. },
  190. })
  191. }
  192. catch (error: any) {
  193. console.log(error)
  194. uni.hideLoading()
  195. // 兑换失败,跳转失败页
  196. router.push({
  197. name: 'exchangeFail',
  198. params: {
  199. failReason: error?.message || '兑换失败,请稍后重试',
  200. },
  201. })
  202. }
  203. },
  204. /**
  205. * 取消订单
  206. * @param orderId 订单ID
  207. */
  208. async handleCommonCancelOrder(orderId: string) {
  209. return new Promise((resolve, reject) => {
  210. useGlobalMessage().confirm({
  211. title: '提示',
  212. msg: '确定要取消该订单吗?',
  213. zIndex: 9999,
  214. success: async () => {
  215. uni.showLoading({ mask: true })
  216. try {
  217. await Apis.general.post_smqjh_oms_api_v1_oil_order_cancel({ params: { orderId } })
  218. useGlobalToast().show('取消成功')
  219. resolve(true)
  220. }
  221. catch {
  222. useGlobalToast().show('取消失败')
  223. reject(new Error('取消失败'))
  224. }
  225. finally {
  226. uni.hideLoading()
  227. }
  228. },
  229. })
  230. })
  231. },
  232. /**
  233. * 拉起小橘支付
  234. * @param path
  235. */
  236. handleCommonPath(path: string) {
  237. uni.showLoading({ mask: true })
  238. const url = import.meta.env.VITE_REDIRECT_URL
  239. window.location.href = `${path}&redirectUrl=${url}`
  240. uni.hideLoading()
  241. },
  242. /**
  243. * 跳转小程序
  244. * @param orderNumber
  245. */
  246. handleCommonMiniProgram(orderNumber: string) {
  247. const query = {
  248. orderNo: orderNumber,
  249. }
  250. const queryString = Object.entries(query)
  251. .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
  252. .join('&')
  253. this.handleCommonWx('subPack-refueling/orderDetaile/index', queryString)
  254. },
  255. handleCommonWx(path: string, queryString: string) {
  256. window.location.href = `weixin://dl/business/?appid=wx43b5b906cc30ed0b&path=${path}&query=${queryString}&env_version=release`
  257. },
  258. async handleCommonGoXiaoJuPay(orderNumber: string) {
  259. try {
  260. const res = await Apis.general.post_smqjh_oms_api_v1_oil_order_findbypayurl({ params: { orderNumber } })
  261. this.handleCommonPath(res.data as string)
  262. }
  263. catch (error) {
  264. console.log(error)
  265. useGlobalToast().show('获取支付信息失败')
  266. }
  267. },
  268. },
  269. })