运维小程序
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

index.js 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  1. // pages/privacy/index.js
  2. import * as echarts from '../../ec-canvas/echarts';
  3. // import * as liquidFill from '../../ec-canvas/echarts-liquidfill.min';
  4. const api = require('../../api/index.js');
  5. const {timestamp,getYesterday} = require('../../utils/util.js');
  6. Page({
  7. /**
  8. * 页面的初始数据
  9. */
  10. data: {
  11. // 状态栏高度
  12. statusBarHeight: '',
  13. // 导航栏高度
  14. navBarHeight: '',
  15. // 导航栏和状态栏高度
  16. navStatusBarHeight: '',
  17. // 胶囊
  18. menu: '',
  19. ec: {
  20. lazyLoad: true
  21. },
  22. workorder: [],
  23. index: '',
  24. objectArray: [],
  25. powerdata: [],
  26. ech: {
  27. lazyLoad: true
  28. },
  29. ymdlist: [],
  30. chargeTotal: [],
  31. currentUnit: 'day', // 当前选中单位:day=日,month=月,year=年
  32. currentDate: '', // 动态格式显示日期
  33. actualDate: '', // 底层存储完整日期(YYYY-MM-DD)
  34. minDate: '2025-9-01', // 最小可选日期(可外部设置)
  35. maxDate: '', // 最大可选日期(可外部设置,默认当前日期)
  36. visible: false, // 日历选择器显隐
  37. // 禁用状态标识
  38. isMin: false, // 当前单位下是否已到最小边界
  39. isMax: false, // 当前单位下是否已到最大边界
  40. isUpperMin: false, // 上级单位下是否已到最小边界
  41. isUpperMax: false, // 上级单位下是否已到最大边界
  42. mintimeDate: '',
  43. maxtimeDate: '',
  44. currentTime: '',
  45. activeBarIndex: 0,
  46. activeBardata: [],
  47. choicedaydata: ['晟运电站', '南山电站', '晟运电站', '南山电站', '晟运电站', '南山电站']
  48. },
  49. /**
  50. * 生命周期函数--监听页面加载
  51. */
  52. onLoad(options) {
  53. // 日期字符串转时间戳
  54. const currentTimestamp = Date.now();
  55. // 初始化最大日期为当前日期,可通过options接收外部传入的日期范围
  56. const today = this.formatDate(new Date(), 'day');
  57. // 支持通过页面参数设置最小/最大日期(如从其他页面跳转时传入)
  58. const minDate = options.minDate || this.data.minDate;
  59. const maxDate = options.maxDate || today;
  60. // 确保实际日期在有效范围内
  61. let initialDate = today;
  62. if (new Date(initialDate) < new Date(minDate)) {
  63. initialDate = minDate;
  64. } else if (new Date(initialDate) > new Date(maxDate)) {
  65. initialDate = maxDate;
  66. }
  67. const mintimeDate = this.convertTimestamp(minDate);
  68. const maxtimeDate = this.convertTimestamp(maxDate);
  69. console.log(initialDate);
  70. this.setData({
  71. minDate,
  72. maxDate,
  73. mintimeDate,
  74. maxtimeDate,
  75. actualDate: initialDate,
  76. actualDate: initialDate,
  77. currentDate: this.formatDate(new Date(initialDate), 'day'),
  78. // currentDate: getYesterday(),
  79. currentTime: currentTimestamp,
  80. }, () => {
  81. this.updateDisableStatus();
  82. });
  83. if (wx.getStorageSync('powerstationId') == '') {
  84. wx.setStorage({
  85. key: 'powerstationId', // 存储的key值
  86. data: ''
  87. });
  88. }
  89. this.getShowScreenHeight()
  90. this.setData({
  91. statusBarHeight: wx.getStorageSync('statusBarHeight'),
  92. navBarHeight: wx.getStorageSync('navBarHeight'),
  93. navStatusBarHeight: wx.getStorageSync('navStatusBarHeight'),
  94. menu: wx.getStorageSync('menu')
  95. })
  96. this.ecline2 = this.selectComponent('#mychart_line2');
  97. this.ecline = this.selectComponent('#mychart_line');
  98. this.getpowestation()
  99. // 电站数据
  100. },
  101. getShowScreenHeight() {
  102. //系统信息
  103. const systemInfo = wx.getWindowInfo()
  104. //胶囊位置
  105. const capsuleInfo = wx.getMenuButtonBoundingClientRect()
  106. //计算导航栏高度
  107. let navHeight = systemInfo.statusBarHeight + capsuleInfo.height + (capsuleInfo.top - systemInfo.statusBarHeight) * 2
  108. //计算tabbar高度
  109. let tabHeight = systemInfo.safeArea.bottom - systemInfo.safeArea.height
  110. //计算可现实内容高度(中间区域)
  111. // let screenHeight = systemInfo.screenHeight-navHeight-tabHeight-30
  112. const menu = wx.getMenuButtonBoundingClientRect()
  113. wx.setStorageSync('menu', menu)
  114. // 手机系统状态栏高度
  115. wx.setStorageSync('statusBarHeight', tabHeight)
  116. // 导航栏高度
  117. wx.setStorageSync('navBarHeight', menu.height + (menu.top - systemInfo.statusBarHeight) * 2)
  118. // 状态栏加导航栏
  119. wx.setStorageSync('navStatusBarHeight', navHeight)
  120. },
  121. rolelocate(e) {
  122. wx.navigateTo({
  123. url: '/pages/statistics/index',
  124. })
  125. },
  126. // 工单统计
  127. getworkoder() {
  128. let data = {
  129. workorderType: ''
  130. }
  131. api.request(`/workoder/statistics`, 'POST', data)
  132. .then((res) => {
  133. console.log(res);
  134. this.setData({
  135. workorder: res.data
  136. })
  137. })
  138. .catch((err) => {
  139. console.error('请求失败:', err);
  140. // 在这里处理请求失败的情况
  141. });
  142. },
  143. gitpower() {
  144. let data = {
  145. day: this.data.currentDate
  146. }
  147. api.request(`/syspowerstation/selectpowerstattiondata`, 'POST', data)
  148. .then((res) => {
  149. console.log(res.data);
  150. this.setData({
  151. powerdata: res.data
  152. })
  153. if (this.data.index == 0 || this.data.index == '') {
  154. this.setData({
  155. activeBardata: res.data.sysPowerstationdatalist[this.data.activeBarIndex],
  156. ymdlist: res.data.sysPowerstationdatalist.map(item => item.powerstationName),
  157. chargeTotal: res.data.sysPowerstationdatalist.map(item => item.dailydischarge * 1),
  158. })
  159. console.log(this.data.ymdlist);
  160. console.log(this.data.chargeTotal);
  161. this.initChart_right();
  162. } else {
  163. this.initChartright()
  164. }
  165. })
  166. .catch((err) => {
  167. console.error('请求失败:', err);
  168. // 在这里处理请求失败的情况
  169. });
  170. },
  171. // 电容量
  172. initChartright: function () {
  173. let _this = this;
  174. // 初始化图表
  175. this.ecline.init((canvas, width, height, dpr) => {
  176. const chart = echarts.init(canvas, null, {
  177. width: width,
  178. height: height,
  179. devicePixelRatio: dpr
  180. });
  181. // 初始数据
  182. let initialData = {
  183. accumulatedchargetime: this.data.powerdata.dayfaultlossrate || 0,
  184. accumulateddischargetime: this.data.powerdata.monthlycumulativelossrate || 0
  185. };
  186. // 设置初始选项
  187. let option = _this.getChartOption(initialData);
  188. chart.setOption(option);
  189. // _this.chartInstance2 = chart;
  190. return chart;
  191. });
  192. },
  193. // 辅助函数,用于生成图表选项
  194. getChartOption: function (data) {
  195. let _this = this;
  196. return {
  197. backgroundColor: "#ffffff",
  198. legend: [{
  199. left: '0',
  200. bottom: 20,
  201. itemHeight: 8,
  202. itemWidth: 8,
  203. icon: "circle",
  204. textStyle: {
  205. color: '#999999', // 设置文字颜色为灰色
  206. fontSize: 10 // 设置字号为20px
  207. },
  208. formatter: function (name) {
  209. return name + ` ${(data.accumulatedchargetime * 1).toFixed(2)} %`;
  210. },
  211. rich: {
  212. a: {
  213. color: '#222222',
  214. fontSize: 12 // 设置字号为20px
  215. }
  216. },
  217. data: [{ name: '当日损失率' }]
  218. }, {
  219. left: '0',
  220. bottom: 0,
  221. itemHeight: 8,
  222. itemWidth: 8,
  223. icon: "circle",
  224. textStyle: {
  225. color: '#999999', // 设置文字颜色为灰色
  226. fontSize: 10 // 设置字号为20px
  227. },
  228. formatter: function (name) {
  229. return name + ` ${(data.accumulateddischargetime * 1).toFixed(2)} %`;
  230. },
  231. data: [{ name: '月累计损失率' }]
  232. }],
  233. tooltip: {
  234. trigger: 'item'
  235. },
  236. series: [{
  237. type: 'pie',
  238. radius: ['40%', '60%'],
  239. center: ['50%', '40%'],
  240. avoidLabelOverlap: false,
  241. label: {
  242. show: false,
  243. position: 'center'
  244. },
  245. emphasis: {
  246. label: {
  247. show: true,
  248. fontSize: 0,
  249. fontWeight: 'bold'
  250. }
  251. },
  252. labelLine: {
  253. show: false
  254. },
  255. data: [{
  256. value: (data.accumulatedchargetime * 1).toFixed(2),
  257. name: '当日损失率',
  258. itemStyle: { color: '#4DF096' }
  259. }, {
  260. value: (data.accumulateddischargetime * 1).toFixed(2),
  261. name: '月累计损失率',
  262. itemStyle: { color: '#3C9EFA' }
  263. }]
  264. }]
  265. };
  266. },
  267. onInformation() {
  268. wx.navigateTo({
  269. url: '/pages/Information/index',
  270. })
  271. },
  272. // 查询电站
  273. getpowestation() {
  274. api.request(`/syspowerstation/selectpowestation`, 'POST', {})
  275. .then((res) => {
  276. if (res.code == 200) {
  277. res.data.unshift({
  278. powerstationAddress: "",
  279. powerstationId: "",
  280. powerstationImg: "",
  281. powerstationName: "全部电站"
  282. })
  283. this.setData({
  284. objectArray: res.data
  285. })
  286. this.getaddredisredis()
  287. for (let index = 0; index < res.data.length; index++) {
  288. if (res.data[index].powerstationId == wx.getStorageSync('powerstationId')) {
  289. this.setData({
  290. index: index
  291. })
  292. return
  293. } else {
  294. this.setData({
  295. index: ''
  296. })
  297. }
  298. }
  299. }
  300. })
  301. .catch((err) => {
  302. console.error('请求失败:', err);
  303. // 在这里处理请求失败的情况
  304. });
  305. },
  306. getaddredisredis(){
  307. let data = {
  308. powerstationId: wx.getStorageSync('powerstationId')
  309. }
  310. api.request(`/syspowerstation/addredisredis`, 'POST', data)
  311. .then((res) => {
  312. console.log(res);
  313. })
  314. .catch((err) => {
  315. console.error('请求失败:', err);
  316. // 在这里处理请求失败的情况
  317. });
  318. },
  319. bindPickerChange: function (e) {
  320. console.log('picker发送选择改变,携带值为', e.detail.value)
  321. this.setData({
  322. index: e.detail.value
  323. })
  324. wx.setStorage({
  325. key: 'powerstationId', // 存储的key值
  326. data: this.data.objectArray[e.detail.value].powerstationId
  327. });
  328. let data = {
  329. powerstationId: this.data.objectArray[e.detail.value].powerstationId
  330. }
  331. api.request(`/syspowerstation/addredisredis`, 'POST', data)
  332. .then((res) => {
  333. console.log(res);
  334. if (this.data.index == '') {
  335. this.gitpower()
  336. } else {
  337. this.getworkoder()
  338. this.gitpower()
  339. }
  340. })
  341. .catch((err) => {
  342. console.error('请求失败:', err);
  343. // 在这里处理请求失败的情况
  344. });
  345. },
  346. initChart_right: function () {
  347. var unitName = '上网电量/万kWh'
  348. let _this = this;
  349. // 初始化选中索引(-1表示无选中)
  350. // this.setData({ activeBarIndex: 0 });
  351. this.ecline2.init((canvas, width, height, dpr) => {
  352. const chart = echarts.init(canvas, null, {
  353. width: width,
  354. height: height,
  355. devicePixelRatio: dpr
  356. });
  357. canvas.setChart(chart);
  358. // 原始柱体颜色(默认样式)
  359. const originalColor = 'rgba(60, 158, 250, 0.5)';
  360. // 高亮颜色
  361. const highlightColor = 'rgba(60, 158, 250, 1)';
  362. // 图表配置项
  363. var option = {
  364. title: {
  365. subtext: unitName,
  366. textStyle: { color: 'rgba(0, 0, 0, 0)' }
  367. },
  368. grid: {
  369. left: '1%',
  370. top: '18%',
  371. right: '1%',
  372. bottom: '20%',
  373. containLabel: true
  374. },
  375. xAxis: {
  376. type: 'category',
  377. data: _this.data.ymdlist,
  378. axisTick: { show: false },
  379. axisLabel: { interval: 0 }
  380. },
  381. yAxis: {
  382. type: 'value',
  383. x: 'center',
  384. axisTick: { show: false },
  385. splitLine: { show: false }
  386. },
  387. dataZoom: {
  388. type: 'inside',
  389. start: 0,
  390. end: 50
  391. },
  392. series: [{
  393. type: "bar",
  394. barMaxWidth: 20,
  395. label: { show: true, position: 'top', color: '#222' },
  396. data: _this.data.chargeTotal,
  397. itemStyle: {
  398. color: function (params) {
  399. // 只有选中的柱体用高亮色,其他保持原始色
  400. return params.dataIndex === _this.data.activeBarIndex
  401. ? highlightColor
  402. : originalColor;
  403. },
  404. barBorderRadius: [2, 2, 0, 0],
  405. // 选中柱体悬停增强
  406. emphasis: {
  407. shadowBlur: 10,
  408. shadowColor: 'rgba(0, 0, 0, 0)'
  409. }
  410. }
  411. }]
  412. };
  413. chart.setOption(option);
  414. // 柱体点击事件
  415. chart.on('click', function (params) {
  416. if (params.componentType !== 'series' || params.seriesType !== 'bar') {
  417. return;
  418. }
  419. const clickedIndex = params.dataIndex;
  420. // 切换选中状态(点击已选中的柱体则取消高亮)
  421. if (clickedIndex === _this.data.activeBarIndex) {
  422. return
  423. }
  424. const newActiveIndex = clickedIndex;
  425. _this.setData({ activeBarIndex: newActiveIndex }, () => {
  426. // 重新设置颜色样式
  427. chart.setOption({
  428. series: [{
  429. itemStyle: {
  430. color: function (p) {
  431. return p.dataIndex === _this.data.activeBarIndex
  432. ? highlightColor
  433. : originalColor;
  434. }
  435. }
  436. }]
  437. });
  438. });
  439. _this.choicestation()
  440. });
  441. return chart;
  442. });
  443. },
  444. //点击的柱体
  445. choicestation() {
  446. console.log(this.data.activeBarIndex);
  447. console.log(this.data.powerdata);
  448. this.setData({
  449. activeBardata: this.data.powerdata.sysPowerstationdatalist[this.data.activeBarIndex]
  450. })
  451. },
  452. convertTimestamp(value, unit = 'day') {
  453. // 如果是数字,视为时间戳,转换为日期字符串
  454. if (typeof value === 'number') {
  455. // 处理毫秒级和秒级时间戳
  456. const timestamp = value.toString().length === 10 ? value * 1000 : value;
  457. return this.formatDate(new Date(timestamp), unit);
  458. }
  459. // 如果是字符串,视为日期字符串,转换为时间戳(毫秒)
  460. if (typeof value === 'string') {
  461. // 支持 YYYY-MM-DD、YYYY-MM、YYYY 三种格式
  462. const dateParts = value.split('-');
  463. let year = parseInt(dateParts[0], 10);
  464. let month = dateParts.length > 1 ? parseInt(dateParts[1], 10) - 1 : 0; // 月份从0开始
  465. let day = dateParts.length > 2 ? parseInt(dateParts[2], 10) : 1;
  466. // 处理无效日期
  467. const date = new Date(year, month, day);
  468. if (isNaN(date.getTime())) {
  469. console.error('无效的日期格式:', value);
  470. return null;
  471. }
  472. return date.getTime();
  473. }
  474. console.error('不支持的转换类型:', typeof value);
  475. return null;
  476. },
  477. /**
  478. * 切换日/月/年单位
  479. */
  480. handleUnitChange(e) {
  481. console.log(e);
  482. const targetClass = e.currentTarget.dataset.name;
  483. let currentUnit = 'day';
  484. if (targetClass == "choiceday") currentUnit = 'day';
  485. else if (targetClass == "choicemoon") currentUnit = 'month';
  486. else if (targetClass == "choiceyear") currentUnit = 'year';
  487. const formattedDate = this.formatDate(new Date(this.data.actualDate), 'day');
  488. this.setData({ currentUnit, currentDate: formattedDate }, () => {
  489. this.updateDisableStatus();
  490. });
  491. },
  492. // 选择电站
  493. bindchart(e) {
  494. console.log(e);
  495. this.setData({
  496. activeBarIndex: e.currentTarget.dataset.index,
  497. activeBardata: this.data.powerdata.sysPowerstationdatalist[e.currentTarget.dataset.index]
  498. })
  499. this.initChart_right();
  500. },
  501. /**
  502. * 处理翻页逻辑:单箭头=当前单位,双箭头=上级单位
  503. */
  504. handleDateNav(e) {
  505. const { currentUnit, actualDate, minDate, maxDate } = this.data;
  506. const action = e.currentTarget.dataset.action;
  507. const currentDateObj = new Date(actualDate);
  508. const minDateObj = new Date(minDate);
  509. const maxDateObj = new Date(maxDate);
  510. let newDateObj;
  511. // 确定翻页单位
  512. const navUnit = action.includes('day') ? currentUnit : this.getUpperUnit(currentUnit);
  513. // 计算新日期
  514. switch (navUnit) {
  515. case 'day':
  516. newDateObj = new Date(currentDateObj);
  517. action.startsWith('prev')
  518. ? newDateObj.setDate(currentDateObj.getDate() - 1)
  519. : newDateObj.setDate(currentDateObj.getDate() + 1);
  520. break;
  521. case 'month':
  522. newDateObj = new Date(currentDateObj);
  523. action.startsWith('prev')
  524. ? newDateObj.setMonth(newDateObj.getMonth() - 1)
  525. : newDateObj.setMonth(newDateObj.getMonth() + 1);
  526. // 处理跨月日期溢出
  527. if (newDateObj.getDate() !== currentDateObj.getDate()) {
  528. newDateObj.setDate(0);
  529. }
  530. break;
  531. case 'year':
  532. newDateObj = new Date(currentDateObj);
  533. action.startsWith('prev')
  534. ? newDateObj.setFullYear(newDateObj.getFullYear() - 1)
  535. : newDateObj.setFullYear(newDateObj.getFullYear() + 1);
  536. // 处理闰年2月29日特殊情况
  537. if (newDateObj.getDate() !== currentDateObj.getDate()) {
  538. newDateObj.setDate(0);
  539. }
  540. break;
  541. }
  542. console.log(newDateObj);
  543. // 检查是否超出最小/最大日期范围
  544. if (newDateObj.getTime() < minDateObj.getTime() || newDateObj.getTime() > maxDateObj.getTime()) {
  545. wx.showToast({
  546. title: '超出时间范围',
  547. icon: 'none'
  548. });
  549. return; // 超出范围则不更新
  550. }
  551. // 正常更新日期
  552. const newActualDate = this.formatDate(newDateObj, 'day');
  553. const newDisplayDate = this.formatDate(newDateObj, currentUnit);
  554. console.log(newActualDate);
  555. console.log(newDisplayDate);
  556. this.setData({
  557. actualDate: newActualDate,
  558. currentDate: newDisplayDate
  559. }, () => {
  560. this.updateDisableStatus();
  561. });
  562. this.gitpower()
  563. },
  564. /**
  565. * 获取上级单位
  566. */
  567. getUpperUnit(unit) {
  568. const upperMap = { day: 'month', month: 'year', year: 'year' };
  569. return upperMap[unit];
  570. },
  571. /**
  572. * 更新禁用状态:同时判断最小和最大日期边界
  573. */
  574. updateDisableStatus() {
  575. const { currentUnit, actualDate, minDate, maxDate } = this.data;
  576. const currentObj = new Date(actualDate);
  577. const minObj = new Date(minDate);
  578. const maxObj = new Date(maxDate);
  579. const upperUnit = this.getUpperUnit(currentUnit);
  580. const status = { isMin: false, isMax: false, isUpperMin: false, isUpperMax: false };
  581. // 判断当前单位边界
  582. status.isMin = this.isDateEqual(currentObj, minObj, currentUnit);
  583. status.isMax = this.isDateEqual(currentObj, maxObj, currentUnit);
  584. // 判断上级单位边界
  585. status.isUpperMin = this.isDateEqual(currentObj, minObj, upperUnit);
  586. status.isUpperMax = this.isDateEqual(currentObj, maxObj, upperUnit);
  587. this.setData(status);
  588. },
  589. /**
  590. * 按指定单位比较两个日期是否相等
  591. */
  592. isDateEqual(date1, date2, unit) {
  593. if (unit === 'day') {
  594. return date1.getFullYear() === date2.getFullYear()
  595. && date1.getMonth() === date2.getMonth()
  596. && date1.getDate() === date2.getDate();
  597. } else if (unit === 'month') {
  598. return date1.getFullYear() === date2.getFullYear()
  599. && date1.getMonth() === date2.getMonth();
  600. } else if (unit === 'year') {
  601. return date1.getFullYear() === date2.getFullYear();
  602. }
  603. return false;
  604. },
  605. /**
  606. * 日历选择器相关方法
  607. */
  608. onCalendarClick() {
  609. console.log(this.data.currentDate);
  610. // console.log(dateToTimestamp.dateToTimestamp(this.data.currentDate));
  611. this.setData({
  612. currentTime: new Date(this.data.currentDate).getTime()
  613. })
  614. console.log(this.data.currentTime);
  615. this.setData({ visible: true });
  616. },
  617. handleConfirm(e) {
  618. console.log(e);
  619. // 1761062400000
  620. // 1761753600000
  621. const selectedDate = e.detail.value;
  622. const { minDate, maxDate, currentUnit } = this.data;
  623. const selectedObj = new Date(selectedDate);
  624. const minObj = new Date(minDate);
  625. const maxObj = new Date(maxDate);
  626. // 检查选中日期是否在有效范围内
  627. if (selectedObj.getTime() < minObj.getTime() || selectedObj.getTime() > maxObj.getTime()) {
  628. this.setData({ visible: false });
  629. return;
  630. }
  631. console.log(timestamp(selectedObj));
  632. // const formattedDate = this.formatDate(new Date(selectedDate), currentUnit);
  633. const formattedDate = timestamp(selectedObj)
  634. console.log(formattedDate);
  635. this.setData({
  636. actualDate: selectedDate,
  637. currentDate: formattedDate,
  638. visible: false
  639. }, () => {
  640. this.updateDisableStatus();
  641. });
  642. this.gitpower()
  643. },
  644. onClose(e) {
  645. console.log(e);
  646. this.setData({ visible: false });
  647. },
  648. /**
  649. * 动态格式化日期
  650. */
  651. formatDate(date, unit) {
  652. // 处理传入的date参数(兼容字符串格式的日期)
  653. const targetDate = new Date(date);
  654. // 校验日期有效性
  655. if (isNaN(targetDate.getTime())) {
  656. console.error('无效的日期格式:', date);
  657. return ''; // 或返回默认值
  658. }
  659. // 从传入的日期中获取年、月、日
  660. const year = targetDate.getFullYear();
  661. const month = String(targetDate.getMonth() + 1).padStart(2, '0'); // 月份从0开始,需+1
  662. const day = String(targetDate.getDate()).padStart(2, '0');
  663. // 根据单位返回对应格式
  664. switch (unit) {
  665. case 'day':
  666. return `${year}-${month}-${day}`; // 例如:2025-11-04
  667. case 'month':
  668. return `${year}-${month}`; // 例如:2025-11
  669. case 'year':
  670. return `${year}`; // 例如:2025
  671. default:
  672. return `${year}-${month}-${day}`; // 默认返回完整日期
  673. }
  674. },
  675. /**
  676. * 外部调用接口:设置最小日期
  677. */
  678. setMinDate(minDate) {
  679. if (new Date(minDate) && this.isValidDate(minDate)) {
  680. this.setData({ minDate }, () => {
  681. this.checkDateInRange();
  682. this.updateDisableStatus();
  683. });
  684. }
  685. },
  686. /**
  687. * 外部调用接口:设置最大日期
  688. */
  689. setMaxDate(maxDate) {
  690. if (new Date(maxDate) && this.isValidDate(maxDate)) {
  691. this.setData({ maxDate }, () => {
  692. this.checkDateInRange();
  693. this.updateDisableStatus();
  694. });
  695. }
  696. },
  697. /**
  698. * 检查当前日期是否在有效范围内,不在则自动调整
  699. */
  700. checkDateInRange() {
  701. const { actualDate, minDate, maxDate, currentUnit } = this.data;
  702. const currentObj = new Date(actualDate);
  703. const minObj = new Date(minDate);
  704. const maxObj = new Date(maxDate);
  705. let adjustedDate = actualDate;
  706. if (currentObj.getTime() < minObj.getTime()) {
  707. adjustedDate = minDate;
  708. } else if (currentObj.getTime() > maxObj.getTime()) {
  709. adjustedDate = maxDate;
  710. }
  711. if (adjustedDate !== actualDate) {
  712. this.setData({
  713. actualDate: adjustedDate,
  714. currentDate: this.formatDate(new Date(adjustedDate), currentUnit)
  715. });
  716. }
  717. },
  718. /**
  719. * 验证日期格式是否有效
  720. */
  721. isValidDate(dateString) {
  722. const regExp = /^\d{4}-\d{2}-\d{2}$/;
  723. if (!regExp.test(dateString)) return false;
  724. const date = new Date(dateString);
  725. return date.toISOString().slice(0, 10) === dateString;
  726. },
  727. /**
  728. * 生命周期函数--监听页面初次渲染完成
  729. */
  730. onReady() {
  731. },
  732. /**
  733. * 生命周期函数--监听页面显示
  734. */
  735. onShow() {
  736. // this.initChartright()
  737. this.gitpower()
  738. },
  739. /**
  740. * 生命周期函数--监听页面隐藏
  741. */
  742. onHide() {
  743. },
  744. /**
  745. * 生命周期函数--监听页面卸载
  746. */
  747. onUnload() {
  748. },
  749. /**
  750. * 页面相关事件处理函数--监听用户下拉动作
  751. */
  752. async onPullDownRefresh() {
  753. await this.getworkoder()
  754. await this.gitpower()
  755. await wx.stopPullDownRefresh();
  756. },
  757. /**
  758. * 页面上拉触底事件的处理函数
  759. */
  760. onReachBottom() {
  761. },
  762. /**
  763. * 用户点击右上角分享
  764. */
  765. onShareAppMessage() {
  766. }
  767. })