baoxiudj.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. const app = getApp();
  2. Page({
  3. data: {
  4. address: app.globalData.currentAccountInfo.address,
  5. contact: '',
  6. phone: '',
  7. repairType: '',
  8. repairTypeValue: '',
  9. repairTypeMap: [
  10. {name: '换表', value: '1'},
  11. {name: '换前阀', value: '2'},
  12. {name: '换后阀', value: '3'},
  13. {name: '换前后阀', value: '4'},
  14. {name: '其他', value: '5'}
  15. ],
  16. description: '',
  17. imageList: [],
  18. showNotification: true,
  19. countDown: 3,
  20. isFormValid: false,
  21. isPreviewMode: false,
  22. replyTime: '',
  23. replyContent: '',
  24. id: '',
  25. mode: '',
  26. isReplied: false,
  27. formSubmitted: false,
  28. isSubmitting: false, // 新增保存标志位
  29. lastSubmitTime: 0, // 上次提交时间(通过防抖(Debounce)技术,限制用户在一定时间内只能提交一次。)
  30. },
  31. onLoad: function (options) {
  32. const isReplied = options.isReplied === 'true';
  33. // 更新地址信息,确保是最新的户号地址
  34. this.setData({
  35. address: app.globalData.currentAccountInfo.address
  36. });
  37. if (options.mode === 'preview') {
  38. this.setData({
  39. isPreviewMode: true,
  40. showNotification: false,
  41. id: options.id,
  42. mode: options.mode,
  43. isReplied: isReplied
  44. });
  45. this.loadPreviewData(options.id);
  46. } else {
  47. this.startCountDown();
  48. this.setData({
  49. id: options.id || '',
  50. mode: options.mode || '',
  51. isReplied: isReplied
  52. });
  53. }
  54. },
  55. startCountDown: function () {
  56. let that = this;
  57. let timer = setInterval(function () {
  58. if (that.data.countDown > 0) {
  59. that.setData({
  60. countDown: that.data.countDown - 1
  61. });
  62. } else {
  63. clearInterval(timer);
  64. }
  65. }, 1000);
  66. },
  67. closeNotification: function () {
  68. if (this.data.countDown <= 0) {
  69. this.setData({
  70. showNotification: false
  71. });
  72. }
  73. },
  74. goBack: function () {
  75. wx.navigateBack();
  76. },
  77. inputContact: function (e) {
  78. this.setData({
  79. contact: e.detail.value
  80. });
  81. this.checkFormValidity();
  82. },
  83. inputPhone: function (e) {
  84. const value = e.detail.value;
  85. const phoneNumber = value.replace(/\D/g, '');
  86. this.setData({
  87. phone: phoneNumber
  88. });
  89. this.checkFormValidity();
  90. },
  91. validatePhone: function (phone) {
  92. const phoneReg = /^1[3-9]\d{9}$/;
  93. return phoneReg.test(phone);
  94. },
  95. showRepairTypeSelector: function () {
  96. let that = this;
  97. // 只显示名称列表
  98. const typeNames = this.data.repairTypeMap.map(item => item.name);
  99. wx.showActionSheet({
  100. itemList: typeNames,
  101. success: function (res) {
  102. const selectedType = that.data.repairTypeMap[res.tapIndex];
  103. that.setData({
  104. repairType: selectedType.name,
  105. repairTypeValue: selectedType.value
  106. });
  107. that.checkFormValidity();
  108. }
  109. });
  110. },
  111. inputDescription: function (e) {
  112. this.setData({
  113. description: e.detail.value
  114. });
  115. this.checkFormValidity();
  116. },
  117. chooseImage: function () {
  118. let that = this;
  119. if (that.data.imageList.length >= 10) {
  120. wx.showToast({
  121. title: '最多只能上传10张图片',
  122. icon: 'none'
  123. });
  124. return;
  125. }
  126. wx.chooseMedia({
  127. count: 10 - that.data.imageList.length,
  128. mediaType: ['image'],
  129. sourceType: ['album', 'camera'],
  130. sizeType: ['compressed'],
  131. success: function (res) {
  132. let tempFiles = res.tempFiles;
  133. let validFiles = [];
  134. for (let i = 0; i < tempFiles.length; i++) {
  135. const file = tempFiles[i];
  136. if (file.size <= 10 * 1024 * 1024) {
  137. // 为每个文件添加唯一标识
  138. validFiles.push({
  139. ...file,
  140. uid: `${Date.now()}_${Math.random().toString(36).substr(2, 9)}_${i}`
  141. });
  142. } else {
  143. wx.showToast({
  144. title: '图片大小不能超过10M',
  145. icon: 'none'
  146. });
  147. }
  148. }
  149. if (validFiles.length > 0) {
  150. wx.showLoading({
  151. title: '图片处理中...',
  152. mask: true
  153. });
  154. // 创建副本保存待处理的图片列表
  155. const filesToProcess = [...validFiles];
  156. // 使用Map结构存储结果,确保不会丢失
  157. let processedFilesMap = new Map();
  158. let processCount = 0;
  159. // 获取当前已有图片的路径列表,用于去重检查
  160. const existingPaths = that.data.imageList.map(img =>
  161. typeof img === 'string' ? img : img.tempFilePath
  162. );
  163. // 处理每个图片
  164. filesToProcess.forEach((file) => {
  165. // 检查是否已经存在相同路径的图片
  166. if (existingPaths.includes(file.tempFilePath)) {
  167. console.log("跳过重复图片:", file.tempFilePath);
  168. processCount++;
  169. // 检查是否所有图片都已处理完成
  170. if (processCount === filesToProcess.length) {
  171. finishProcessing();
  172. }
  173. return;
  174. }
  175. that.compressImage(file.tempFilePath).then(compressedPath => {
  176. processCount++;
  177. // 如果返回路径与原路径不同,则认为已成功压缩
  178. if (compressedPath !== file.tempFilePath) {
  179. // 使用Map结构通过uid存储处理结果,保证一一对应
  180. processedFilesMap.set(file.uid, {
  181. tempFilePath: compressedPath,
  182. size: file.size, // 这里使用原始大小,实际上压缩后大小会变小
  183. uid: file.uid,
  184. originalPath: file.tempFilePath // 保存原始路径以便追踪
  185. });
  186. } else {
  187. // 如果路径没变,可能是压缩失败或无需压缩的小图片
  188. processedFilesMap.set(file.uid, {
  189. tempFilePath: compressedPath,
  190. size: file.size,
  191. uid: file.uid
  192. });
  193. }
  194. // 检查是否所有图片都已处理完成
  195. if (processCount === filesToProcess.length) {
  196. finishProcessing();
  197. }
  198. }).catch(err => {
  199. console.error('图片压缩失败:', err);
  200. processCount++;
  201. // 即使压缩失败,也将原图添加到结果中
  202. processedFilesMap.set(file.uid, {
  203. tempFilePath: file.tempFilePath,
  204. size: file.size,
  205. uid: file.uid
  206. });
  207. if (processCount === filesToProcess.length) {
  208. finishProcessing();
  209. }
  210. });
  211. });
  212. // 统一处理添加图片到列表的逻辑
  213. function finishProcessing() {
  214. // 将Map转换为数组,保持原有顺序
  215. let processedFiles = filesToProcess.map(file => processedFilesMap.get(file.uid)).filter(Boolean);
  216. // 再次检查去重,防止压缩后的图片路径与已有图片重复
  217. let currentImagePaths = that.data.imageList.map(img =>
  218. typeof img === 'string' ? img : img.tempFilePath
  219. );
  220. let newFiles = processedFiles.filter(file =>
  221. !currentImagePaths.includes(file.tempFilePath)
  222. );
  223. console.log(`添加 ${newFiles.length} 张新图片,跳过 ${processedFiles.length - newFiles.length} 张重复图片`);
  224. if (newFiles.length > 0) {
  225. let newImageList = that.data.imageList.concat(newFiles);
  226. that.setData({
  227. imageList: newImageList
  228. });
  229. }
  230. wx.hideLoading();
  231. }
  232. }
  233. }
  234. });
  235. },
  236. // 修改图片压缩函数,确保生成的路径在后续处理中保持一致
  237. compressImage: function(imagePath) {
  238. return new Promise((resolve, reject) => {
  239. // 对于已经压缩过的图片(通常路径中会包含"compressed"),直接返回
  240. if (imagePath.indexOf("compressed") > -1) {
  241. console.log("图片已压缩,直接使用:", imagePath);
  242. resolve(imagePath);
  243. return;
  244. }
  245. // 获取图片信息
  246. wx.getImageInfo({
  247. src: imagePath,
  248. success: (res) => {
  249. // 先获取原图大小,单位KB
  250. wx.getFileInfo({
  251. filePath: imagePath,
  252. success: (fileInfo) => {
  253. const originalSize = fileInfo.size / 1024; // 原始大小,单位KB
  254. // 如果原图已经很小(小于300KB),可以直接使用
  255. if (originalSize < 300) {
  256. console.log("图片较小,无需压缩:", originalSize, "KB");
  257. resolve(imagePath);
  258. return;
  259. }
  260. // 根据原图大小确定压缩质量
  261. let targetQuality = 0.8; // 默认压缩质量
  262. if (originalSize <= 500) {
  263. // 如果原图已经小于500KB,保持较高质量
  264. targetQuality = 0.9;
  265. } else if (originalSize <= 1024) {
  266. // 1MB以下,适当压缩
  267. targetQuality = 0.7;
  268. } else if (originalSize <= 2048) {
  269. // 2MB以下,中等压缩
  270. targetQuality = 0.5;
  271. } else if (originalSize <= 5120) {
  272. // 5MB以下,较大压缩
  273. targetQuality = 0.3;
  274. } else {
  275. // 超过5MB,大幅压缩
  276. targetQuality = 0.2;
  277. }
  278. wx.createSelectorQuery()
  279. .select('#compressCanvas')
  280. .fields({ node: true, size: true })
  281. .exec((canvasRes) => {
  282. if (!canvasRes || !canvasRes[0] || !canvasRes[0].node) {
  283. // 如果找不到canvas节点,则返回原图
  284. console.log("找不到canvas节点,使用原图");
  285. resolve(imagePath);
  286. return;
  287. }
  288. const canvas = canvasRes[0].node;
  289. const ctx = canvas.getContext('2d');
  290. const image = canvas.createImage();
  291. image.onload = () => {
  292. // 计算要缩放的尺寸,保持宽高比
  293. let ratio = 1;
  294. // 根据原图大小调整尺寸
  295. if (originalSize > 5120) { // 5MB以上
  296. ratio = Math.min(1, 1200 / res.width, 1200 / res.height);
  297. } else if (originalSize > 2048) { // 2MB以上
  298. ratio = Math.min(1, 1500 / res.width, 1500 / res.height);
  299. } else if (originalSize > 1024) { // 1MB以上
  300. ratio = Math.min(1, 1800 / res.width, 1800 / res.height);
  301. } else {
  302. ratio = Math.min(1, 2000 / res.width, 2000 / res.height);
  303. }
  304. const targetWidth = Math.round(res.width * ratio);
  305. const targetHeight = Math.round(res.height * ratio);
  306. // 设置canvas尺寸
  307. canvas.width = targetWidth;
  308. canvas.height = targetHeight;
  309. // 清除画布
  310. ctx.clearRect(0, 0, targetWidth, targetHeight);
  311. // 绘制图片
  312. ctx.drawImage(image, 0, 0, targetWidth, targetHeight);
  313. // 生成带有标记的压缩后路径名称
  314. const compressedName = `compressed_${Date.now()}_${Math.random().toString(36).substr(2, 5)}`;
  315. // 压缩参数
  316. const compressOptions = {
  317. canvas: canvas,
  318. width: targetWidth,
  319. height: targetHeight,
  320. destWidth: targetWidth,
  321. destHeight: targetHeight,
  322. fileType: 'jpg',
  323. quality: targetQuality,
  324. // 添加压缩标记
  325. filePath: `${wx.env.USER_DATA_PATH}/${compressedName}.jpg`
  326. };
  327. // 执行一次压缩
  328. wx.canvasToTempFilePath({
  329. ...compressOptions,
  330. success: (result) => {
  331. console.log("压缩成功,新路径:", result.tempFilePath);
  332. resolve(result.tempFilePath);
  333. },
  334. fail: (error) => {
  335. console.error('Canvas转图片失败:', error);
  336. // 如果转换失败则返回原图
  337. resolve(imagePath);
  338. }
  339. });
  340. };
  341. image.onerror = () => {
  342. console.error('图片加载失败');
  343. resolve(imagePath);
  344. };
  345. image.src = imagePath;
  346. });
  347. },
  348. fail: (error) => {
  349. console.error('获取原始图片信息失败:', error);
  350. resolve(imagePath);
  351. }
  352. });
  353. },
  354. fail: (error) => {
  355. console.error('获取图片信息失败:', error);
  356. resolve(imagePath);
  357. }
  358. });
  359. });
  360. },
  361. previewImage: function (e) {
  362. let index = e.currentTarget.dataset.index;
  363. let urls = this.data.imageList.map(item => {
  364. // 处理不同格式的图片对象
  365. return typeof item === 'string' ? item : item.tempFilePath;
  366. });
  367. wx.previewImage({
  368. current: urls[index],
  369. urls: urls
  370. });
  371. },
  372. deleteImage: function (e) {
  373. let index = e.currentTarget.dataset.index;
  374. let imageList = this.data.imageList;
  375. imageList.splice(index, 1);
  376. this.setData({
  377. imageList: imageList
  378. });
  379. },
  380. checkFormValidity: function () {
  381. const {
  382. contact,
  383. phone,
  384. address,
  385. repairType,
  386. repairTypeValue,
  387. description
  388. } = this.data;
  389. const hasAddress = address && address.trim() !== '';
  390. const hasContact = contact && contact.trim() !== '';
  391. const hasPhone = phone && phone.trim() !== '';
  392. const hasValidPhone = this.validatePhone(phone);
  393. const hasRepairType = repairType && repairType.trim() !== '';
  394. const hasRepairTypeValue = repairTypeValue && repairTypeValue.trim() !== '';
  395. const hasDescription = description && description.trim() !== '';
  396. const isValid = hasAddress && hasContact && hasPhone && hasValidPhone && hasRepairType && hasRepairTypeValue && hasDescription;
  397. this.setData({
  398. isFormValid: isValid
  399. });
  400. return isValid;
  401. },
  402. onInputChange: function (e) {
  403. const {
  404. field
  405. } = e.currentTarget.dataset;
  406. const {
  407. value
  408. } = e.detail;
  409. this.setData({
  410. [field]: value
  411. });
  412. this.checkFormValidity();
  413. },
  414. bindPickerChange: function (e) {
  415. this.checkFormValidity();
  416. },
  417. submitRepair: function () {
  418. if (!this.checkFormValidity()) {
  419. wx.showToast({
  420. title: '请填写完整信息',
  421. icon: 'none'
  422. });
  423. return;
  424. }
  425. if (!this.validatePhone(this.data.phone)) {
  426. wx.showToast({
  427. title: '请输入正确的手机号',
  428. icon: 'none'
  429. });
  430. return;
  431. }
  432. const submitData = {
  433. address: this.data.address,
  434. contact: this.data.contact,
  435. phone: this.data.phone,
  436. repairType: this.data.repairType,
  437. repairTypeValue: this.data.repairTypeValue,
  438. description: this.data.description,
  439. images: this.data.imageList
  440. };
  441. console.log('提交的数据:', submitData);
  442. wx.showLoading({
  443. title: '提交中...',
  444. });
  445. setTimeout(() => {
  446. wx.hideLoading();
  447. wx.showToast({
  448. icon: 'success',
  449. duration: 2000,
  450. success: function () {
  451. setTimeout(() => {
  452. wx.navigateTo({
  453. url: '/pages/baoxiuSuccess/baoxiuSuccess',
  454. });
  455. }, 2000);
  456. }
  457. });
  458. }, 1500);
  459. },
  460. loadPreviewData: function (id) {
  461. wx.showLoading({
  462. title: '加载中...',
  463. });
  464. // 从上一个页面获取数据
  465. const pages = getCurrentPages();
  466. const prevPage = pages[pages.length - 2]; // 获取上一个页面
  467. if (prevPage && prevPage.data && prevPage.data.noticeList) {
  468. // 根据id查找对应的报修项
  469. const item = prevPage.data.noticeList.find(item => item.id == id);
  470. debugger
  471. if (item) {
  472. // 找到对应的报修类型名称
  473. let repairTypeName = '';
  474. const repairTypeValue = item.repairtype || '';
  475. const repairTypeItem = this.data.repairTypeMap.find(type => type.name === repairTypeValue);
  476. if (repairTypeItem) {
  477. repairTypeName = repairTypeItem.name;
  478. }
  479. // 格式化时间
  480. const formatTime = (timeString) => {
  481. if (!timeString) return ''; // 如果时间为空,返回空字符串
  482. const date = new Date(timeString);
  483. const year = date.getFullYear();
  484. const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份补零
  485. const day = String(date.getDate()).padStart(2, '0'); // 日期补零
  486. return `${year}-${month}-${day}`;
  487. };
  488. this.setData({
  489. address: item.address || '',
  490. contact: item.contact || '',
  491. phone: item.contactnumber || '',
  492. repairType: repairTypeName,
  493. repairTypeValue: repairTypeValue,
  494. description: item.faultdescription || '',
  495. imageList: item.attachments || [],
  496. replyTime: item.isReplied ? formatTime(item.repairtime) : '',
  497. replyContent: item.isReplied ? item.remark : ''
  498. });
  499. }
  500. }
  501. wx.hideLoading();
  502. },
  503. submitForm: function () {
  504. // 如果正在提交中,直接返回
  505. if (this.data.isSubmitting) {
  506. return;
  507. }
  508. if (!this.data.address || this.data.address.trim() === '') {
  509. wx.showToast({
  510. title: '请填写地址',
  511. icon: 'none'
  512. });
  513. this.setData({
  514. isSubmitting: false
  515. });
  516. return;
  517. }
  518. if (!this.data.contact || this.data.contact.trim() === '') {
  519. wx.showToast({
  520. title: '请填写联系人',
  521. icon: 'none'
  522. });
  523. this.setData({
  524. isSubmitting: false
  525. });
  526. return;
  527. }
  528. if (!this.data.phone || this.data.phone.trim() === '') {
  529. wx.showToast({
  530. title: '请填写联系电话',
  531. icon: 'none'
  532. });
  533. this.setData({
  534. isSubmitting: false
  535. });
  536. return;
  537. }
  538. if (!this.validatePhone(this.data.phone)) {
  539. wx.showToast({
  540. title: '请输入正确的手机号',
  541. icon: 'none'
  542. });
  543. this.setData({
  544. isSubmitting: false
  545. });
  546. return;
  547. }
  548. if (!this.data.repairType || this.data.repairType.trim() === '') {
  549. wx.showToast({
  550. title: '请选择报修类型',
  551. icon: 'none'
  552. });
  553. this.setData({
  554. isSubmitting: false
  555. });
  556. return;
  557. }
  558. if (!this.data.repairTypeValue || this.data.repairTypeValue.trim() === '') {
  559. wx.showToast({
  560. title: '请选择报修类型',
  561. icon: 'none'
  562. });
  563. this.setData({
  564. isSubmitting: false
  565. });
  566. return;
  567. }
  568. if (!this.data.description || this.data.description.trim() === '') {
  569. wx.showToast({
  570. title: '请填写故障说明',
  571. icon: 'none'
  572. });
  573. this.setData({
  574. isSubmitting: false
  575. });
  576. return;
  577. }
  578. const now = Date.now();
  579. const lastSubmitTime = this.data.lastSubmitTime;
  580. // 如果距离上次提交时间小于 2 秒,直接返回
  581. if (now - lastSubmitTime < 2000) {
  582. // wx.showToast({
  583. // title: '请勿重复提交',
  584. // icon: 'none',
  585. // });
  586. return;
  587. }
  588. // 更新上次提交时间
  589. this.setData({
  590. lastSubmitTime: now,
  591. });
  592. const fileManager = wx.getFileSystemManager();
  593. this.data.imageList.map(imgInfo => {
  594. const base64 = fileManager.readFileSync(imgInfo.tempFilePath, 'base64');
  595. imgInfo.base64 = base64;
  596. return imgInfo;
  597. })
  598. const submitData = {
  599. address: this.data.address,
  600. contact: this.data.contact,
  601. phone: this.data.phone,
  602. repairType: this.data.repairTypeValue,
  603. description: this.data.description,
  604. images: this.data.imageList,
  605. userName: app.globalData.currentAccountInfo.username,
  606. userNum: app.globalData.currentAccountInfo.usernumber
  607. };
  608. // 设置正在提交中 防止重复点击提交按钮
  609. this.setData({
  610. isSubmitting: true,
  611. });
  612. console.log('提交的数据:', submitData);
  613. wx.showLoading({
  614. title: '提交中...',
  615. mask: true
  616. });
  617. const that = this;
  618. wx.request({
  619. url: app.globalData.interfaceUrls.repairRegistration,
  620. method: 'POST',
  621. header: {
  622. 'content-type': 'application/json', // 默认值
  623. 'token': app.globalData.userWxInfo.token,
  624. 'source': "wc",
  625. '!SAAS_LOGIN_TOKEN_!': app.globalData.currentAccountInfo.dsKey
  626. },
  627. data: submitData,
  628. success(res) {
  629. wx.hideLoading();
  630. if (res.data.code == '200') {
  631. wx.navigateTo({
  632. url: '/pages/baoxiuSuccess/baoxiuSuccess',
  633. });
  634. }
  635. that.setData({
  636. isSubmitting: false
  637. });
  638. },
  639. fail(error) {
  640. wx.hideLoading();
  641. wx.showToast({
  642. title: '登记失败,请稍后再试',
  643. icon: 'none'
  644. });
  645. that.setData({
  646. isSubmitting: false
  647. });
  648. },
  649. complete: () => {
  650. this.setData({
  651. isSubmitting: false, // 提交完成,重置标志位,可继续提交
  652. formSubmitted: true // 在提交成功后设置标记,返回将重置表单
  653. });
  654. },
  655. })
  656. },
  657. inputAddress: function (e) {
  658. this.setData({
  659. address: e.detail.value
  660. });
  661. },
  662. onShow: function () {
  663. // 检查是否是从成功页面返回
  664. if (this.data.formSubmitted) {
  665. // 重置表单数据
  666. this.resetForm();
  667. // 重置提交状态标记
  668. this.setData({
  669. formSubmitted: false
  670. });
  671. } else if (!this.data.isPreviewMode) {
  672. // 非预览模式下,更新地址信息
  673. this.setData({
  674. address: app.globalData.currentAccountInfo.address
  675. });
  676. }
  677. },
  678. // 添加重置表单的方法
  679. resetForm: function () {
  680. this.setData({
  681. contact: '',
  682. phone: '',
  683. repairType: '',
  684. repairTypeValue: '',
  685. description: '',
  686. imageList: []
  687. });
  688. },
  689. });