
import React, {  useState, useEffect,useRef } from "react";
import { connect } from "react-redux";
import moment from 'moment';
import { Form, Tooltip, Select, Checkbox, Modal, Input, Button, Switch, DatePicker, Row } from "@douyinfe/semi-ui";
import {IconLineChartStroked} from "@douyinfe/semi-icons"
import { TimeAbnValueLineChart } from '../components/TimeAbnValueLineChart';
import PropTypes from 'prop-types';





const TrendModal = (props) => {
    const { modalData,dispatch,actions,sensorId, closeModal, visible,project } = props
    const{install}=actions
    const [currStartTime, setCurrStartTime] = useState(moment().add('days', -1).format('YYYY-MM-DD HH:mm:ss'))
    const [currEndTime, setcurrEndTime] = useState(moment().format('YYYY-MM-DD HH:mm:ss'))
    const form = useRef()
    //初始化
    useEffect(() => {
    }, [])
    const checkPoint = (rule, value) => {
        const pattern = /^[1-9]*[1-9][0-9]*$/;
        if (pattern.test(value) && value != 1) {
            return true
        }
        return false
    }
    const checkNumber = (rule, val) => {
        const strRegex = /^-?\d+(\.\d+)?$/
        if (strRegex.test(val)) {
            return true
        }
        return false



    }
    const btnFormSubmit = () => {
        let data = modalData
        form.current.validate().then(value=>{
            let paramJson = {
                "thr_burr": Number(value.burr),//毛刺阈值
                "win_med": Number(value.ws),//滑动中值
                "win_avg": Number(value.rc),//滑动均值
                "thr_der": Number(value.dv), //导数阈值
                "win_grad": Number(value.pn),//渐变点个数
                "thr_grad": Number(value.gv),//渐变阈值
                "days_Last": Number(value.timeRange),//分析时长
            }
            let pushData = {
                station: data.sensorId,//测点
                factorId: data.factorId,
                itemId: data.itemIndex,
                abnType: 3,//异常趋势
                enabled: value.checked,
                params: paramJson
            };
            dispatch(install.editAbnParams(data.id,pushData)).then(res => {
                if (res.success) {
                    const id=[...sensorId?.map(item=>project+'-'+item), -1].join(',')
                    dispatch(install.getAbnParamList({ sensorId:id}))
                    closeModal()
                }
            })
        })
    }
    const checkInterger = (rule, val) => {
        // if(val){
        const strRegex = /^[1-9]*[1-9][0-9]*$/
        if (strRegex.test(val)) {
            return true
        }
        return false
        // }

    };
    const timeOnChange = (dates, dateStrings) => {
        if (dates.length == 0) {
            setCurrStartTime(null)
            setCurrEndTime(null)
            return Notification.warning({
                content: `请选择时间`,
                duration: 3,
            })
        }
        setCurrStartTime(dates[0].format('YYYY-MM-DD HH:mm:ss'))
        setCurrEndTime(dates[1].format('YYYY-MM-DD HH:mm:ss'))
    }
    //数据对比
    // const dataCompare = () => {
    //     this.props.form.validateFields((err, values) => {
    //         if (!err) {
    //             let paramJson = {
    //                 "thr_burr": values.burr,//毛刺阈值
    //                 "win_med": values.ws,//滑动中值
    //                 "win_avg": values.rc,//滑动均值
    //                 "thr_der": values.dv, //导数阈值
    //                 "win_grad": values.pn,//渐变点个数
    //                 "thr_grad": values.gv,//渐变阈值
    //                 "days_Last": values.timeRange,//分析时长
    //             }
    //             let data = {
    //                 station: this.props.modalData.stationId,
    //                 factorId: this.props.modalData.factorId,
    //                 itemId: this.props.modalData.itemId,
    //                 abnType: 'trend',//算法类型
    //                 enabled: true,
    //                 params: paramJson
    //             };
    //             let start = this.state.currStartTime;
    //             let end = this.state.currEndTime;
    //             this.props.dispatch(getItemAbnResult_tr(this.props.structId, start, end, data)).then(res => {
    //             })
    //         }
    //     });
    // }

    // let originalData = ['还没查询'], calcArray = [], key, itemName, start, end;
    // let stationsData = [];
    // if (abnItemCompData) {
    //     originalData = abnItemCompData.stationData;
    //     calcArray = abnItemCompData.resultArray;
    //     key = abnItemCompData.itemKey;
    //     itemName = abnItemCompData.itemName;
    //     start = originalData && originalData.length > 0 ? originalData[0].time : '';
    //     end = originalData && originalData.length > 0 ? originalData[originalData.length - 1].time : '';

    //     for (let i = 0; i < originalData.length; i++) {
    //         let one = { name: itemName + "（单位：" + abnItemCompData.unit + "）", value: originalData[i][key], time: originalData[i].time };
    //         stationsData.push(one);
    //     }
    //     if (calcArray) {
    //         let preLineData = calcArray.calcPreprocess;
    //         let abnTrends = calcArray.calcFinal;
    //         for (let j = 0; j < preLineData.length; j++) {
    //             let one = { name: "预处理+滑动均值后数据", value: preLineData[j].value, time: preLineData[j].time };
    //             stationsData.push(one);
    //         }
    //         for (let t = 0; t < abnTrends.length; t++) {
    //             let name = abnTrends[t].startTime + "至" + abnTrends[t].endTime + abnTrends[t].des + "，渐变差值：" + abnTrends[t].value.toFixed(2) + abnItemCompData.unit;
    //             let start = { name: name, value: abnTrends[t].startValue, time: abnTrends[t].startTime };
    //             let end = { name: name, value: abnTrends[t].endValue, time: abnTrends[t].endTime };
    //             stationsData.push(start);
    //             stationsData.push(end);
    //         }
    //     }
    // }
    TrendModal.propTypes = {
        visible: PropTypes.bool.isRequired,
        closeModal: PropTypes.func.isRequired
    };

    return <div>
        <Modal title="异常参数编辑" maskClosable={false} visible={visible} onCancel={closeModal} width={1000}
            footer={[<div>
                <Button type="primary" theme='borderless' htmlType="submit" onClick={btnFormSubmit}>保存</Button>
                <Button key="cancel" onClick={closeModal}>关闭</Button>
            </div>]}>
            <Form getFormApi={formApi => {
                form.current = formApi
            }}             labelPosition='left'

            >
                <Row>
                    <Form.Input label='测点位置' field='stationName'
                        rules={[{ required: true, message: '测点位置' }]}
                        disabled={true}
                        initValue={modalData.sensorName}
                    >
                    </Form.Input>
                    <Form.Input label='监测因素' field='factorName'
                        rules={[{ required: true, message: '监测因素' }]}
                        disabled={true}
                        initValue={modalData.factorName}
                    >
                    </Form.Input>
                    <Form.Switch label='是否启用' field='checked'
                        rules={[{ required: true, message: '是否启用' }]}
                        initValue={modalData.enabled}
                    >
                    </Form.Switch>

                    <Form.Select showSearch filter label="分析时长" field="timeRange" 
                        placeholder="请选择分析时长" style={{ width: 127, marginBottom: 0 }}
                        initValue={modalData.params.days_Last}  rules={[{
                            required: true, message: "请选择分析时长"
                        }]}
                        >
                        <Select.Option value="1">1个月</Select.Option>
                        <Select.Option value="2">2个月</Select.Option>
                        <Select.Option value="3">3个月</Select.Option>
                    </Form.Select>
                </Row>

                <Row style={{ marginTop: 18 }}>
                    <Form.Input
                    initValue={ modalData.params.thr_burr}
                        field='burr'
                        placeholder="毛刺阈值：数字" label="毛刺阈值"
                        rules={[{
                            required: true, message: "请输入正整数", validator: checkInterger
                        }]} t
                        trigger='blur' />
                    <Form.Input
                    initValue={ modalData.params.win_med}
                        field='ws'
                        placeholder="滑动中值：正值" label="滑动中值"
                        rules={[{
                            required: true, message: "请输入正整数", validator: checkInterger
                        }]}
                        trigger='blur' />
                    <Form.Input
                        field='rc'
                        initValue={ modalData.params.win_avg}
                        placeholder="滑动均值：正值" label="滑动均值"
                        rules={[{
                            required: true, message: "请输入正整数", validator: checkInterger
                        }]}
                        trigger='blur' />
                </Row>
                <Row style={{ marginTop: 18 }}>
                    <Form.Input
                        field='dv'
                        initValue={modalData.params.thr_der}
                        placeholder="导数阈值：数字" label="导数阈值"
                        rules={[{
                            required: true, message: "请输入数字", validator: checkNumber
                        }]}
                        trigger='blur' />
                    <Form.Input
                        field='pn'
                        initValue={modalData.params.win_grad}
                        placeholder="渐变点个数：正值" label="渐变点数"
                        rules={[{
                            required: true, message: "请输入大于1的正整数", validator: checkPoint
                        }]}
                        trigger='blur' />

                    <Form.Input
                        field='gv'
                        initValue={modalData.params.thr_grad}
                        placeholder="渐变阈值：数字" label="渐变阈值"
                        rules={[{
                            required: true, message: "请输入数字", validator: checkNumber
                        }]} trigger='blur'
                        />

                </Row>
                <Row style={{ marginTop: 28 }}>
                    <Form.DatePicker
                        placeholder={['开始时间', '结束时间']}
                        field="timeSelected"
                        label="查询时间"
                        initValue={[moment().subtract(24, 'hours').format('YYYY-MM-DD HH:mm:ss'), moment().format('YYYY-MM-DD HH:mm:ss')]}
                        type="dateTimeRange" density="compact"
                        onChange={timeOnChange}
                    />

                    {/* <Button size='default' type="primary" onClick={dataCompare}>数据对比</Button> */}
                </Row>

                {/* <div className="data-chart-container">
                    {originalData && originalData[0] == '还没查询' ?
                        <div style={{ margin: '30px 0' }}><IconLineChartStroked/> 输入参数，点击数据对比展示数据对比图</div>
                        :
                        originalData && originalData[0] != '还没查询' && originalData.length > 0 ?
                            <TimeAbnValueLineChart contentType={'trend'} data={stationsData} width={300} height={300}
                                itemName={itemName} configs={{ slider: { start: start, end: end } }} />
                            :
                            <div style={{ margin: '30px 0' }}><IconLineChartStroked/> 没有查询到任何有效数据！</div>}
                </div> */}

            </Form>
        </Modal>
    </div>;
}

function mapStateToProps(state) {
    const { abnItemState_tr, global} = state;
    return {
        abnItemCompData: abnItemState_tr.items,
        actions:global.actions
    }
}

export default connect(mapStateToProps)(TrendModal)
