util.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915
  1. import { getData } from '@/api/platform/desktop/column'
  2. import { getFile } from '@/utils/avatar'
  3. import { mapState } from 'vuex'
  4. import { taskTypeOptions, dashboardStatus, genderOptions, favoritesOptions, noticeOptions, unreadMessageOptions, imgOptionsData } from '@/business/platform/bpmn/constants'
  5. import ActionUtils from '@/utils/action'
  6. import Utils from '@/utils/util'
  7. import { findAllByCurrUserId, saveCalendarInfos, removeCalendarInfos, delNavigation, addNavigation, getNavigation, sortNavigation } from '@/api/detection/newHomeApi'
  8. import { isEqual, now } from 'lodash'
  9. import Bus from '@/utils/EventBus'
  10. import newPng from '@/assets/images/homepage/new.png'
  11. import { BASE_URL } from '@/constant'
  12. import dayjs from 'dayjs'
  13. import { scheduleType } from '@/views/constants/schedule'
  14. import { lifeTimeData } from '@/views/business/deviceManagement/constants/simulated'
  15. /**
  16. * 创建组件
  17. */
  18. export function buildComponent (name, column, preview, vm) {
  19. try {
  20. return {
  21. name,
  22. components: {
  23. VueDraggable: () => import('vuedraggable')
  24. },
  25. props: {
  26. params: {
  27. type: Object,
  28. default: () => {}
  29. },
  30. height: {
  31. type: Number,
  32. default: column.height || 300
  33. },
  34. visible: {
  35. type: Boolean,
  36. default: false
  37. },
  38. fullScreen: {
  39. type: Boolean,
  40. default: false
  41. }
  42. },
  43. filters: {
  44. filterStatus (val, type) {
  45. if (Utils.isEmpty(val)) {
  46. return ''
  47. }
  48. const typeMap = {
  49. pending: taskTypeOptions,
  50. already: dashboardStatus,
  51. myRequest: dashboardStatus,
  52. gender: genderOptions,
  53. favorites: favoritesOptions,
  54. notice: noticeOptions,
  55. unreadMessage: unreadMessageOptions
  56. }
  57. if (!typeMap[type]) {
  58. return val
  59. }
  60. return typeMap[type].find(x => x['value'] === val) ? typeMap[type].find(x => x['value'] === val).label : val
  61. }
  62. },
  63. data () {
  64. const { first = '', second = '' } = this.$store.getters.level
  65. const { userId, userList = [], deptList = [], menus, userInfo } = this.$store.getters
  66. const t1 = deptList.find(i => i.positionId === first) || {}
  67. const t2 = deptList.find(i => i.positionId === second) || {}
  68. const locationName = second ? t1.positionName + t2.positionName : t1.positionName
  69. return {
  70. userId,
  71. userList,
  72. deptList,
  73. menus,
  74. locationName,
  75. newPng,
  76. imgOptionsData,
  77. positions: userInfo.positions,
  78. loading: false,
  79. title: `${column.name}`,
  80. alias: `${column.alias}`,
  81. attrs: this.getAttrs(),
  82. variables: {}, // 一些变量,比如分页信息
  83. data: null,
  84. totalCount: 0,
  85. quickNavigationData: [],
  86. navigationList: [],
  87. stautusOptions: [],
  88. bpmnFormrenderDialogVisible: false, // 表单
  89. editId: '',
  90. bodyShow: true,
  91. show: false,
  92. showHeight: '',
  93. cardHeight: '100%',
  94. activeName: 'innerMessage',
  95. unreadMessageOption: {},
  96. formName: 'quickNavform',
  97. dialogFormVisible: false,
  98. formLabelWidth: '120px',
  99. quickNavform: {
  100. urlName: '',
  101. urlAddr: '',
  102. display: '_blank',
  103. diDian: second || first
  104. },
  105. defaultForm: {},
  106. pendingTabActiveName: 'user-type',
  107. bodyParams: ActionUtils.formatParams({}, {}, {}),
  108. pendingBusinessOption: {},
  109. bpmn: [],
  110. rules: {
  111. urlName: [
  112. {
  113. required: true,
  114. message: this.$t('validate.required')
  115. }
  116. ],
  117. urlAddr: [
  118. {
  119. required: true,
  120. message: this.$t('validate.required')
  121. }
  122. ],
  123. display: [
  124. {
  125. required: true,
  126. message: this.$t('validate.required')
  127. }
  128. ]
  129. },
  130. calendarDialogForm: {
  131. id: '',
  132. biaoTi: '',
  133. neiRong: '',
  134. kaiShiShiJian: '',
  135. jieShuShiJian: '',
  136. formDate: []
  137. },
  138. colorStatus: ['#e7505a', '#f3c200', '#578ebe', '#1BBC9B'],
  139. // const status = ['急', '重', '轻','缓']
  140. isDragging: false,
  141. draggableOptions: {
  142. handle: '.draggable',
  143. ghostClass: 'sortable-ghost',
  144. distance: 1,
  145. disabled: false,
  146. animation: 200,
  147. axis: 'y'
  148. },
  149. calendarToolbar: this.fullScreen ? [{ key: 'refresh' }] : [{ key: 'refresh' }, { key: 'fullscreen' }, { key: 'collapse' }],
  150. isFirstAlert: true, // 是否首次日程提醒
  151. scheduleData: [],
  152. hasMounted: false,
  153. attendanceData: [],
  154. scheduleShift: [],
  155. todaySchedule: [],
  156. tempSelectedValue: ''
  157. }
  158. },
  159. computed: {
  160. ...mapState({
  161. userInfo: state => state.ibps.user.info
  162. })
  163. },
  164. mounted () {
  165. this.defaultForm = JSON.parse(JSON.stringify(this.quickNavform))
  166. this.$nextTick(async () => {
  167. this.fetchData()
  168. this.attendanceData = await this.getAttendanceData()
  169. this.scheduleData = await this.getScheduleData()
  170. })
  171. },
  172. methods: {
  173. fetchData (columns, params = {}) {
  174. this.loading = true
  175. this.data = []
  176. this.showHeight = this.getHeight()
  177. const param = Utils.isNotEmpty(columns) && (column.alias === 'unreadMessage' || column.alias === 'pendingBusiness')
  178. ? { dataMode: column.dataMode, dataFrom: column.dataFrom }
  179. : column
  180. if (param.alias === 'myCalendar') {
  181. const { getFormatDate, getDate } = this.$common
  182. findAllByCurrUserId().then(res => {
  183. const { data = [] } = res || {}
  184. if (this.isFirstAlert) {
  185. this.isFirstAlert = false
  186. this.showAlert(data)
  187. }
  188. this.data = data.map(i => ({
  189. id: i.id,
  190. title: i.title,
  191. content: i.content,
  192. start: i.startTime,
  193. // 日期组件日程显示里,end的时间需要多加一天,end:2024-01-02时,日程条只到2024-01-01的日期位置上
  194. end: getFormatDate('string', 10, getDate('day', 1, i.endTime)),
  195. jieShuShiJian: i.endTime,
  196. zhuangTai: i.emergencyState,
  197. color: this.colorStatus[Number(i.emergencyState) - 1]
  198. }))
  199. }).catch(() => {
  200. this.$message.error('获取日历日程失败!')
  201. })
  202. } else if (param.alias === 'quickNavigation') {
  203. getNavigation().then(res => {
  204. const { data = [] } = res || {}
  205. data.forEach(item => {
  206. if (!item.userId) {
  207. item.urlAddr = `${BASE_URL}#${item.urlAddr}`
  208. }
  209. })
  210. this.quickNavigationData = data
  211. })
  212. } else {
  213. getData(param, params).then(res => {
  214. let { data } = res || {}
  215. if (Utils.isNotEmpty(data) && Utils.isString(data)) {
  216. data = Utils.parseData(res.data)
  217. }
  218. this.data = data && data.dataResult ? data.dataResult : data
  219. this.totalCount = data && data.pageResult ? data.pageResult.totalCount : 0
  220. // 更新小铃铛消息数量
  221. if (param.alias === 'unreadMessage') {
  222. Bus.$emit('getMessageCount', this.totalCount)
  223. }
  224. this.variables = res.variables
  225. this.loading = false
  226. }).catch((e) => {
  227. this.loading = false
  228. })
  229. }
  230. },
  231. // 过滤日程提醒数据
  232. filterAlertData (data, dayNumber = 3) {
  233. if (dayNumber <= 0) return
  234. const today = dayjs()
  235. const tempCalendarAlertData = data.filter(day => {
  236. const startTime = dayjs(day.startTime)
  237. const endTime = dayjs(day.endTime)
  238. if (day.popUp) {
  239. if ((startTime.diff(today, 'day') <= 0 && endTime.diff(today, 'day') >= 0) || (startTime.diff(today, 'day') <= dayNumber - 2 && startTime.diff(today, 'day') >= 0)) {
  240. return true
  241. }
  242. }
  243. })
  244. tempCalendarAlertData.sort((a, b) => new Date(a.startTime) - new Date(b.startTime))
  245. const calendarIds = tempCalendarAlertData.map(item => item.id)
  246. const calendarAlertData = {}
  247. tempCalendarAlertData.forEach(item => {
  248. if (calendarAlertData[item.startTime]) {
  249. calendarAlertData[item.startTime].push(item)
  250. } else {
  251. calendarAlertData[item.startTime] = []
  252. calendarAlertData[item.startTime].push(item)
  253. }
  254. })
  255. return { calendarAlertData, calendarIds }
  256. },
  257. // 日程提醒
  258. showAlert (data) {
  259. const calendarAlertData = this.filterAlertData(data)
  260. this.$emit('action-event', 'calendarAlert', calendarAlertData)
  261. },
  262. getPhoto (photo) {
  263. return getFile(photo)
  264. },
  265. getTaskDesc (v) {
  266. if (!v.includes('#')) {
  267. return ''
  268. }
  269. return v.split('#')[1] || ''
  270. },
  271. getTaskInfo (val, arg) {
  272. const arr = val.split('#')
  273. if (!arr[2]) {
  274. return ''
  275. }
  276. // 中文冒号转英文冒号 防止流程定义时输入的冒号格式错误导致转换报错
  277. arr[2] = arr[2].replace(':', ':')
  278. const result = JSON.parse(`{${arr[2]}}`)
  279. if (!result.dept) {
  280. return ''
  281. }
  282. const depts = result.dept.split(',')
  283. const deptNames = []
  284. depts.forEach(item => {
  285. const t = this.deptList.find(i => i.positionId === item)
  286. deptNames.push(t ? t.positionName : result.dept)
  287. })
  288. result.deptName = deptNames.join(',')
  289. return result[arg]
  290. },
  291. transformData (val, dataset, from, to) {
  292. if (!val) {
  293. return ''
  294. }
  295. const temp = this[dataset].find(u => u[from] === val)
  296. return temp ? temp[to] : ''
  297. },
  298. getHeightNoUnit () {
  299. // 高度 - header - 边框
  300. if (!this.visible) {
  301. return this.height ? (this.height - 60 - 20) : 150
  302. } else {
  303. return 150
  304. }
  305. },
  306. getHeight (h = 20) {
  307. // 高度 - header - 边框
  308. if (!this.visible) {
  309. return this.height ? `${(this.height - 60 - h)}px` : '150px'
  310. } else {
  311. return '100%'
  312. }
  313. },
  314. getDashboardHeight () {
  315. return this.height ? `${this.height + 20}px` : '150px'
  316. },
  317. getAttrs () {
  318. const item = JSON.parse(JSON.stringify(column))
  319. item.templateHtml = null
  320. return item
  321. },
  322. /**
  323. * 构建首页日期组件的参数
  324. * @param {*} data
  325. * @returns
  326. */
  327. getFullCalendarConfig (data) {
  328. const events = data === null ? [] : Utils.parseJSON(data)
  329. const config = {
  330. height: preview ? '100%' : (this.height ? this.height : 180),
  331. // editable: true, // 允许拖动缩放,不写默认就是false
  332. selectable: true,
  333. dayMaxEvents: 1, // 最多显示3个日程
  334. locale: this.$i18n.locale ? this.$i18n.locale.toLowerCase() : 'zh-cn',
  335. events: events,
  336. buttonText: {
  337. today: '今天',
  338. dayGridMonth: '月',
  339. listMonth: '日程'
  340. // week: '周视图',
  341. // day: '日视图',
  342. // prev: '<i class="icon-chevron-left">后退</i>',
  343. // next: '<i class="icon-chevron-right">前进</i>'
  344. },
  345. dateClick: this.handleDateClick, // 日期点击
  346. eventClick: this.handleEventClick,
  347. moreLinkClick: this.handleMoreLinkClick
  348. }
  349. if (preview) {
  350. config.headerToolbar = {
  351. start: '',
  352. center: 'title',
  353. end: 'prev,next,today'
  354. // end: 'prev,next,today,month,agendaWeek,agendaDay,listWeek'
  355. }
  356. delete config['dayMaxEvents']
  357. }
  358. return config
  359. },
  360. handleDateClick (param) {
  361. this.$emit(
  362. 'open',
  363. 'calendar',
  364. [param.dateStr, param.dateStr],
  365. this.data
  366. )
  367. },
  368. handleEventClick (param) {
  369. this.$emit(
  370. 'open',
  371. 'calendar',
  372. [param.event.startStr, param.event._def.extendedProps.jieShuShiJian],
  373. this.data,
  374. param.event.id
  375. )
  376. },
  377. handleMoreLinkClick (date) {
  378. this.$emit(
  379. 'open',
  380. 'calendar',
  381. [date.allSegs[0].event.startStr, date.allSegs[0].event._def.extendedProps.jieShuShiJian],
  382. this.data,
  383. date.allSegs[0].event.id
  384. )
  385. },
  386. refreshData () {
  387. this.fetchData()
  388. },
  389. /**
  390. * 处理按钮事件
  391. * @param {*} command
  392. * @param {*} position
  393. * @param {*} data
  394. * @param {*} actions
  395. */
  396. handleActionEvent (command, position, data, actions) {
  397. switch (command) {
  398. case 'refresh': // 刷新
  399. this.refreshData()
  400. break
  401. case 'fullscreen': // 全屏
  402. this.handleFullscreen()
  403. break
  404. case 'more': // 更多
  405. this.handleMore()
  406. break
  407. case 'collapse': // 收缩
  408. case 'expansion': // 展开
  409. this.handleCollapseExpand(command, data, actions)
  410. break
  411. case 'add': // 新增
  412. this.getFormData()
  413. break
  414. default:
  415. break
  416. }
  417. },
  418. emitActionEventHandler (command) {
  419. this.$emit('action-event', command, ...Array.from(arguments).slice(1))
  420. },
  421. // 公告栏目点击事件
  422. handleApprove (id, title) {
  423. this.$emit('action-event', 'approve', {
  424. id, title
  425. })
  426. },
  427. handleUnreadMessage (id, tableId, tableName) {
  428. this.$emit('action-event', 'unRead', { id, tableId, tableName })
  429. },
  430. // 处理全屏
  431. handleFullscreen () {
  432. this.emitActionEventHandler('fullscreen', { id: this.attrs.id })
  433. },
  434. openPlate (url) {
  435. const menuMap = {
  436. myTraining: 'rygl/rypx/wdpx',
  437. myTesting: 'rygl/kszx/wdks',
  438. myDevices: 'sbgls/mywh',
  439. notice: 'tygl/tzgg',
  440. myFacility: 'sshjgl/sshjjk/sshjkzzl',
  441. quickNavigation: 'xtgl/xtsjpz/tyglpz/kjdhpz'
  442. }
  443. if (menuMap[url]) {
  444. const alias = menuMap[url].split('/')[0]
  445. const resInfo = this.menus.find(i => i.alias === alias)
  446. this.$store.dispatch('ibps/menu/activeHeaderSet', { activeHeader: resInfo.id, vm: this })
  447. }
  448. this.$router.push(`/${menuMap[url] || url}`)
  449. },
  450. /**
  451. * 处理更多
  452. */
  453. handleMore () {
  454. if (this.attrs.alias === 'quickNavigation') {
  455. return this.openPlate('quickNavigation')
  456. }
  457. if (!this.attrs.colUrl) {
  458. return this.$message.warning('未设置更多路径的url')
  459. }
  460. this.openPlate(this.attrs.colUrl)
  461. },
  462. // 未读消息
  463. handleClick (option) {
  464. this.unreadMessageOption = option
  465. option[this.activeName].dataMode = column.dataMode
  466. this.fetchData(option[this.activeName])
  467. },
  468. // 待办事务
  469. handleTabClick (option) {
  470. this.pendingBusinessOption = option
  471. option[this.pendingTabActiveName].dataMode = column.dataMode
  472. this.fetchData(option[this.pendingTabActiveName])
  473. },
  474. handleFlowClick (params) {
  475. params.$alias = this.alias
  476. this.emitActionEventHandler('flow', params)
  477. },
  478. handleCollapseExpand (command, data, actions) {
  479. this.bodyShow = !this.bodyShow
  480. const index = actions.findIndex((action) => action.key === data.key)
  481. actions[index].key = this.bodyShow ? 'collapse' : 'expansion'
  482. if (!this.visible) {
  483. this.emitActionEventHandler(command, {})
  484. return
  485. }
  486. this.showHeight = this.bodyShow ? this.getHeight() : 0
  487. this.$refs['toolbar'].callback(actions)
  488. },
  489. formValidate (formName) {
  490. this.$nextTick(() => {
  491. this.$refs[formName].validate(() => {})
  492. })
  493. },
  494. getFormData () {
  495. this.quickNavform = JSON.parse(JSON.stringify(this.defaultForm))
  496. this.formValidate('quickNavform')
  497. this.dialogFormVisible = true
  498. },
  499. handleNavRemove (navId, i) {
  500. this.$confirm('是否确认删除该快捷导航?', '提示', {
  501. confirmButtonText: '确认',
  502. cancelButtonText: '取消',
  503. type: 'warning',
  504. showClose: false,
  505. closeOnClickModal: false
  506. }).then(() => {
  507. delNavigation({ navigateIds: navId }).then(() => {
  508. this.$message.success('删除成功')
  509. this.quickNavigationData.splice(i, 1)
  510. })
  511. })
  512. },
  513. // 错误头像的照片
  514. errorAvatarHandler (data) {
  515. // data.photo = require('https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png')
  516. return true
  517. },
  518. close () {
  519. this.$refs[this.formName].resetFields()
  520. this.dialogFormVisible = false
  521. },
  522. saveQuickNav () {
  523. this.$refs[this.formName].validate(valid => {
  524. if (valid) {
  525. addNavigation({ id: '', ...this.quickNavform }).then(res => {
  526. this.$message.success('添加成功!')
  527. const { id } = res.variables || {}
  528. this.quickNavigationData.unshift({ id, ...this.quickNavform, userId: this.userId })
  529. this.dialogFormVisible = false
  530. })
  531. } else {
  532. ActionUtils.saveErrorMessage()
  533. }
  534. })
  535. },
  536. handleSortChange () {
  537. this.isDragging = false
  538. const newSort = this.quickNavigationData.map(i => i.id)
  539. if (isEqual(this.navigationList, newSort)) {
  540. return
  541. }
  542. this.navigationList = newSort
  543. sortNavigation({ orders: this.navigationList.join(',') }).then(() => {
  544. this.$message.success('排序成功!')
  545. })
  546. },
  547. // 父组件调用该方法给日程添加数据
  548. async setCalendarEvents (param) {
  549. const { name = '' } = this.$store.getters
  550. const form = param.form
  551. const paramObject = {
  552. id: form.id ? form.id : '11111',
  553. // diDian: "string", // 地点
  554. userId: this.userId, // 用户id
  555. userName: name, // 用户名
  556. title: form.biaoTi, // 标题
  557. content: form.neiRong, // 内容
  558. startTime: form.formDate[0], // 开始时间
  559. endTime: form.formDate[1], // 结束时间
  560. emergencyState: form.zhuangTai // 紧急状态
  561. }
  562. await saveCalendarInfos(paramObject)
  563. this.refreshData()
  564. },
  565. async hanldeCalendardel (param) {
  566. if (param.form.id) {
  567. await removeCalendarInfos({
  568. calendarIds: param.form.id
  569. })
  570. }
  571. this.refreshData()
  572. },
  573. // 公告栏是否显示new图标
  574. showNewIcon (date, days) {
  575. const nowDate = new Date().getTime()
  576. const targetDate = new Date(date).getTime()
  577. return targetDate + days * 24 * 60 * 60 * 1000 > nowDate
  578. },
  579. handleOverflow (val, length) {
  580. if (val.length > length) {
  581. return val.slice(0, length - 2) + '...'
  582. }
  583. return val
  584. },
  585. getDays (start, end) {
  586. if (!start || !end) {
  587. return 0
  588. }
  589. return Math.ceil((new Date(end) - new Date(start)) / (1000 * 60 * 60 * 24))
  590. },
  591. getAttendanceData () {
  592. const { first, second } = this.$store.getters.level || {}
  593. const today = this.$common.getDateNow()
  594. const sql = `select a.id_, a.kao_qin_zhuang_ta,a.ri_qi_, a.pai_ban_id_, a.pai_ban_ji_lu_id_, a.ban_ci_bie_ming_, a.ban_ci_kai_shi_, a.ban_ci_jie_shu_, a.ban_ci_ming_, a.da_ka_shi_jian_1_, a.zhuang_tai_1_, a.da_ka_shi_jian_2_, a.zhuang_tai_2_, a.chi_dao_shi_chang FROM t_attendance_detail a JOIN t_schedule b ON a.pai_ban_id_ = b.id_ AND b.status_ = '已发布' WHERE a.di_dian_ = '${second || first}' AND a.ri_qi_ <= '${today}' AND a.yong_hu_id_ = '${this.userId}' `
  595. return new Promise((resolve, reject) => {
  596. this.$common.request('sql', sql).then(res => {
  597. const { data = [] } = res.variables || {}
  598. const resultMap = new Map()
  599. data.forEach(item => {
  600. const { ri_qi_, pai_ban_id_, ban_ci_bie_ming_, ...rest } = item
  601. // 第一级:按日期分组
  602. if (!resultMap.has(ri_qi_)) {
  603. resultMap.set(ri_qi_, new Map())
  604. }
  605. const dateMap = resultMap.get(ri_qi_)
  606. // 第二级:按排班ID分组
  607. if (!dateMap.has(pai_ban_id_)) {
  608. dateMap.set(pai_ban_id_, new Map())
  609. }
  610. const scheduleMap = dateMap.get(pai_ban_id_)
  611. // 第三级:按班次别名存储完整数据
  612. scheduleMap.set(ban_ci_bie_ming_, rest)
  613. })
  614. // return resultMap
  615. resolve(resultMap)
  616. }).catch(error => {
  617. reject(error)
  618. })
  619. })
  620. },
  621. getScheduleData () {
  622. const { first, second } = this.$store.getters.level || {}
  623. const sql = `select a.*, b.title_,b.type_, b.start_date_, b.end_date_, b.config_, b.overview_, b.id_ as pai_ban_id_ from t_schedule_detail a, t_schedule b where a.parent_id_ = b.id_ and b.di_dian_ = '${second || first}' and a.user_id_ = '${this.userId}' and b.status_ = '已发布'`
  624. return new Promise((resolve, reject) => {
  625. this.$common.request('sql', sql).then((res) => {
  626. const { data = [] } = res.variables || {}
  627. const eventList = []
  628. const self = this
  629. data.forEach(item => {
  630. const days = this.getDays(item.start_date_, item.end_date_)
  631. const config = item.config_ ? JSON.parse(item.config_) : {}
  632. const scheduleTypeLabel = scheduleType.filter(obj => obj.value === item.type_)[0]?.label || ''
  633. const scheduleCreateBy = self.userList.filter(obj => obj.userId === item.create_by_)[0]?.userName || ''
  634. const { scheduleShift } = config
  635. this.scheduleShift = scheduleShift
  636. for (let i = 1; i <= days; i++) {
  637. const shift = item[`d${i}_`]
  638. if (shift) {
  639. const date = this.$common.getFormatDate('string', 10, this.$common.getDate('day', i - 1, item.start_date_))
  640. const shiftList = shift.split(',')
  641. shiftList.forEach(s => {
  642. const t = scheduleShift.find(i => i.alias === s)
  643. const attendance = self.attendanceData
  644. .get(date)
  645. ?.get(item.pai_ban_id_)
  646. ?.get(s)
  647. eventList.push({
  648. scheduleName: item.title_ ? item.title_ : '', // 排班表名字
  649. scheduleTypeLabel: scheduleTypeLabel || '', // 排班类型
  650. scheduleCreateBy: scheduleCreateBy || '', // 排班创建人
  651. content: t.dateRange.map(d => {
  652. return d.type === 'allday' ? '全天' : (`当天 ${d.startTime}` + ' 至 ' + `${d.isSecondDay === 'Y' ? '第二天' : '当天'} ${d.endTime}`)
  653. }).join('\n'),
  654. title: s,
  655. start: date,
  656. end: date,
  657. jieShuShiJian: date,
  658. zhuangTai: '',
  659. id: i,
  660. bcolor: t.color,
  661. attendance: attendance || {}, // 考勤状态
  662. ...t
  663. })
  664. })
  665. }
  666. }
  667. })
  668. const today = this.$common.getDateNow()
  669. this.todaySchedule = eventList.filter(i => i.start === today).map(i => i.title)
  670. console.log(this.todaySchedule)
  671. resolve(eventList)
  672. }).catch(error => {
  673. reject(error)
  674. })
  675. })
  676. },
  677. handleScheduleEventClick (param) { // 排班点击事件
  678. this.$emit(
  679. 'open',
  680. 'banci',
  681. param.event._def.extendedProps,
  682. this.scheduleShift,
  683. param.event._def.title
  684. )
  685. },
  686. showDaKaBtn (targetDay) { // 判断是否展示打卡按钮,当前日期则展示
  687. const today = this.$common.getDateNow()
  688. if (targetDay == today) {
  689. return true
  690. } else {
  691. return false
  692. }
  693. },
  694. // 打卡处理逻辑
  695. handleClock (attendance) {
  696. if (Object.keys(attendance).length === 0) {
  697. this.$message.warning('考勤数据异常!')
  698. return
  699. }
  700. // 获取当前时间
  701. const currentDate = new Date()
  702. const hours = currentDate.getHours()
  703. const minutes = currentDate.getMinutes()
  704. const dakashijian = `${hours}:${minutes}`
  705. const time = this.$common.getDateNow() + ' ' + dakashijian
  706. let str = '打卡成功!'
  707. // 在班次结束时间前初次点击打卡按钮,视作上班打卡,自动判定状态为正常或迟到(迟到需记录迟到时长);再次点击打卡按钮提示已打卡
  708. if (time < attendance.ban_ci_jie_shu_) { // 上班打卡
  709. if (!attendance.da_ka_shi_jian_1_) {
  710. attendance.da_ka_shi_jian_1_ = dakashijian
  711. attendance.zhuang_tai_1_ = time < attendance.ban_ci_kai_shi_ ? '正常' : '迟到'
  712. if (attendance.zhuang_tai_1_ == '迟到') {
  713. attendance.chi_dao_shi_chang = this.getTimeDifferenceInMinutes(attendance.ban_ci_kai_shi_, time)
  714. attendance.kao_qin_zhuang_ta = '异常' // 总考勤状态设置为异常
  715. }
  716. } else {
  717. this.$message.warning('该班次上班已打卡!')
  718. return
  719. }
  720. } else { // 下班打卡
  721. // 在班次结束时间后初始点击打卡按钮,视作下班打卡,再次点击打卡按钮则更新下班打卡时间并提示更新打卡时间成功
  722. if (attendance.da_ka_shi_jian_2_) {
  723. str = '已更新下班打卡!'
  724. }
  725. attendance.da_ka_shi_jian_2_ = dakashijian
  726. attendance.zhuang_tai_2_ = '正常'
  727. }
  728. // 更新打卡请求
  729. const tableName = ' t_attendance_detail'
  730. const updateParams = {
  731. tableName,
  732. updList: [
  733. {
  734. where: {
  735. id_: attendance.id_
  736. },
  737. param: {
  738. da_ka_shi_jian_1_: attendance.da_ka_shi_jian_1_,
  739. zhuang_tai_1_: attendance.zhuang_tai_1_,
  740. da_ka_shi_jian_2_: attendance.da_ka_shi_jian_2_,
  741. zhuang_tai_2_: attendance.zhuang_tai_2_,
  742. kao_qin_zhuang_ta: attendance.kao_qin_zhuang_ta,
  743. chi_dao_shi_chang: attendance.chi_dao_shi_chang
  744. }
  745. }
  746. ]
  747. }
  748. this.$common.request('update', updateParams).then(() => {
  749. this.$message.success(str)
  750. })
  751. },
  752. getTimeDifferenceInMinutes (startTimeStr, endTimeStr) { // 时间相减分钟数
  753. const startTime = new Date(startTimeStr)
  754. const endTime = new Date(endTimeStr)
  755. const timeDifference = endTime - startTime
  756. return timeDifference / (1000 * 60)
  757. },
  758. // 打卡处理逻辑
  759. handleClockFromTab (todaySchedule) {
  760. const today = this.$common.getDateNow()
  761. // 当天仅有一个班次
  762. if (todaySchedule.length == 1) {
  763. const scheduleObj = this.scheduleData.filter(item => item.start == today && item.alias == todaySchedule[0])
  764. const attendance = scheduleObj.attendance
  765. this.handleClock(attendance)
  766. } else {
  767. let scheduleArr = []
  768. for (let i = 0; i < todaySchedule.length; i++) {
  769. const currentSchedule = todaySchedule[i]
  770. const filtered = this.scheduleData.filter(item => item.start === today && item.alias === currentSchedule)
  771. scheduleArr = scheduleArr.concat(filtered)
  772. }
  773. debugger
  774. const h = this.$createElement
  775. const self = this
  776. this.$msgbox({
  777. title: '选择打卡班次',
  778. message: h('div', null, [
  779. h('p', { style: 'margin-bottom: 15px;' }, '请选择一个班次打卡'),
  780. h('el-radio-group', {
  781. model: {
  782. value: self.tempSelectedValue,
  783. callback: (value) => {
  784. self.tempSelectedValue = value;
  785. }
  786. }
  787. }, scheduleArr.map(schedule =>
  788. h('el-radio', {
  789. props: {
  790. label: schedule.alias,
  791. key: schedule.alias
  792. },
  793. style: 'display: block; margin: 10px 0;'
  794. }, schedule.alias))
  795. )
  796. ]),
  797. showCancelButton: true,
  798. confirmButtonText: '确定',
  799. cancelButtonText: '取消',
  800. beforeClose: (action, instance, done) => {
  801. if (action === 'confirm') {
  802. if (!this.tempSelectedValue) {
  803. this.$message.warning('请选择一个班次');
  804. return false;
  805. }
  806. done();
  807. } else {
  808. done();
  809. }
  810. }
  811. }).then(() => {
  812. const scheduleObj = this.scheduleData.find(item =>
  813. item.start === today && item.alias === this.tempSelectedValue
  814. );
  815. if (scheduleObj?.attendance) {
  816. this.handleClock(scheduleObj.attendance);
  817. }
  818. }).catch(() => {
  819. // 用户取消操作
  820. });
  821. }
  822. },
  823. showMySchedule () {
  824. const scheduleConfig = {
  825. height: '100%',
  826. locale: 'zh-cn', // 语言
  827. selectable: true, // 是否可以选中日历格
  828. buttonText: { // 日历头部按钮中文转换
  829. today: '今天',
  830. dayGridMonth: '月',
  831. listMonth: '',
  832. month: '月',
  833. week: '周视图',
  834. day: '日视图',
  835. list: '表'
  836. // prev: '<i class="icon-chevron-left">后退</i>',
  837. // next: '<i class="icon-chevron-right">前进</i>'
  838. },
  839. headerToolbar: { // 日历头部按钮位置
  840. // left: 'prev,next today',
  841. // start: '',
  842. right: 'prev,next today',
  843. left: '',
  844. center: 'title'
  845. // right: 'dayGridMonth,timeGridWeek,timeGridDay'
  846. // end: 'prev,next,today,month,agendaWeek,agendaDay,listWeek'
  847. },
  848. // events: this.scheduleData, // 排班数组
  849. eventClick: this.handleScheduleEventClick, // 排班点击信息展示
  850. scheduleShift: this.scheduleShift,
  851. eventColor: '#ffffff',
  852. events: this.scheduleData,
  853. // 添加自定义事件渲染
  854. eventContent: (arg) => {
  855. const event = arg.event
  856. const now = new Date()
  857. const dayStart = new Date(event.start)
  858. dayStart.setHours(0, 0, 0, 0)
  859. // 组合DOM内容
  860. const fragment = document.createDocumentFragment()
  861. const content = document.createElement('div')
  862. const titleStr = event.extendedProps.name + '/' + event.extendedProps.alias
  863. const timeStr = event.extendedProps.dateRange[0].startTime + '至' + event.extendedProps.dateRange[0].endTime
  864. // 考勤是否正常
  865. const status = event.extendedProps.attendance.kao_qin_zhuang_ta || ''
  866. content.innerHTML = `
  867. <div class="event-header">
  868. <div>
  869. <div style="background:${event.extendedProps.bcolor};height:10px;width:10px;display:inline-block;"> </div>
  870. ${titleStr}
  871. </div>
  872. <div class="button-placeholder">
  873. ${ event.extendedProps.jieShuShiJian <= this.$common.getDateNow() ?
  874. (
  875. (status === "正常")? '<i class="el-icon-check" style="color:#409EFF"></i>'
  876. : '<i class="el-icon-warning-outline" style="color:#F5222D"></i>'
  877. ) : ''
  878. }
  879. </div>
  880. </div>
  881. `
  882. // 打卡按钮显示
  883. if (this.showDaKaBtn(event.extendedProps.jieShuShiJian)) {
  884. const button = document.createElement('button')
  885. button.className = 'clock-btn'
  886. // 根据打卡状态显示不同文本
  887. button.innerHTML = '打卡'
  888. // 绑定点击事件(通过闭包传递当前事件)
  889. button.onclick = (e) => {
  890. e.stopPropagation()
  891. this.handleClock(event.extendedProps.attendance)
  892. }
  893. const placeholder = content.querySelector('.button-placeholder')
  894. placeholder.replaceWith(button)
  895. }
  896. fragment.appendChild(content)
  897. return { domNodes: [fragment] }
  898. }
  899. }
  900. this.$emit('action-event', 'mySchedule', scheduleConfig)
  901. }
  902. },
  903. template: column.templateHtml !== '' ? `${column.templateHtml}` : `<div></div>`
  904. }
  905. } catch (error) {
  906. console.error(error)
  907. }
  908. }