index.jsx 21.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
import React, { useState, useEffect } from "react"
import { Tabs, Form, Select, Badge, Button, DatePicker, Slider, InputNumber, Table, Radio, Row, Col, Tree, Card, Spin, TreeSelect } from "antd"
import classNames from "classnames"
import { connect, useAccess, Access } from 'umi'
import { CheckOutlined, CloseOutlined, DownloadOutlined, LineChartOutlined, TableOutlined } from "@ant-design/icons"
import moment from "moment";
import IEcharts from 'react-echarts-v3/src/full.js';
import { dispatchHandle } from '@/utils/publicHandle';
import useFormTable from '@/useHooks/useFormTable';
import ExportFile from '@/components/Custom/ExportFile';

import utilsStyles from '@/utils/utils.less';
import HeaderTabs from "./components/HeaderTabs"
import SlideTree from "./components/SlideTree"
import { chartData, generateList } from "./components/chartData"
import MeterGroupTree from "./components/MeterGroupTree"
import CustormRangePicker from '@/components/CustormRangePicker';
import _ from 'lodash'

import style from "./index.less"

const { TabPane } = Tabs
const { Option } = Select
const { RangePicker } = DatePicker
let number = 1;

const ParamQuery = (props) => {
    const {
        dispatch,
        loading,
        treeLoading,
    } = props;
    const access = useAccess();
    const [form] = Form.useForm()
    const [dateSelect, setDateSelect] = useState([moment().startOf('day').valueOf(), moment().endOf('day').valueOf()]); // 日期区间选择
    const [groupBy, setGroupBy] = useState('hour');
    const [deviceId, setDeviceId] = useState()
    const [meterTrendLineList, setMeterTrendLineList] = useState([])
    const [option, setOption] = useState({})
    const [meterArr, setMeterArr] = useState([]) // 选中的属性
    const [duration, setDuration] = useState(0)
    const [groupInterval, setGroupInterval] = useState(1)
    const [meterGroupList, setMeterGroupList] = useState([])
    const groupBySelect = [
        // { label: '秒', value: 'second' },
        { label: '分钟', value: 'minute' },
        { label: '小时', value: 'hour' },
        { label: '日周期', value: 'day' },
        { label: '月周期', value: 'month' },
        { label: '年周期', value: 'year' },
    ]
    const chartsTabs = [{ name: "曲线", icon: <LineChartOutlined /> }, { name: "表格", icon: <TableOutlined /> }]
    const ParamsBgColor = ['#5470c633', '#91cc7533', '#fac85833', '#ee666633', '#73c0de33', '#3ba27233', '#fc845233', '#9a60b433', '#ea7ccc33']
    const ParamsFontColor = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
    const dateList = [{ name: "今天", num: 0 }, { name: "7天", num: 7 }, { name: "30天", num: 30 }, { name: "60天", num: 60 }]
    const colorArr = (index) => {
        const num = index % 9
        return {
            bg: ParamsBgColor[num],
            color: ParamsFontColor[num],
        };
    }
    // 表格columns
    const columnsData = (data) => {
        if (data && data.length > 0) {
            const columns = data.map((i, j) => ({
                title: i.name,
                dataIndex: j
            }))
            columns.unshift({
                title: '时间',
                dataIndex: 'time',
                key: 'time'
            })
            return columns;
        }
    }
    // 表格数据...表格columns
    const createTableData = (data) => {
        if (data?.length === 0) return [];
        if (!data || data?.length === 0) return { columns: [], dataSource: [] };
        const dateRange = data[0].trendIndexList;
        const columns = [
            { title: '时间', dataIndex: 'time' },
        ]
        data.forEach((item, index) => {
            columns.push({
                title: `${item.name} ${item.unit ? ` ( ${item.unit} ) ` : ''}`,
                dataIndex: `data-${index}`
            })
        })
        const dataSource = dateRange?.length > 0 && dateRange.map((item, index) => {
            const dataGroup = {};
            data.forEach((child, index2) => {
                dataGroup[`data-${index2}`] = data[index2]?.trendIndexList[index]?.yvalue
            })
            return {
                id: index,
                time: item.xvalueText,
                ...dataGroup
            }
        })
        return {
            columns,
            dataSource
        }
    }
    const tableRows = createTableData(meterTrendLineList || []);
    const getTrendLinesList = (payload = {}) => {
        dispatchHandle(
            dispatch,
            'monitor/device_service_meter_data_trend_lines_post',
            payload,
            res => {
                if (res) {
                    setMeterTrendLineList(res)
                    setOption(chartData(res))
                    number += 1;
                }
            }
        )
    }
    // 侧边栏列表请求
    const [slideTreeList, setSlideTreeList] = useState([])
    const requestSlideTreeList = (payload = {}) => {
        dispatchHandle(
            dispatch,
            // 'monitor/device_service_system_node_tree_meter_post',
            'monitor/device_service_system_node_tree_device_meter_post',
            { systemId: payload.id },
            res => {
                console.log(res)
                setSlideTreeList(res || [])
            }
        )
    }
    // 头部系统切换
    const [systemSelect, setSystemSelect] = useState()
    const systemChange = (key) => {
        console.log(key)
        requestSlideTreeList({ id: key })
        setSystemSelect(key)
        number += 1;
        setMeterGroupList([])
    }
    // 侧边栏
    const deviceSelect = (data) => {
        setMeterGroupList([])
        let payload = {};
        const res = typeof data.key;
        if (res === 'number') {
            setDeviceId(data.key)
            payload = {
                deviceId: data.key
            }
        } else if (data.key) {
            const deviceIdArr = data?.key?.split('-')
            if (deviceIdArr?.length > 0) {
                setDeviceId(deviceIdArr[1])
                payload = {
                    deviceId: deviceIdArr[1]
                }
            }
        }
        dispatchHandle(
            dispatch,
            'monitor/device_service_meter_attr_attr_group_by_device_id_deviceId_get',
            payload,
            (result) => {
                if (result) {
                    setMeterGroupList(result)
                }
            }
        )
        form.resetFields()
        form.setFieldsValue({
            date: [moment(), moment()],
            // groupBy: 'hour'
        })
        setOption({})
        setDuration(0)
        setGroupBy('hour')
        setMeterArr([])
        number += 1;
    }
    // 日期区间选中 今天 7天 30天 60天
    const dateChange = (e) => {
        setDuration(e.target.value)
        setDateSelect([moment().subtract(e.target.value, 'days'), moment()])
        form.setFieldsValue({
            date: [moment().subtract(e.target.value, 'days'), moment()]
        })
        if (meterArr.length > 0) {
            const arr = meterArr.map(item => item.id)
            getTrendLinesList({
                meterAttrIds: arr,
                analysis: {
                    endTimestamp: moment().endOf('day').valueOf(),
                    startTimestamp: moment().subtract(e.target.value, 'days').startOf('day').valueOf(),
                    groupBy,
                    groupInterval: (groupBy === 'day' || groupBy === 'month' || groupBy === 'year') ? 1 : groupInterval
                }
            })
        }
    }
    // 日期选择
    const rangeChange = (values) => {
        setDateSelect(values)
        if (meterArr.length > 0) {
            const arr = meterArr.map(item => item.id)
            getTrendLinesList({
                meterAttrIds: arr,
                analysis: {
                    endTimestamp: moment(values[1]).endOf('day').valueOf(),
                    startTimestamp: moment(values[0]).startOf('day').valueOf(),
                    groupBy,
                    groupInterval: (groupBy === 'day' || groupBy === 'month' || groupBy === 'year') ? 1 : groupInterval
                }
            })
        }
    }
    // 显示频率
    const groupByChange = (value) => {
        setGroupBy(value)
        if (meterArr.length > 0) {
            const arr = meterArr.map(item => item.id)
            getTrendLinesList({
                meterAttrIds: arr,
                analysis: {
                    endTimestamp: moment(dateSelect[1]).endOf('day').valueOf(),
                    startTimestamp: moment(dateSelect[0]).startOf('day').valueOf(),
                    groupBy: value || 'hour',
                    groupInterval: (value === 'day' || value === 'month' || value === 'year') ? 1 : groupInterval
                }
            })
        }
    }
    // 显示频率实际天数
    const groupIntervalChange = (value) => {
        console.log(value)
        setGroupInterval(value)
        if (meterArr.length > 0) {
            const arr = meterArr.map(item => item.id)
            getTrendLinesList({
                meterAttrIds: arr,
                analysis: {
                    endTimestamp: moment(dateSelect[1]).endOf('day').valueOf(),
                    startTimestamp: moment(dateSelect[0]).startOf('day').valueOf(),
                    groupBy,
                    groupInterval: value || 1
                }
            })
        }
    }
    // 属性
    const selectParams = (value) => {
        let meterArray = []
        // setMeterArr([])
        value?.forEach(id => {
            if (id && id?.split('-')?.length > 1) { // 选中父级
                const array = meterGroupList?.filter(item => item?.id === parseInt(id?.split('-')[1], 10))
                if (array?.length > 0) {
                    meterArray = [...meterArray, ...array[0]?.meterAttrList]
                }
            } else if (id && id?.split('-')?.length === 1) {// 选中子级
                const list = generateList(meterGroupList, [])
                const index = list?.findIndex(item => item?.id === parseInt(id, 10))
                if (index || index === 0) {
                    meterArray.push(list[index])
                }
            }
        })
        const array = _.unionBy(meterArray, 'id');
        const arr = array.map(item => item.id)
        setMeterArr(array)
        console.log(meterArray, arr, array)
        getTrendLinesList({
            meterAttrIds: arr,
            analysis: {
                endTimestamp: moment(dateSelect[1]).endOf('day').valueOf(),
                startTimestamp: moment(dateSelect[0]).startOf('day').valueOf(),
                groupBy,
                groupInterval: (groupBy === 'day' || groupBy === 'month' || groupBy === 'year') ? 1 : groupInterval
            }
        })
    }
    // 图表tab切换
    const [chartIndex, setChartIndex] = useState('曲线');
    const chartsTabsChange = (activeKey) => {
        setChartIndex(activeKey)
        number += 1;
    }
    const deleteParamsAction = (child) => { // 删除属性
        const arr = meterArr.filter((item, index) => index !== child)
        setMeterArr(arr)
        const array = arr.map(item => item.id)
        getTrendLinesList({
            meterAttrIds: array,
            analysis: {
                endTimestamp: moment(dateSelect[1]).endOf('day').valueOf(),
                startTimestamp: moment(dateSelect[0]).startOf('day').valueOf(),
                groupBy,
                groupInterval: (groupBy === 'day' || groupBy === 'month' || groupBy === 'year') ? 1 : groupInterval
            }
        })
    }
    /**
     * @页面初始化
     */
    useEffect(() => {
        dispatchHandle(// 系统树
            dispatch,
            'monitor/device_service_system_tree_post',
            {},
            res => {
                if (res && res.length > 0) {
                    requestSlideTreeList({ id: res[0].id })
                }
            }
        )
        form.setFieldsValue({
            date: [moment(), moment()],
            // groupBy: 'hour'
        })
    }, [])
    const compare = (item) => {
        return (a, b) => {
            const value1 = a[item];
            const value2 = b[item];
            return value1 - value2;
        }
    }
    console.log(option)
    return <Form form={form} className={classNames(utilsStyles.disFlexCol, utilsStyles.fullContainer)}>
        <HeaderTabs systemChange={systemChange} setSystemSelect={setSystemSelect} />
        <Row key={systemSelect} className={style.param_query} style={{ alignItems: 'stretch' }}>
            <Col md={{ span: 6 }} xxl={{ span: 4 }}>
                <SlideTree data={slideTreeList || []} onSelect={deviceSelect} loading={treeLoading} />
                {/* <MeterTree data={slideTreeList || []} onSelect={deviceSelect} loading={treeLoading}/> */}
            </Col>
            <Col md={{ span: 18 }} xxl={{ span: 20 }}>
                <div style={{ width: '100%', height: '100%' }}>
                    <div className={style.params_select}>
                        <Col md={{ span: 10 }} xxl={{ span: 8 }}>
                            <Form.Item label="选择参数" name="param">
                                <MeterGroupTree
                                    treeData={meterGroupList}
                                    selectParams={selectParams}
                                />
                            </Form.Item>
                        </Col>
                    </div>
                    <div className={style.params_query_content} style={{ height: '91%' }}>
                        <header>
                            <p>已选参数:</p>
                            <ul>
                                {
                                    meterArr && meterArr?.length > 0 &&
                                    meterArr?.
                                        map((item, index) => (
                                            <li key={index} style={{ margin: '0 20px 5px 0' }}>
                                                <Badge
                                                    count={<CloseOutlined onClick={() => deleteParamsAction(index)} style={{ color: '#fff', cursor: 'pointer' }} />}
                                                    style={{ backgroundColor: '#ff4d4f', borderRadius: '50%' }}
                                                    offset={[-7, 0]}
                                                >
                                                    <Button
                                                        style={{ color: colorArr(index).color, backgroundColor: `${colorArr(index).bg}`, border: `1px solid ${colorArr(index).color}`, borderRadius: '16px' }}
                                                    >
                                                        {item?.name || ''}
                                                    </Button>
                                                </Badge>
                                            </li>
                                        ))
                                }
                            </ul>
                        </header>
                        <Row justify="space-between" className={style.date_select}>
                            <Col md={{ span: 14 }} xxl={{ span: 10 }} className={style.duration_time}>
                                <Radio.Group onChange={dateChange} value={duration}>
                                    {
                                        dateList.map((i, j) => {
                                            return <Radio.Button key={i.name} value={i.num}>{i.name}</Radio.Button>
                                        })
                                    }
                                </Radio.Group>
                                <Form.Item name="date">
                                    <CustormRangePicker
                                        style={{ width: '12.77vw' }}
                                        key={number}
                                        onChange={rangeChange}
                                        allowClear={false}
                                    />
                                </Form.Item>
                            </Col>
                            <Col
                                md={{ span: 10 }}
                                xxl={{ span: 7 }}
                                style={{ display: 'flex', alignItems: 'center' }}
                            >
                                <Form.Item name="groupBy" label="显示频率" style={{ width: '100%' }} className={style.group_by}>
                                    {
                                        (groupBy === 'hour' || groupBy === 'minute') && (
                                            <InputNumber
                                                onChange={groupIntervalChange}
                                                max={(groupBy === 'hour' && 24) || (groupBy === 'minute' && 60)}
                                                min={1}
                                                style={{ marginRight: 16 }}
                                                value={groupInterval}
                                            />
                                        )
                                    }
                                    <Select
                                        placeholder="请选择"
                                        allowClear
                                        style={{ width: '100%' }}
                                        value={groupBy}
                                        onChange={groupByChange}
                                    >
                                        {
                                            groupBySelect.map(i => (
                                                <Option value={i.value} key={i.value}>{i.label}</Option>
                                            ))
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col>
                                <ExportFile
                                    url="/device-service/meter-data/trend-lines/export-excel"
                                    data={{
                                        analysis: {
                                            startTimestamp: moment(dateSelect[0]).startOf('day').valueOf(),
                                            endTimestamp: moment(dateSelect[1]).endOf('day').valueOf(),
                                            groupBy,
                                            groupInterval,
                                        },
                                        meterAttrIds: meterArr.map(item => item?.id)
                                    }}
                                >
                                    <Access accessible={access.insideAccess('pVkpMjnWVRd')}>
                                        <Button style={{ color: '#4A90E2' }} type="link" icon={<DownloadOutlined />}>导出记录</Button>
                                    </Access>

                                </ExportFile>
                            </Col>
                        </Row>
                        <Tabs onChange={chartsTabsChange}>
                            {
                                chartsTabs.map(i => {
                                    return <TabPane
                                        key={i.name}
                                        tab={<span>
                                            {i.icon}
                                            {i.name}
                                        </span>}
                                    />
                                })
                            }
                        </Tabs>
                        {
                            chartIndex === '曲线' ?
                                (
                                    <Spin
                                        spinning={loading || false}
                                    >
                                        <IEcharts
                                            key={number}
                                            option={option}
                                            style={{ width: "100%", height: "51.50vh", paddingTop: "0.86vw" }}
                                        />
                                    </Spin>
                                )
                                :
                                <Table
                                    loading={loading}
                                    key={chartIndex}
                                    columns={tableRows.columns}
                                    dataSource={tableRows.dataSource}
                                    pagination={{
                                        pageSize: 7
                                    }}
                                    style={{ marginTop: 7 }}
                                    rowKey={record => record?.time}
                                />
                        }
                    </div>
                </div>
            </Col>
        </Row>
    </Form>
}

export default connect(({ monitor, loading }) => ({
    monitor,
    loading: loading.effects['monitor/device_service_meter_data_trend_lines_post'],
    treeLoading: loading.effects['monitor/device_service_system_tree_post']
}))(ParamQuery);