import React, { useState, useEffect, useRef } from 'react'
import SiteModal from '@/components/Modal/SiteModa';
import { Form, Input, notification, Select, Checkbox, message, Button, Card, Switch as Switchs } from 'antd'
import BaseForm from '@/components/BaseForm/index';
import { Switch } from 'react-router';
import { iteratee } from 'lodash';
import styles from './schemeDetail.less';
import v from 'voca';

import { UsergroupDeleteOutlined } from '@ant-design/icons';
import VisibleRoleModal from '../messageManage/projectManage/components/RolseSelect/VisibleRoleModal'
import VisibleIISAgentConfig from '../messageManage/projectManage/components/IISAgentConfig/VisibleIISAgentConfig'
import { GetMessageTemplate } from '@/services/platform/messagemanage'
import moment from 'moment'
import { UpdateMessageConfig, InsertMessageConfig, AddIISAgentConfig } from '@/services/platform/messagemanage'
import { useHistory } from 'react-router-dom';
const { Item } = Form;
const { TextArea } = Input;
const EditModal = props => {

    const history = useHistory();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [plan, setPlan] = useState('');
    const [isStart, setIsStart] = useState(false);
    const [IISConfig, setIISConfig] = useState(null)
    const [isUse, setIsUse] = useState("0")
    const [btnType, setBtnType] = useState("定时推送")
    const { template, confirmModal } = props.location.state
    const [currentTrench, setCurrentTrench] = useState({
        isMessageShow: false,
        isAPPShow: false,
        isWEBShow: false,
        isWXShow: false
    })
    const [APP_ITEMS, setAPP_ITEMS] = useState([])
    const [WEB_ITEMS, setWEB_ITEMS] = useState([])
    const [WX_ITEMS, setWX_ITEMS] = useState([])
    const [MES_ITEMS, setMES_ITEMS] = useState([])
    const [listType, setListType] = useState([{ title: '定时推送', desc: '用于周期性简报的定时推送，如智能巡检、运行周报。' }, { title: '监控报警', desc: '设备硬件故障，阈值超限，状态突变，采集超时等异常情况报警。' }, { title: '工单办理', desc: '在工单系统中，针对特定人员的通知，包括工作办理、审核、会签、回退等操作。' }, { title: '平台公告', desc: '由运维人员向所有用户或特定用户发送的事务公告，如系统升级、维护。' }])

    useEffect(() => {
        GetMessageTemplate().then(
            res => {
                if (res.code === 0) {
                    let arr1 = []
                    let arr2 = []
                    let arr3 = []
                    let arr4 = []
                    res.data.map((item, index) => {
                        if (item.Type === "公众号") {
                            arr1.push(item)
                        }
                        if (item.Type === "短信") {
                            arr2.push(item)
                        }
                        if (item.Type === "APP") {
                            arr3.push(item)
                        }
                        if (item.Type === "WEB") {
                            arr4.push(item)
                        }
                    })
                    setAPP_ITEMS(arr3)
                    setMES_ITEMS(arr2)
                    setWX_ITEMS(arr1)
                    setWEB_ITEMS(arr4)
                }
            }
        )
    }, [])
    useEffect(() => {
        if (template.ThemeName) {
            console.log('template',template);
            form.setFieldsValue({
                name: template.MsgType,
                isStart: template.IsStarted === "0" ? "关闭" : "开启",
                to_person: template.PushGroup,
                push_mode: template.PushMode === null ? '' : template.PushMode.split(","),

                app_template: template.AppTemplateID,
                app_path: template.AppFunctionPath,
                wx_template: template.PublicTemplateID ? parseInt(template.PublicTemplateID) : '',
                h5_path: template.PublicPath,
                miniprogram_path: template.MiniAppRoute,
                web_template: template.WebTemplateID,
                web_path: template.WebFunctionPath,
                message_template: template.MsgTemplateID,
            })
            setPlan(template.MsgType)
            setBtnType(template.type)
            setIsUse(template.IsStarted)
            setCurrentTrench({
                isAPPShow: template.PushMode && template.PushMode.split(",").indexOf("平台弹框") > -1 ? true : false,
                isWXShow: template.PushMode && template.PushMode.split(",").indexOf("公众号推送") > -1 ? true : false,
                isWEBShow: template.PushMode && template.PushMode.split(",").indexOf("平台弹框") > -1 ? true : false,
                isMessageShow: template.PushMode && template.PushMode.split(",").indexOf("短信推送") > -1 ? true : false,
            })
        }
        else {
            setBtnType('定时推送')
        }
    }, [props])
    const onNameChange = (e) => {
        setPlan(e.target.value)
    }

    const onSubmit = () => {
        let fv = form.getFieldValue()
        let push_mode = ((currentTrench.isAPPShow || currentTrench.isWEBShow) ? '平台弹框' : '') + (currentTrench.isWXShow ? ',公众号推送' : '') + (currentTrench.isMessageShow ? ',短信推送' : '')
        if (template.ThemeName) {
            let a = {
                ID: template.ID,
                ThemeName: template.ThemeName,
                MsgType: fv.name,
                PublicTemplateID: fv.wx_template.toString(),
                PublicConfig: template.PublicConfig,
                PublicPath: fv.h5_path,
                MsgTemplateName: template.MsgTemplateName,
                MsgTemplateCode: template.MsgTemplateCode,
                MsgConfig: template.MsgConfig,
                MiniAppRoute: fv.miniprogram_path,
                AppFunctionPath: fv.app_path,
                AppConfig: template.AppConfig,
                WebFunctionPath: fv.web_path,
                WebConfig: template.WebConfig,
                IsDelete: template.IsDelete,
                InputTime: moment().format("YYYY-MM-DD HH:mm:ss"),
                Pusher: template.Pusher,
                PushMode: push_mode,
                PushPath: template.PushPath,
                IsStarted: isUse,
                MsgTemplateID: fv.message_template,
                AppTemplateID: fv.app_template,
                WebTemplateID: fv.web_template,
                PushGroup: fv.to_person ? fv.to_person.toString() : ''
            }

            UpdateMessageConfig(a).then(
                res => {
                    if (res.code === 0) {
                        if (IISConfig) {
                            AddIISAgentConfig(IISConfig).then(
                                res => {
                                    if (res.code === 0) {
                                        message.success("保存成功")

                                    } else {
                                        notification.error({
                                            message: '提示',
                                            duration: 3,
                                            description: res.msg,
                                        });
                                    }
                                }
                            )
                        } else {
                            message.success("保存成功")

                        }
                    }
                    else {
                        notification.error({
                            message: '提示',
                            duration: 3,
                            description: res.msg,
                        });
                    }
                }
            )

        } else {
            let b = {
                ThemeName: "定时推送",
                MsgType: fv.name,
                PublicTemplateID: fv.wx_template ? fv.wx_template.toString() : null,
                PublicConfig: template.PublicConfig,
                PublicPath: fv.h5_path,
                MsgTemplateName: template.MsgTemplateName,
                MsgTemplateCode: template.MsgTemplateCode,
                MsgConfig: template.MsgConfig,
                MiniAppRoute: fv.miniprogram_path,
                AppFunctionPath: fv.app_path,
                AppConfig: template.AppConfig,
                WebFunctionPath: fv.web_path,
                WebConfig: template.WebConfig,
                IsDelete: template.IsDelete,
                InputTime: moment().format("YYYY-MM-DD HH:mm:ss"),
                Pusher: template.Pusher,
                PushMode: push_mode,
                PushPath: template.PushPath,
                IsStarted: isUse,
                MsgTemplateID: fv.message_template,
                AppTemplateID: fv.app_template,
                WebTemplateID: fv.web_template,
                PushGroup: fv.to_person ? fv.to_person.toString() : ''
            }
            InsertMessageConfig(b).then(
                res => {
                    if (res.code === 0) {
                        if (IISConfig) {
                            AddIISAgentConfig(IISConfig).then(
                                res => {
                                    if (res.code === 0) {
                                        message.success("保存成功")

                                    }
                                    else {
                                        notification.error({
                                            message: '提示',
                                            duration: 3,
                                            description: res.msg,
                                        });
                                    }
                                }
                            )
                        } else {
                            message.success("保存成功")
                        }
                    }
                    else {
                        notification.error({
                            message: '提示',
                            duration: 3,
                            description: res.msg,
                        });
                    }
                }
            )
        }

    }


    const onIISAgentSubmit = (value) => {
        console.log('value',value);
        setIISConfig(value)

    }

    const onPushSubmit = (value) => {
        console.log(value, "onPushSubmit")
    }
    const layout = {
        layout: 'horizontal',
        labelCol: {
            span: 2,
        },
        wrapperCol: {
            span: 24,
        },
    };
    const onChange = (value) => {
        setIsUse(value ? '1' : '0')
    }
    const back = () => {
        history.push('/platformCenter/notify')
    }
    const tailLayout = {
        wrapperCol: { offset: 21, span: 24 },
    };
    const onTypeChange = (value, type) => {
        let data = { ...currentTrench }
        data[type] = value
        setCurrentTrench(data)
    }
    return (

        <div className={styles.editModal_container}>
            <Form form={form}  {...layout} onFinish={onSubmit}>
                <div className={styles.content}>
                    <Card title="方案" style={{ width: '100%' }}>
                        <Item
                            label="方案名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入方案名称',
                                },
                            ]}
                        >
                            <Input style={{ width: '25rem' }} placeholder="请输入方案名称" disabled={template.ThemeName ? true : false} onChange={onNameChange} />
                        </Item>
                        <Item
                            label="方案类型"

                        >
                            <div className={styles.cardList}>
                                {listType.map(item => {
                                    return <div key={item.title} className={styles.cardListItem}><Button type={item.title === btnType ? 'primary' : 'default'} style={{ cursor: 'not-allowed', marginRight: '1rem' }} >{item.title}</Button> <span>{item.desc}</span></div>
                                })}

                            </div>
                        </Item>

                    </Card>
                    {btnType === '定时推送' && (<Card title="推送信息" style={{ width: '100%', marginTop: '1rem' }}>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <Item
                                label="推送组"
                                name="to_person"
                                labelCol={{ span: 3 }}
                                style={{ paddingTop: '1.6rem', width: '35rem' }}
                            >
                                <VisibleRoleModal
                                    style={{ display: 'flex', width: '35rem', alignItems: 'center' }}
                                    onSubmit={onPushSubmit}
                                    selectValue={template && template.PushGroup ? template.PushGroup : []}
                                    title={<UsergroupDeleteOutlined style={{ fontSize: '18px' }} />} />
                            </Item>

                            <div style={{ display: 'flex', width: '30rem', margin: '0 2rem', alignItems: 'center' }}>
                                推送计划： <VisibleIISAgentConfig agentConfig={template.item && template.item.AgentConfig} value={plan} onIISAgentSubmit={onIISAgentSubmit} />
                            </div>
                            <span>
                                是否启用：<Switchs checked={isUse === '0' ? false : true} onChange={onChange} />
                            </span>
                        </div>

                    </Card>)}
                    <div className={styles.push_trench}>
                        {

                            <div className={styles.trench_card}>
                                <div className={styles.card_title}>
                                    <div className={styles.lable}>APP</div>
                                    <Switchs onChange={e => onTypeChange(e, 'isAPPShow')} checked={currentTrench.isAPPShow} />
                                </div>
                                <div className={styles.card_body}>
                                    <Item
                                        label="模板"
                                        labelAlign='left'
                                        name="app_template"
                                        labelCol={{ span: 2 }}
                                    >
                                        <Select style={{ width: '97%' }} disabled={!currentTrench.isAPPShow} >
                                            {
                                                APP_ITEMS.map((item, idx) => {
                                                    return (
                                                        <Select.Option value={item.Id} key={idx}>{item.LikeName}</Select.Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    </Item>
                                    <Item
                                        label="功能路径"
                                        name="app_path"
                                        labelAlign='left'
                                        labelCol={{ span: 2 }}
                                    >
                                        <TextArea rows={4} style={{ width: '97%' }} disabled={!currentTrench.isAPPShow} placeholder="请输入功能路径" />
                                    </Item>
                                </div>
                            </div>

                        }
                        {

                            <div className={styles.trench_card}>
                                <div className={styles.card_title}>
                                    <div className={styles.lable}>微信</div>
                                    <Switchs onChange={e => onTypeChange(e, 'isWXShow')} checked={currentTrench.isWXShow} />
                                </div>
                                <div className={styles.card_body}>
                                    <Item
                                        label="模板"
                                        name="wx_template"
                                        labelAlign='left'
                                        labelCol={{ span: 3 }}
                                    >
                                        <Select style={{ width: '97%' }} disabled={!currentTrench.isWXShow} >
                                            {
                                                WX_ITEMS.map((item, idx) => {
                                                    return (
                                                        <Select.Option value={item.Id} key={idx}>{item.LikeName}</Select.Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    </Item>
                                    <Item
                                        label="H5路由"
                                        name="h5_path"
                                        labelAlign='left'
                                        labelCol={{ span: 3 }}
                                    >
                                        <Input style={{ width: '97%' }} disabled={!currentTrench.isWXShow} placeholder="请输入功能路径" />
                                    </Item>
                                    <Item
                                        label="小程序路由"
                                        name="miniprogram_path"
                                        labelAlign='left'
                                        labelCol={{ span: 3 }}
                                    >
                                        <Input style={{ width: '97%' }} disabled={!currentTrench.isWXShow} placeholder="请输入功能路径" />
                                    </Item>
                                </div>
                            </div>

                        }
                        {

                            <div className={styles.trench_card}>
                                <div className={styles.card_title}>
                                    <div className={styles.lable}>WEB</div>
                                    <Switchs onChange={e => onTypeChange(e, 'isWEBShow')} checked={currentTrench.isWEBShow} />
                                </div>
                                <div className={styles.card_body}>
                                    <Item
                                        label="模板"
                                        name="web_template"
                                        labelCol={{ span: 2 }}
                                        labelAlign='left'
                                    >
                                        <Select style={{ width: '97%' }} disabled={!currentTrench.isWEBShow}>
                                            {
                                                WEB_ITEMS.map((item, idx) => {
                                                    return (
                                                        <Select.Option value={item.Id} key={idx}>{item.LikeName}</Select.Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    </Item>
                                    <Item
                                        label="功能路径"
                                        name="web_path"
                                        labelAlign='left'
                                        labelCol={{ span: 2 }}
                                    >
                                        <TextArea rows={4} style={{ width: '97%' }} disabled={!currentTrench.isWEBShow} placeholder="请输入功能路径" />
                                    </Item>
                                </div>
                            </div>

                        }

                        {

                            <div className={styles.trench_card}>
                                <div className={styles.card_title}>
                                    <div className={styles.lable}>短信推送</div>
                                    <Switchs onChange={e => onTypeChange(e, 'isMessageShow')} checked={currentTrench.isMessageShow} />
                                </div>
                                <div className={styles.card_body}>
                                    <Item
                                        label="模板"
                                        labelAlign='left'
                                        name="message_template"
                                        labelCol={{ span: 2 }}
                                    >
                                        <Select style={{ width: '97%' }} disabled={!currentTrench.isMessageShow} >
                                            {
                                                MES_ITEMS.map((item, idx) => {
                                                    return (
                                                        <Select.Option value={item.Id} key={idx}>{item.LikeName}</Select.Option>
                                                    )
                                                })
                                            }
                                        </Select>
                                    </Item>
                                </div>
                            </div>

                        }
                    </div>

                </div>
                <Item  {...tailLayout} style={{ marginTop: '1rem' }}>
                    <Button htmlType="button" onClick={back} style={{ marginRight: '2rem' }}>
                        返回
                    </Button>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Item>
            </Form>
            <div>
            </div>
        </div>
    )
}
export default EditModal;