import React, { useState, useRef, useEffect } from "react";
import { connect } from "react-redux";
import { Modal, Form, Notification } from "@douyinfe/semi-ui";
import { IconAlertCircle } from '@douyinfe/semi-icons';
import './pushModal.less'


function pushModal (props) {
    const {
        close,
        cancel,
        visible,
        dispatch,
        pepList,
        actions,
        pushEdit,//是否是编辑
        editObj,
        user
    } = props;
    const { service } = actions;
    const form = useRef();//表单
    const [abnormal, setAbnormal] = useState(false); //异常率推送机制disable
    const [usersList, setUsersList] = useState([]); //获取全部未删除用户
    const [structure, setStructure] = useState(true); //结构物disable
    const [projectPoms, setProjectPoms] = useState([]); //获取已绑定项目
    const [projectStructure, setProjectStructure] = useState([]); //获取绑定项目下结构物
    const [timeTypeDis, setTimeTypeDis] = useState(true); //通知时效disable
    const [projectStatus, setProjectStatus] = useState([]); //获取项目状态列表
    const timeTypePOMS = useRef([]);//表单

    const [interval1, setInterval1] = useState(undefined); //
    const [interval2, setInterval2] = useState(undefined); //
    const [interval3, setInterval3] = useState(undefined); //
    const [deviceProportion, setDeviceProportion] = useState(undefined); //




    //初始化
    useEffect(() => {
        getOrganizationUsersList()//获取全部未删除用户
        getProjectPomsList()//获取已绑定项目
        if (editObj.id) {
            getProjectStructureList(editObj.pomsProjectId)
            if (editObj.pomsProject?.pepProjectId) {
                getProjectStatusList()//获取项目状态列表
            }
            else {
                setProjectStatus([{ construction_status: 'POMS', id: 'POMS' }])
                timeTypePOMS.current = ['POMS']
            }
            if (editObj.tactics == 'immediately') {
                setInterval1(editObj.tacticsParams?.interval)
            } else if (editObj.tactics == 'continue') {
                setInterval2(editObj.tacticsParams?.interval)
            } else if (editObj.tactics == 'abnormal_rate') {
                setInterval3(editObj.tacticsParams?.interval)
                setDeviceProportion(editObj.tacticsParams?.deviceProportion)
            }
        }
    }, []);
    function getOrganizationUsersList () {//获取全部未删除用户
        dispatch(service.getOrganizationUsers()).then((res) => {
            if (res.success) {
                setUsersList(res.payload.data)
            }
        })
    }
    function getProjectPomsList () {//获取已绑定项目
        dispatch(service.getProjectPoms()).then((res) => {
            if (res.success) {
                setProjectPoms(res.payload?.data?.rows)
            }
        })
    }
    function getProjectStructureList (value) {//获取绑定项目下结构物
        dispatch(service.getProjectStructure({ pomsProjectId: value })).then((res) => {
            if (res.success) {
                let mylist = []
                for (let i = 0; i < res.payload?.data.length; i++) {
                    mylist.push(res.payload?.data[i].id)
                }
                setProjectStructure(res.payload?.data)
                form.current.setValue('strucId', mylist)
                form.current.validate(['strucId', 'timeType'])
                setStructure(false)
                setTimeTypeDis(false)
            }
        })
    }
    function getProjectStatusList () {//获取项目状态列表
        dispatch(service.getProjectStatus()).then((res) => {
            if (res.success) {
                setProjectStatus(res.payload?.data)
                let mylist = []
                for (let i = 0; i < res.payload?.data.length; i++) {
                    mylist.push(res.payload?.data[i].id)
                }
                form.current.setValue('timeType', mylist)
                form.current.validate(['strucId', 'timeType'])
            }
        })
    }
    function handleOk () {
        //点击弹框确定  右边按钮
        form.current
            .validate()
            .then((values) => {
                if (pushEdit) {
                    let obj = JSON.parse(JSON.stringify(values))
                    if (obj.timeType[0] == 'POMS') {
                        obj.timeType = []
                    }
                    let regu = /^[0-9]*[1-9][0-9]*$/;
                    if (obj.tactics == 'immediately') {
                        if (obj.interval1) {
                            if (regu.test(obj.interval1)) {
                                if (obj.interval1 <= 1440) {
                                    obj.tacticsParams = {
                                        interval: obj.interval1
                                    }
                                    delete obj.interval1
                                    delete obj.interval2
                                    delete obj.interval3
                                    delete obj.deviceProportion
                                } else {
                                    Notification.error({
                                        content: '即时推送时间不能大于1440分钟',
                                        duration: 2,
                                    })
                                }
                            } else {
                                Notification.error({
                                    content: '即时推送时间应为正整数',
                                    duration: 2,
                                })
                            }
                        } else {
                            Notification.error({
                                content: '即时推送时间应为正整数',
                                duration: 2,
                            })
                        }
                    }
                    else if (obj.tactics == 'continue') {
                        if (obj.interval2) {
                            if (regu.test(obj.interval2)) {
                                if (obj.interval2 <= 1440) {
                                    obj.tacticsParams = {
                                        interval: obj.interval2
                                    }
                                    delete obj.interval1
                                    delete obj.interval2
                                    delete obj.interval3
                                    delete obj.deviceProportion
                                } else {
                                    Notification.error({
                                        content: '持续时长推送时间不能大于1440分钟',
                                        duration: 2,
                                    })
                                }
                            } else {
                                Notification.error({
                                    content: '持续时长推送时间应为正整数',
                                    duration: 2,
                                })
                            }
                        } else {
                            Notification.error({
                                content: '持续时长推送时间应为正整数',
                                duration: 2,
                            })
                        }
                    }
                    else {
                        if (regu.test(obj.interval3) && regu.test(obj.deviceProportion)) {
                            if (obj.interval3 <= 720 && obj.deviceProportion <= 100) {
                                obj.tacticsParams = {
                                    interval: obj.interval3,
                                    deviceProportion: obj.deviceProportion
                                }
                                delete obj.interval1
                                delete obj.interval2
                                delete obj.interval3
                                delete obj.deviceProportion
                            } else if (obj.interval3 <= 720 && obj.deviceProportion > 100) {
                                Notification.error({
                                    content: '异常率推送异常率不能超过100%',
                                    duration: 2,
                                })
                            } else if (obj.interval3 > 720 && obj.deviceProportion <= 100) {
                                Notification.error({
                                    content: '异常率推送时间不能超过720小时',
                                    duration: 2,
                                })
                            } else {
                                Notification.error({
                                    content: '异常率推送时间不能超过720小时',
                                    duration: 2,
                                })
                                Notification.error({
                                    content: '异常率推送异常率不能超过100%',
                                    duration: 2,
                                })
                            }
                        } else if (regu.test(obj.interval3) && !regu.test(obj.deviceProportion)) {
                            Notification.error({
                                content: '异常率推送异常率应为正整数',
                                duration: 2,
                            })
                        } else if (!regu.test(obj.interval3) && regu.test(obj.deviceProportion)) {
                            Notification.error({
                                content: '异常率推送时间应为正整数',
                                duration: 2,
                            })
                        } else {
                            Notification.error({
                                content: '异常率推送异常率应为正整数',
                                duration: 2,
                            })
                            Notification.error({
                                content: '异常率推送时间应为正整数',
                                duration: 2,
                            })
                        }
                    }
                    dispatch(service.postPush({ pushId: pushId, ...obj, msg: '编辑推送配置' })).then((res) => {//获取项企(PEP)全部部门及其下用户
                        if (res.success) {
                            close();
                        }
                    })
                }
                else {
                    let obj = JSON.parse(JSON.stringify(values))
                    if (obj.timeType[0] == 'POMS') {
                        obj.timeType = []
                    }
                    let regu = /^[0-9]*[1-9][0-9]*$/;
                    if (obj.tactics == 'immediately') {
                        if (obj.interval1) {
                            if (regu.test(obj.interval1)) {
                                if (obj.interval1 <= 1440) {
                                    obj.tacticsParams = {
                                        interval: obj.interval1
                                    }
                                    delete obj.interval1
                                    delete obj.interval2
                                    delete obj.interval3
                                    delete obj.deviceProportion
                                } else {
                                    Notification.error({
                                        content: '即时推送时间不能大于1440分钟',
                                        duration: 2,
                                    })
                                }
                            } else {
                                Notification.error({
                                    content: '即时推送时间应为正整数',
                                    duration: 2,
                                })
                            }
                        } else {
                            Notification.error({
                                content: '即时推送时间应为正整数',
                                duration: 2,
                            })
                        }
                    }
                    else if (obj.tactics == 'continue') {
                        if (obj.interval2) {
                            if (regu.test(obj.interval2)) {
                                if (obj.interval2 <= 1440) {
                                    obj.tacticsParams = {
                                        interval: obj.interval2
                                    }
                                    delete obj.interval1
                                    delete obj.interval2
                                    delete obj.interval3
                                    delete obj.deviceProportion
                                } else {
                                    Notification.error({
                                        content: '持续时长推送时间不能大于1440分钟',
                                        duration: 2,
                                    })
                                }
                            } else {
                                Notification.error({
                                    content: '持续时长推送时间应为正整数',
                                    duration: 2,
                                })
                            }
                        } else {
                            Notification.error({
                                content: '持续时长推送时间应为正整数',
                                duration: 2,
                            })
                        }
                    }
                    else {
                        if (regu.test(obj.interval3) && regu.test(obj.deviceProportion)) {
                            if (obj.interval3 <= 720 && obj.deviceProportion <= 100) {
                                obj.tacticsParams = {
                                    interval: obj.interval3,
                                    deviceProportion: obj.deviceProportion
                                }
                                delete obj.interval1
                                delete obj.interval2
                                delete obj.interval3
                                delete obj.deviceProportion
                            } else if (obj.interval3 <= 720 && obj.deviceProportion > 100) {
                                Notification.error({
                                    content: '异常率推送异常率不能超过100%',
                                    duration: 2,
                                })
                            } else if (obj.interval3 > 720 && obj.deviceProportion <= 100) {
                                Notification.error({
                                    content: '异常率推送时间不能超过720小时',
                                    duration: 2,
                                })
                            } else {
                                Notification.error({
                                    content: '异常率推送时间不能超过720小时',
                                    duration: 2,
                                })
                                Notification.error({
                                    content: '异常率推送异常率不能超过100%',
                                    duration: 2,
                                })
                            }
                        } else if (regu.test(obj.interval3) && !regu.test(obj.deviceProportion)) {
                            Notification.error({
                                content: '异常率推送异常率应为正整数',
                                duration: 2,
                            })
                        } else if (!regu.test(obj.interval3) && regu.test(obj.deviceProportion)) {
                            Notification.error({
                                content: '异常率推送时间应为正整数',
                                duration: 2,
                            })
                        } else {
                            Notification.error({
                                content: '异常率推送异常率应为正整数',
                                duration: 2,
                            })
                            Notification.error({
                                content: '异常率推送时间应为正整数',
                                duration: 2,
                            })
                        }
                    }
                    dispatch(service.postPush({ ...obj, msg: '新增推送配置' })).then((res) => {//获取项企(PEP)全部部门及其下用户
                        if (res.success) {
                            close();
                        }
                    })
                }
            })
    }
    function handleCancel () {
        cancel();
        //点击弹框取消  左边按钮
    }
    return (
        <>
            <Modal
                title={pushEdit ? "修改推送策略" : '新增推送策略'}
                okText="确定"
                cancelText="取消"
                visible={visible}
                onOk={handleOk}
                width={860}
                onCancel={handleCancel}
            >
                <div>
                    <Form
                        allowEmpty
                        labelPosition="left"
                        labelAlign="right"
                        labelWidth="120px"
                        onValueChange={(values, field) => {
                            console.log('values', values);
                            for (var key in field) {
                                if (key == 'tactics') {
                                    if (values.tactics == 'abnormal_rate') {
                                        form.current.setValue('alarmType', undefined)
                                        setAbnormal(true)
                                    }
                                    else {
                                        setAbnormal(false)
                                    }
                                }
                                if (key == 'pomsProjectId') {
                                    getProjectStructureList(values.pomsProjectId)//获取绑定项目下结构物
                                    for (let i = 0; i < projectPoms.length; i++) {
                                        if (values.pomsProjectId == projectPoms[i].id) {
                                            if (projectPoms[i].pepProjectId) {
                                                getProjectStatusList()//获取项目状态列表
                                            }
                                            else {
                                                setProjectStatus([{ construction_status: 'POMS', id: 'POMS' }])
                                                form.current.setValue('timeType', ['POMS'])
                                                form.current.validate()
                                            }
                                        }
                                    }
                                }
                            }
                        }}
                        getFormApi={(formApi) => (form.current = formApi)}
                    >
                        <div style={{ color: '#4A4A4A', fontSize: 14, fontWeight: 600, marginLeft: 6 }}>
                            项目信息配置
                        </div>
                        <div>
                            <Form.Input
                                field="name"
                                label='策略名称:'
                                style={{ width: 695 }}
                                initValue={editObj?.name || ""}
                                placeholder="请输入策略名称"
                                showClear
                                rules={[{ required: true, message: "请输入策略名称" }]} />
                        </div>
                        <div>
                            <Form.Select
                                label="请选择项目:"
                                field="pomsProjectId"
                                placeholder="请选择项目"
                                style={{ width: 695 }}
                                rules={[{ required: true, message: "请选择项目" }]}
                                initValue={editObj?.pomsProjectId || ""}
                                filter
                            >
                                {
                                    projectPoms.map((item, index) => {
                                        return (
                                            <Form.Select.Option key={index} value={item.id}>
                                                {item.pepProjectName || item.name}
                                            </Form.Select.Option>
                                        )
                                    })
                                }
                            </Form.Select>
                        </div>
                        <div>
                            <Form.Select
                                label="请选择结构物:"
                                field="strucId"
                                placeholder="请选择结构物"
                                style={{ width: 695 }}
                                rules={[{ required: true, message: "请选择结构物" }]}
                                initValue={editObj?.strucId || []}
                                disabled={structure}
                                filter
                                multiple
                                maxTagCount={3}
                                showClear
                            >
                                {
                                    projectStructure.map((item, index) => {
                                        return (
                                            <Form.Select.Option key={index} value={item.id}>
                                                {item.name}
                                            </Form.Select.Option>
                                        )
                                    })
                                }
                            </Form.Select>
                        </div>
                        <div className='pushInput'>
                            <Form.RadioGroup
                                field="tactics"
                                label='推送策略配置:'
                                type='card'
                                direction='horizontal'
                                initValue={editObj?.tactics || ''}
                                rules={[{ required: true, message: '请选择推送策略' }]}>
                                <Form.Radio
                                    value='immediately'
                                    extra={
                                        <span style={{ fontSize: 13 }}>
                                            发现在
                                            <Form.Input
                                                field="interval1"
                                                pure
                                                style={{ width: 60, height: 20, color: '#1859C1' }}
                                                initValue={interval1 || "10"}
                                            // rules={[{ pattern: "^[0-9]*[1-9][0-9]*$", message: "请输入正整数" }]}
                                            />
                                            分钟内，有告警源新增，则通过【信鸽服务】发送一条通知信息。
                                        </span>
                                    }
                                    style={{ width: 198 }}>
                                    即时推送机制
                                </Form.Radio>
                                <Form.Radio
                                    value='continue'
                                    extra={
                                        <span style={{ fontSize: 13 }}>
                                            告警源持续产生时间超过
                                            <Form.Input
                                                field="interval2"
                                                pure
                                                style={{ width: 60, height: 20, color: '#1859C1' }}
                                                initValue={interval2 || "10"}
                                            // rules={[{ pattern: "^[0-9]*[1-9][0-9]*$", message: "请输入正整数" }]}
                                            />
                                            分钟，则通过【信鸽服务】发送一条通知信息。
                                        </span>
                                    }
                                    style={{ width: 198 }}>
                                    持续时长推送机制
                                </Form.Radio>
                                <Form.Radio
                                    value='abnormal_rate'
                                    extra={
                                        <span style={{ fontSize: 13 }}>
                                            异常设备数量达到项目或结构物内设备总数量的
                                            <Form.Input
                                                field="deviceProportion"
                                                pure
                                                style={{ width: 60, height: 20, color: '#1859C1' }}
                                                initValue={deviceProportion || "40"}
                                            // rules={[{ pattern: "^[0-9]*[1-9][0-9]*$", message: "请输入正整数" }]}
                                            />
                                            %，且持续时长超过
                                            <Form.Input
                                                field="interval3"
                                                pure
                                                style={{ width: 60, height: 20, color: '#1859C1' }}
                                                initValue={interval3 || "2"}
                                            // rules={[{ pattern: "^[0-9]*[1-9][0-9]*$", message: "请输入正整数" }]}
                                            />
                                            小时，则通过【信鸽服务】发送一条通知信息。
                                        </span>
                                    }
                                    style={{ width: 260 }}>
                                    异常率推送机制
                                </Form.Radio>
                            </Form.RadioGroup>
                        </div>
                        <div>
                            <Form.CheckboxGroup
                                label="监听问题模块:"
                                field="alarmType"
                                style={{ width: 695 }}
                                rules={[{ required: true, message: "监听问题模块" }]}
                                initValue={editObj?.alarmType || []}
                                direction='horizontal'
                                showClear
                            >
                                <Form.Checkbox value="data_outages">数据中断</Form.Checkbox>
                                <Form.Checkbox value="data_exception">数据异常</Form.Checkbox>
                                <Form.Checkbox value="strategy_hit" disabled={abnormal}>策略命中</Form.Checkbox>
                                <Form.Checkbox value="video_exception">视频异常</Form.Checkbox>
                                <Form.Checkbox value="app_exception" disabled={abnormal}>应用异常</Form.Checkbox>
                                <Form.Checkbox value="device_exception">设备异常</Form.Checkbox>
                            </Form.CheckboxGroup>
                        </div>
                        <div style={{ color: '#4A4A4A', fontSize: 14, fontWeight: 600, marginLeft: 6 }}>
                            接收信息配置
                        </div>
                        <div style={{ display: 'flex' }}>
                            <Form.Select
                                label="通知时效:"
                                field="timeType"
                                placeholder="请选择通知时效"
                                style={{ width: 285 }}
                                rules={[{ required: true, message: "请选择通知时效" }]}
                                initValue={editObj?.timeType.length > 0 ? editObj?.timeType : timeTypePOMS.current}
                                disabled={timeTypeDis}
                                multiple
                                maxTagCount={3}
                            >
                                {
                                    projectStatus.map((item, index) => {
                                        return (
                                            <Form.Select.Option key={index} value={item.id}>
                                                {item.construction_status}
                                            </Form.Select.Option>
                                        )
                                    })
                                }
                            </Form.Select>
                            <Form.Select
                                label="接收人:"
                                field="receiverPepUserId"
                                placeholder="请选择接收人"
                                style={{ width: 285 }}
                                rules={[{ required: true, message: "请选择接收人" }]}
                                initValue={editObj?.receiverPepUserId || [user.id]}
                                filter
                                multiple
                                maxTagCount={3}
                                showClear
                            >
                                {
                                    usersList.map((item, index) => {
                                        return (
                                            <Form.Select.Option key={index} value={item.id}>
                                                {item.name}
                                            </Form.Select.Option>
                                        )
                                    })
                                }
                            </Form.Select>
                        </div>
                        <div style={{ marginLeft: 120, color: '#005ABD', fontSize: 14 }}>
                            不在项目节点的通知策略，会自动失效.
                        </div>
                        <div style={{ marginTop: 20 }}>
                            <Form.RadioGroup
                                field="disable"
                                pure
                                direction='horizontal'
                                style={{ display: 'flex', justifyContent: 'space-evenly' }}
                                initValue={editObj?.disable || false}
                                rules={[{ required: true, }]}>
                                <Form.Radio value={false}>
                                    启用
                                </Form.Radio>
                                <Form.Radio value={true}
                                    style={{ marginLeft: 120 }}>
                                    禁用
                                </Form.Radio>
                            </Form.RadioGroup>
                        </div>
                    </Form>
                </div>
            </Modal >
        </>
    );
}
function mapStateToProps (state) {
    const { auth, global, members } = state;
    return {
        //   loading: members.isRequesting,
        user: auth.user,
        actions: global.actions,
        //   members: members.data,
    };
}

export default connect(mapStateToProps)(pushModal);
