monitor.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. import { Card, Input, Radio, Select, Space, Spin, Tag, TimePicker, Tooltip, message } from "antd";
  2. import React, { useCallback, useEffect, useState } from "react";
  3. import { ColumnHeightOutlined, ColumnWidthOutlined, EyeInvisibleOutlined, EyeOutlined, RedoOutlined } from "@ant-design/icons";
  4. import useEcharts from '@/Hook/useEcharts'
  5. import { useModel } from 'umi'
  6. import { ListHourProps, ListType } from '@/services/adMonitor/adMonitor'
  7. import '../../adMonitor/adMonitorList/table.less'
  8. import moment from "moment";
  9. import TableData from "@/pages/launchSystemNew/components/TableData";
  10. import RuleAccountLog from "@/components/EarlyWarning/ruleAccountLog";
  11. import { LineField } from "@/pages/adMonitor/adMonitorList/config";
  12. import FilterQuery from "@/pages/adMonitor/adMonitorList/components/FilterQuery";
  13. import Details from "./Details";
  14. import { columnsMonitor } from "./tableMonitorConfig";
  15. import { qiliangpaihanghour } from "./config";
  16. import { syncBatchApi } from "@/services/launchAdq/adqv3";
  17. import { useAjax } from "@/Hook/useAjax";
  18. interface newListType extends ListType {
  19. totalTimeUnit: 'total' | 'minute' | 'hour' | 'day',
  20. planTimeUnit: 'minute' | 'hour' | 'day'
  21. }
  22. /**
  23. * 今日起量监控
  24. * @param props
  25. * @returns
  26. */
  27. function Monitor(props: { onChange: () => void }) {
  28. const { onChange } = props
  29. const { getCostTrendV3List, getCostTopV3List, getListForHourV3, getAdqAccountList } = useModel('useAdMonitor.useMonitor')
  30. const { getPicherList } = useModel('useOperating.useWxGroupList')
  31. // 变量开始
  32. const [queryForm, setQueryForm] = useState<newListType>({ totalTimeUnit: 'day', planTimeUnit: 'hour', sysUserId: JSON.parse(sessionStorage.getItem('SYSUSERID') || '[]'), pageNum: 1, pageSize: 20 }) // 搜索变量//startTime: moment().format('YYYY-MM-DD'), endTime: moment().format('YYYY-MM-DD'),
  33. const { BarMonitor, LineMonitor } = useEcharts()
  34. const [barDis, setBarDis] = useState<any[]>([])
  35. const [lineDis, setLineDis] = useState<any[]>([])
  36. const [lineTitle, setLineTitle] = useState<string>('广告总消耗趋势')
  37. const [px, setPx] = useState<boolean>(false)//设置顶部图形的排列方式
  38. const [visible, setVisible] = useState<boolean>(false) // 详情弹窗控制
  39. const [aId, setAId] = useState<any>()
  40. const [showEacharts, setShowEacharts] = useState<boolean>(true)
  41. const [queryForHour, setQueryForHour] = useState<ListHourProps>({ pageNum: 1, pageSize: 20 })
  42. const [filterQuery, setFilterQuery] = useState<any>({})
  43. const [logVisible, setLogVisible] = useState<boolean>(false)
  44. const [adgroupId, setAdgroupId] = useState<string>('')
  45. const [adgroupName, setAdgroupName] = useState<string>('')
  46. const [accountIdRule, setAccountIdRule] = useState<string>('')
  47. const [trendColumns, setTrendColumns] = useState<string[]>(['cost'])
  48. const { totalTimeUnit, planTimeUnit, adgroup, accountId, sysUserId, groupAccountIds } = queryForm
  49. const configName = '起量广告排行明细3.0'
  50. const { getGroupList, groupListInit } = useModel('useLaunchAdq.useAdAuthorize')
  51. const syncBatch = useAjax((params) => syncBatchApi(params))
  52. useEffect(() => {
  53. groupListInit()
  54. }, [])
  55. useEffect(() => {
  56. getList()
  57. }, [queryForHour, filterQuery, queryForm?.sysUserId, queryForm?.accountId, queryForm?.adgroup, queryForm?.groupAccountIds])
  58. const getList = () => {
  59. let message = localStorage.getItem(`myAdMonitorConfig1.0.1_${configName}`)
  60. if (message) {
  61. message = JSON.parse(message)
  62. }
  63. let isAccountId = true
  64. let isAdgroupId = true
  65. let isAdgroupName = true
  66. let columns: string[] = []
  67. if (message && Array.isArray(message)) {
  68. message.forEach((item: { serverIndex: any; dataIndex: string; }) => {
  69. if (!['event'].includes(item.dataIndex)) {
  70. if (item.dataIndex === 'account_id') {
  71. isAccountId = false
  72. } else if (item.dataIndex === 'adgroup_id') {
  73. isAdgroupId = false
  74. } else if (item.dataIndex === 'adgroup_name') {
  75. isAdgroupName = false
  76. }
  77. columns.push(item?.serverIndex || 'adgroup_data.' + item.dataIndex)
  78. }
  79. })
  80. } else {
  81. qiliangpaihanghour.forEach((item: any) => {
  82. item?.data?.forEach((d: { default: any, serverIndex: string, dataIndex: string }) => {
  83. if (d.default && !['event'].includes(d.dataIndex)) {
  84. if (d.dataIndex === 'account_id') {
  85. isAccountId = false
  86. } else if (d.dataIndex === 'adgroup_id') {
  87. isAdgroupId = false
  88. } else if (item.dataIndex === 'adgroup_name') {
  89. isAdgroupName = false
  90. }
  91. columns.push(d?.serverIndex || 'adgroup_data.' + d.dataIndex)
  92. }
  93. })
  94. })
  95. }
  96. if (isAccountId) {
  97. columns.push('adgroup_data.account_id')
  98. }
  99. if (isAdgroupId) {
  100. columns.push('adgroup_data.adgroup_id')
  101. }
  102. if (isAdgroupName) {
  103. columns.push('adgroup_data.adgroup_name')
  104. }
  105. let params = { ...queryForHour, ...filterQuery }
  106. if (queryForm?.sysUserId) {
  107. params.sysUserIds = queryForm?.sysUserId
  108. }
  109. if (queryForm?.accountId && queryForm?.accountId?.length > 0) {
  110. params.accountIdStr = queryForm?.accountId.toString()
  111. }
  112. if (queryForm?.adgroup) {
  113. params.adgroupIdStr = queryForm?.adgroup
  114. }
  115. if (queryForm?.groupAccountIds) {
  116. params.groupAccountIds = queryForm?.groupAccountIds
  117. }
  118. params.columns = columns
  119. getListForHourV3.run(params)
  120. }
  121. // 获取投手
  122. useEffect(() => {
  123. !getPicherList.data && getPicherList.run()
  124. }, [])
  125. // 获取广告账号
  126. useEffect(() => {
  127. !getAdqAccountList.data && getAdqAccountList.run()
  128. }, [])
  129. // // 获取排行数据,柱图
  130. useEffect(() => {
  131. getPlanCostList()
  132. }, [totalTimeUnit, accountId, sysUserId, groupAccountIds])
  133. // 获取今日计划总消耗图谱,折线
  134. useEffect(() => {
  135. getTootalCostList()
  136. }, [planTimeUnit, adgroup, accountId, sysUserId, groupAccountIds, trendColumns])
  137. /** 获取折线图 */
  138. const getTootalCostList = useCallback(async () => {
  139. let { totalTimeUnit, planTimeUnit, pageNum, pageSize, adgroup, sysUserId, accountId, ...newQueryForm } = queryForm
  140. let params = adgroup ? { ...newQueryForm, adgroupIdStr: adgroup } : newQueryForm
  141. let res = await getCostTrendV3List.run({ ...params, timeUnit: planTimeUnit, sysUserIds: sysUserId, accountIdStr: accountId?.join(), trendColumns })
  142. let data = trendColumns.map((field) => {
  143. let value: any = {}
  144. res?.data?.forEach((item: any, index: number) => {
  145. if (index === 0) value.legendName = LineField[field];
  146. value[item?.trend_unit] = item?.[field]
  147. });
  148. return value
  149. })
  150. setLineDis(() => data)
  151. setLineTitle(() => `广告总${LineField[trendColumns[0]]}趋势`)
  152. }, [queryForm, lineDis, trendColumns])
  153. /** 获取柱状图 */
  154. const getPlanCostList = useCallback(async () => {
  155. let { totalTimeUnit, planTimeUnit, pageNum, pageSize, sysUserId, accountId, ...newQueryForm } = queryForm
  156. let { adgroup, ...planQueryFrom } = newQueryForm
  157. let res = await getCostTopV3List.run({ ...planQueryFrom, timeUnit: totalTimeUnit, sysUserIds: sysUserId, accountId: accountId?.join(), topN: 10 })
  158. let data = res?.data?.map((item: { adgroupId: number, cost: number, adgroupName: string, accountId: number }) => {
  159. return { name: item.adgroupId.toString(), value: item.cost, adName: item.adgroupName, accountId: item.accountId }
  160. })
  161. data = data?.sort((a: any, b: any) => {
  162. var value1 = a['value'];
  163. var value2 = b['value'];
  164. return value2 - value1;
  165. })
  166. setBarDis(() => data)
  167. }, [queryForm, barDis])
  168. // 详情
  169. const details = (data: any) => {
  170. setAId(data)
  171. setVisible(true)
  172. }
  173. // 计划详情
  174. const planDetail = (data: any) => {
  175. sessionStorage.setItem('ADIDORNAME', JSON.stringify(data))
  176. onChange && onChange()
  177. }
  178. //全部接口刷新
  179. const refresh = () => {
  180. getCostTrendV3List.refresh()
  181. getCostTopV3List.refresh()
  182. getListForHourV3.refresh()
  183. }
  184. // 接口自动刷新10分钟一次
  185. useEffect(() => {
  186. let time = setInterval(() => {
  187. refresh()
  188. }, 1000 * 60 * 10)
  189. return () => {
  190. clearInterval(time)
  191. }
  192. }, [])
  193. //图形排列样式改变重新获取数据刷新图形
  194. const set = useCallback((b) => {
  195. setPx(b)
  196. getCostTrendV3List.refresh()
  197. getCostTopV3List.refresh()
  198. }, [getCostTopV3List, getCostTrendV3List, trendColumns])
  199. // 处理折线图数据
  200. const timePickerHandle = async (values: any, formatString: [string, string]) => {
  201. let res = await getCostTrendV3List.data
  202. let data = trendColumns.map((field) => {
  203. let value: any = {}
  204. res?.data?.forEach((item: any, index: number) => {
  205. if (index === 0) value.legendName = LineField[field];
  206. value[item?.trend_unit] = item?.[field]
  207. });
  208. return value
  209. })
  210. if (values) {
  211. let date = moment().format('YYYY-MM-DD')
  212. let strTime = formatString[0]
  213. let endTime = formatString[1]
  214. let dateTimeStr = `${date} ${strTime}:00`
  215. let dateTimeEnd = `${date} ${endTime}:00`
  216. let newData: any[] = data.map(item => {
  217. let { legendName, ...otherData } = item
  218. let newItem: any = { legendName }
  219. for (const key in otherData) {
  220. if (Object.prototype.hasOwnProperty.call(otherData, key)) {
  221. const value = otherData[key];
  222. if (moment(dateTimeStr) <= moment(key) && moment(key) <= moment(dateTimeEnd)) {
  223. newItem[key] = value
  224. }
  225. }
  226. }
  227. return newItem
  228. })
  229. setLineDis(() => newData)
  230. } else {
  231. setLineDis(() => data)
  232. }
  233. }
  234. const log = (value: any) => {
  235. setAccountIdRule(value.account_id)
  236. setAdgroupId(value.adgroup_id)
  237. setAdgroupName(value.adgroup_name)
  238. setLogVisible(true)
  239. }
  240. const sync = (data: any) => {
  241. const hide = message.loading(`${data?.adgroup_name}广告同步中`, 0, () => {
  242. message.success('修改成功');
  243. });
  244. let accountAdgroupMaps = [data.account_id + ',' + data.adgroup_id]
  245. syncBatch.run({ accountAdgroupMaps }).then(res => {
  246. hide()
  247. getListForHourV3.refresh()
  248. message.success('同步完成!')
  249. }).catch(() => hide())
  250. }
  251. return <Space direction='vertical' style={{ width: '100%' }} className="monitor">
  252. <Card hoverable bodyStyle={{ padding: '12px 16px' }}>
  253. <div style={{ display: 'flex', justifyContent: 'space-between' }}>
  254. <Space>
  255. <Select
  256. showSearch
  257. value={queryForm.sysUserId}
  258. style={{ minWidth: 180, maxWidth: 250 }}
  259. mode='multiple'
  260. maxTagCount={1}
  261. allowClear
  262. placeholder="请选择投手"
  263. disabled={queryForm?.adgroup || queryForm?.accountId?.length > 0}
  264. onChange={(value: number[]) => {
  265. setQueryForm({ ...queryForm, sysUserId: value, pageNum: 1 })
  266. sessionStorage.setItem('SYSUSERID', value ? JSON.stringify(value) : '')
  267. }}
  268. filterOption={(input, option) =>
  269. (option?.children as any).toLowerCase().indexOf(input.toLowerCase()) >= 0
  270. }
  271. >
  272. {getPicherList?.data?.map((item: { nickname: string, userId: number }, index: number) =>
  273. <Select.Option
  274. value={item.userId}
  275. key={item.userId + '' + index}
  276. >
  277. {item.nickname}
  278. </Select.Option>
  279. )}
  280. </Select>
  281. <Select
  282. showSearch
  283. mode='multiple'
  284. maxTagCount={1}
  285. value={queryForm.accountId}
  286. style={{ minWidth: 220, maxWidth: 250 }}
  287. allowClear
  288. placeholder="请选择广告账号"
  289. onChange={(value: number[]) => {
  290. setQueryForm({ ...queryForm, accountId: value, pageNum: 1 })
  291. }}
  292. >
  293. {getAdqAccountList?.data?.data?.map((item: { id: number, accountId: number }) => <Select.Option
  294. value={item.accountId}
  295. key={item.id}
  296. >
  297. {item.accountId}
  298. </Select.Option>)}
  299. </Select>
  300. <Input
  301. value={queryForm?.accountId?.toString()}
  302. placeholder="输入广告账号"
  303. onChange={(e) => {
  304. setQueryForm({ ...queryForm, accountId: e.target.value ? e.target.value?.split(/[,,\s\n]+/) : undefined })
  305. }}
  306. allowClear
  307. />
  308. <Input
  309. value={queryForm.adgroup}
  310. placeholder="广告ID"
  311. onChange={(e) => {
  312. setQueryForm({ ...queryForm, adgroup: e.target.value })
  313. }}
  314. allowClear
  315. />
  316. <Select
  317. showSearch
  318. mode='multiple'
  319. maxTagCount={1}
  320. value={queryForm.groupAccountIds}
  321. style={{ minWidth: 150 }}
  322. allowClear
  323. placeholder="请选择账号分组"
  324. onChange={(value: number[]) => {
  325. setQueryForm({ ...queryForm, groupAccountIds: value, pageNum: 1 })
  326. }}
  327. >
  328. {getGroupList?.data?.map((item: { groupId: number, groupName: number }) => <Select.Option
  329. value={item.groupId}
  330. key={item.groupId}
  331. >
  332. {item.groupName}
  333. </Select.Option>)}
  334. </Select>
  335. </Space>
  336. <Space>
  337. <Tag onClick={() => setShowEacharts(!showEacharts)}>{showEacharts ? <><EyeInvisibleOutlined /> 隐藏</> : <><EyeOutlined /> 显示</>}</Tag>
  338. <Tag color="#2db7f5" onClick={refresh}><RedoOutlined /> 刷新</Tag>
  339. </Space>
  340. </div>
  341. </Card>
  342. {showEacharts && <Card hoverable bodyStyle={{ padding: '12px 16px' }}>
  343. <span style={{ position: 'absolute', top: 10, zIndex: 10 }}>
  344. {px ?
  345. <Tooltip title='左右排列'><Tag color='#f50' onClick={() => { set(false) }}><ColumnWidthOutlined /><span style={{ fontSize: 10 }}>左右排列</span></Tag></Tooltip>
  346. :
  347. <Tooltip title='上下排列'><Tag color='#f50' onClick={() => { set(true) }} ><ColumnHeightOutlined /><span style={{ fontSize: 10 }}>上下排列</span></Tag></Tooltip>
  348. }
  349. </span>
  350. <div className={!px ? 'charts' : 'charts charts100'}>
  351. <div>
  352. <div className="selectTime">
  353. <Space>
  354. <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getCostTopV3List?.data?.reqTime}</span>
  355. <Radio.Group value={queryForm.totalTimeUnit} buttonStyle="solid" size='small' onChange={(e) => { setQueryForm({ ...queryForm, totalTimeUnit: e.target.value }) }}>
  356. <Radio.Button value="total">总</Radio.Button>
  357. <Radio.Button value="day">天</Radio.Button>
  358. <Radio.Button value="hour">小时</Radio.Button>
  359. <Radio.Button value="minute">5min</Radio.Button>
  360. </Radio.Group>
  361. </Space>
  362. </div>
  363. {getCostTopV3List?.loading ? <Spin /> : <BarMonitor style={{ width: '100%', height: '100%' }} data={barDis} xName="今日消耗" yName="广告名称" onChange={(value: string, accountId) => { console.log(value, accountId); setQueryForm({ ...queryForm, adgroup: value }) }} planID={queryForm?.adgroup} />}
  364. </div>
  365. <div>
  366. <div className="selectTime">
  367. <Space>
  368. <span style={{ fontSize: 10, color: '#999' }}>刷新时间:{getCostTrendV3List?.data?.reqTime}</span>
  369. <Radio.Group value={queryForm.planTimeUnit} buttonStyle="solid" size='small' onChange={(e) => { setQueryForm({ ...queryForm, planTimeUnit: e.target.value }) }}>
  370. <Radio.Button value="hour">小时</Radio.Button>
  371. <Radio.Button value="minute">5min</Radio.Button>
  372. </Radio.Group>
  373. {queryForm.planTimeUnit === 'minute' && <TimePicker.RangePicker
  374. size="small"
  375. format='HH:mm'
  376. minuteStep={5}
  377. onChange={timePickerHandle}
  378. />}
  379. <Select
  380. showSearch
  381. mode='multiple'
  382. maxTagCount={1}
  383. value={trendColumns}
  384. style={{ minWidth: 130 }}
  385. allowClear
  386. placeholder="请选择图表字段"
  387. onChange={(value: string[]) => {
  388. setTrendColumns(value?.length ? value : ['cost'])
  389. }}
  390. size="small"
  391. >
  392. {Object.keys(LineField).map((key) => <Select.Option value={key} key={key}>
  393. {LineField[key]}
  394. </Select.Option>)}
  395. </Select>
  396. </Space>
  397. </div>
  398. {getCostTrendV3List?.loading ? <Spin /> : <LineMonitor style={{ width: '100%', height: '100%' }} series smooth data={lineDis} title={trendColumns?.length > 1 ? undefined : lineTitle} />}
  399. </div>
  400. </div>
  401. </Card>}
  402. <div className={'MYtable'}>
  403. <TableData
  404. refreshData={getList}
  405. bodyStyle={{ padding: '12px 16px' }}
  406. gutter={[0, 12]}
  407. columns={columnsMonitor(planDetail, details, (value) => { setQueryForm({ ...queryForm, adgroup: value }); }, log, sync)}
  408. dataSource={getListForHourV3?.data?.data?.records}
  409. loading={getListForHourV3?.loading}
  410. ajax={getListForHourV3}
  411. leftChild={
  412. <Space>
  413. <FilterQuery onChange={(data) => {
  414. setFilterQuery(data)
  415. }} />
  416. </Space>
  417. }
  418. myKey={'adgroup_id'}
  419. fixed={{ left: 0, right: 2 }}
  420. total={getListForHourV3?.data?.data?.total}
  421. onChange={(props: any) => {
  422. let { sortData, pagination } = props
  423. let { current, pageSize } = pagination
  424. let newQueryForm = JSON.parse(JSON.stringify(queryForHour))
  425. newQueryForm.pageNum = current
  426. newQueryForm.pageSize = pageSize
  427. if (sortData && JSON.stringify('sortData') !== '{}') {
  428. let { field, order } = sortData // descend 降序 大到小 ascend 升序 小到大
  429. if (order) {
  430. newQueryForm.sortColumn = field
  431. newQueryForm.sortAsc = order === 'ascend'
  432. } else {
  433. Object.keys(newQueryForm).forEach(key => {
  434. if (key === 'sortColumn' || key === 'sortAsc') {
  435. delete newQueryForm[key]
  436. }
  437. })
  438. }
  439. } else {
  440. Object.keys(newQueryForm).forEach(key => {
  441. if (key === 'sortField' || key === 'sort') {
  442. delete newQueryForm[key]
  443. }
  444. })
  445. }
  446. setQueryForHour({ ...newQueryForm })
  447. }}
  448. page={queryForHour.pageNum}
  449. pageSize={queryForHour.pageSize}
  450. scroll={{ y: 750 }}
  451. config={qiliangpaihanghour}
  452. configName={configName}
  453. />
  454. </div>
  455. {visible && <Details visible={visible} onClose={() => { setVisible(false) }} data={aId} />}
  456. {logVisible && <RuleAccountLog accountId={accountIdRule} adgroupName={adgroupName} adgroupId={adgroupId} visible={logVisible} onClose={() => setLogVisible(false)} />}
  457. </Space>
  458. }
  459. export default React.memo(Monitor)