common.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import config from '@/config'
  2. import { getToken } from '@/utils/auth'
  3. import errorCode from '@/utils/errorCode'
  4. let timeout = 10000
  5. const baseUrl = config.baseUrl
  6. /**
  7. * 显示消息提示框
  8. * @param content 提示的标题
  9. */
  10. export function toast(content) {
  11. uni.showToast({
  12. icon: 'none',
  13. title: content
  14. })
  15. }
  16. /**
  17. * 显示模态弹窗
  18. * @param content 提示的标题
  19. */
  20. export function showConfirm(content) {
  21. return new Promise((resolve, reject) => {
  22. uni.showModal({
  23. title: '提示',
  24. content: content,
  25. cancelText: '取消',
  26. confirmText: '确定',
  27. success: function(res) {
  28. resolve(res)
  29. }
  30. })
  31. })
  32. }
  33. // 字典值匹配
  34. export function selectDictValue(datas, value) {
  35. var actions = [];
  36. Object.keys(datas).some((key) => {
  37. if (datas[key].dictValue == ('' + value)) {
  38. actions.push(datas[key].dictLabel);
  39. return true;
  40. }
  41. })
  42. return actions.join('');
  43. }
  44. // export function selectDictLabel(datas, value) {
  45. // var actions = [];
  46. // Object.keys(datas).some((key) => {
  47. // if (datas[key].dictLabel == ('' + value)) {
  48. // actions.push(datas[key].dictValue);
  49. // return true;
  50. // }
  51. // })
  52. // return actions.join('');
  53. // }
  54. export function selectValueKey(datas, value) {
  55. var actions = [];
  56. var idx=0;
  57. Object.keys(datas).some((key) => {
  58. if (datas[key].dictValue == ('' + value)) {
  59. idx=key;
  60. actions.push(datas[key].dictLabel);
  61. return true;
  62. }
  63. })
  64. var newObj={
  65. actions:actions.join(''),
  66. key:idx
  67. }
  68. return newObj
  69. }
  70. // export function selectValue(datas, value) {
  71. // var actions = [];
  72. // var idx=0;
  73. // Object.keys(datas).some((key) => {
  74. // if (datas[key].value == ('' + value)) {
  75. // actions.push(datas[key].label);
  76. // return true;
  77. // }
  78. // })
  79. // return actions.join('')
  80. // }
  81. // export function selectValuetext(datas, value) {
  82. // var actions = [];
  83. // var idx=0;
  84. // Object.keys(datas).some((key) => {
  85. // if (datas[key].value == ('' + value)) {
  86. // actions.push(datas[key].text);
  87. // return true;
  88. // }
  89. // })
  90. // return actions.join('')
  91. // }
  92. export function geocodeAddress(address, key) {
  93. return new Promise((resolve, reject) => {
  94. // H5 和 App 平台使用高德地图 JavaScript API
  95. if (uni.getSystemInfoSync().platform === 'h5' || uni.getSystemInfoSync().platform === 'android') {
  96. const url = `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(address)}&key=${key}`;
  97. uni.request({
  98. url,
  99. success: (res) => {
  100. if (res.data.status === '1' && res.data.geocodes.length > 0) {
  101. const location = res.data.geocodes[0].location; // 返回格式:经度,纬度
  102. const [longitude, latitude] = location.split(',');
  103. resolve({ latitude: parseFloat(latitude), longitude: parseFloat(longitude) });
  104. } else {
  105. reject(new Error('未找到地址对应的经纬度'));
  106. }
  107. },
  108. fail: (err) => {
  109. reject(err);
  110. },
  111. });
  112. }
  113. // 小程序平台使用高德地图小程序 SDK
  114. else if (uni.getSystemInfoSync().platform === 'mp-weixin') {
  115. wx.request({
  116. url: `https://restapi.amap.com/v3/geocode/geo?address=${encodeURIComponent(address)}&key=${key}`,
  117. success: (res) => {
  118. if (res.data.status === '1' && res.data.geocodes.length > 0) {
  119. const location = res.data.geocodes[0].location; // 返回格式:经度,纬度
  120. const [longitude, latitude] = location.split(',');
  121. resolve({ latitude: parseFloat(latitude), longitude: parseFloat(longitude) });
  122. } else {
  123. reject(new Error('未找到地址对应的经纬度'));
  124. }
  125. },
  126. fail: (err) => {
  127. reject(err);
  128. },
  129. });
  130. } else {
  131. reject(new Error('不支持的平台'));
  132. }
  133. });
  134. }
  135. /**
  136. * 参数处理
  137. * @param params 参数
  138. */
  139. export function tansParams(params) {
  140. let result = ''
  141. for (const propName of Object.keys(params)) {
  142. const value = params[propName]
  143. var part = encodeURIComponent(propName) + "="
  144. if (value !== null && value !== "" && typeof (value) !== "undefined") {
  145. if (typeof value === 'object') {
  146. for (const key of Object.keys(value)) {
  147. if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
  148. let params = propName + '[' + key + ']'
  149. var subPart = encodeURIComponent(params) + "="
  150. result += subPart + encodeURIComponent(value[key]) + "&"
  151. }
  152. }
  153. } else {
  154. result += part + encodeURIComponent(value) + "&"
  155. }
  156. }
  157. }
  158. return result
  159. }
  160. //上传图片(本地地址识别一张)
  161. export function uploadIdentify(api, filePaths, successUp, failUp, i, length, files, callback) {
  162. const isToken = (config.headers || {}).isToken === false
  163. config.header = config.header || {}
  164. if (getToken() && !isToken) {
  165. config.header['Authorization'] = 'Bearer ' + getToken()
  166. }
  167. // get请求映射params参数
  168. if (config.params) {
  169. let url = config.url + '?' + tansParams(config.params)
  170. url = url.slice(0, -1)
  171. config.url = url
  172. }
  173. uni.showLoading({
  174. title: '上传中'
  175. })
  176. var failfile = [];
  177. uni.uploadFile({
  178. timeout: config.timeout || timeout,
  179. url: baseUrl + api, //仅为示例,非真实的接口地址
  180. filePath: filePaths[i],
  181. name: 'file',
  182. header: config.header,
  183. formData: config.formData,
  184. success: function(resp) {
  185. uni.hideLoading();
  186. let result = JSON.parse(resp.data)
  187. const code = result.code || 200
  188. const msg = errorCode[code] || result.msg || errorCode['default']
  189. // console.log(result.fileName,8)
  190. if (result.code == 200) {
  191. successUp++;
  192. files[i] = result;
  193. } else if(result.code==401) {
  194. showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  195. if (res.confirm) {
  196. store.dispatch('LogOut').then(res => {
  197. uni.reLaunch({ url: '/pages/login/login' })
  198. })
  199. }
  200. })
  201. callback('无效的会话,或者会话已过期,请重新登录。');
  202. }else{
  203. failfile = failfile.concat(filePaths[i])
  204. failUp++;
  205. }
  206. },
  207. fail: function(res) {
  208. uni.hideLoading();
  209. failfile = failfile.concat(filePaths[i])
  210. failUp++;
  211. },
  212. complete: function(rsp) {
  213. // console.log(rsp, filePaths[i])
  214. uni.hideLoading();
  215. i++;
  216. if (i == length) {
  217. uni.showToast({
  218. title: '上传成功',
  219. icon: 'none',
  220. duration: 2000
  221. });
  222. callback(files);
  223. } else { //递归调用upload函数
  224. uploadIdentify(api, filePaths, successUp, failUp, i, length, files, callback);
  225. }
  226. }
  227. });
  228. }
  229. //上传图片
  230. export function uploadmore(api, filePaths, successUp, failUp, i, length, files, callback) {
  231. const isToken = (config.headers || {}).isToken === false
  232. config.header = config.header || {}
  233. if (getToken() && !isToken) {
  234. config.header['Authorization'] = 'Bearer ' + getToken()
  235. }
  236. // get请求映射params参数
  237. if (config.params) {
  238. let url = config.url + '?' + tansParams(config.params)
  239. url = url.slice(0, -1)
  240. config.url = url
  241. }
  242. uni.showLoading({
  243. title: '上传中'
  244. })
  245. var failfile = [];
  246. uni.uploadFile({
  247. timeout: config.timeout || timeout,
  248. url: baseUrl + api, //仅为示例,非真实的接口地址
  249. filePath: filePaths[i],
  250. name: 'file',
  251. header: config.header,
  252. formData: config.formData,
  253. success: function(resp) {
  254. uni.hideLoading();
  255. let result = JSON.parse(resp.data)
  256. const code = result.code || 200
  257. const msg = errorCode[code] || result.msg || errorCode['default']
  258. // console.log(result.fileName,8)
  259. if (result.code == 200) {
  260. successUp++;
  261. files[i] = result.fileName;
  262. } else if(result.code==401) {
  263. showConfirm("登录状态已过期,您可以继续留在该页面,或者重新登录?").then(res => {
  264. if (res.confirm) {
  265. store.dispatch('LogOut').then(res => {
  266. uni.reLaunch({ url: '/pages/login/login' })
  267. })
  268. }
  269. })
  270. callback('无效的会话,或者会话已过期,请重新登录。');
  271. }else{
  272. failfile = failfile.concat(filePaths[i])
  273. failUp++;
  274. }
  275. },
  276. fail: function(res) {
  277. uni.hideLoading();
  278. failfile = failfile.concat(filePaths[i])
  279. failUp++;
  280. },
  281. complete: function(rsp) {
  282. uni.hideLoading();
  283. i++;
  284. if (i == length) {
  285. uni.showToast({
  286. title: '上传成功',
  287. icon: 'none',
  288. duration: 2000
  289. });
  290. callback(files);
  291. } else { //递归调用upload函数
  292. uploadmore(api, filePaths, successUp, failUp, i, length, files, callback);
  293. }
  294. }
  295. });
  296. }