import React, { useEffect, useState } from 'react'
import {
    // Tree,
    Table,
    Space,
    Input,
    Button,
    Select,
    Popconfirm,
    message,
    Tooltip,
    notification,
    Spin
} from 'antd';
import { PlusCircleOutlined, EditTwoTone, DeleteOutlined } from '@ant-design/icons';

const { Search } = Input;
const { Option } = Select;
import EditModal from './components/EditModal'
import AddModal from './components/AddModal'
import { GetMessageTemplate, UpdateMessageTemplate, DeleteMessageTemplate, InsertMessageTemplate, GetThirdpartyTemplates } from '@/services/platform/messagemanage'
import styles from './TemplateManage.less'



const TemplateManage = () => {

    const [visibleParams, setvisibleParams] = useState({
        addVisible: false, // 新增弹窗
        delVisible: false, // 删除弹窗
        editVisible: false, // 修改弹窗
        spinLoading: false, // 加载弹窗
        btnLoading: false,
        loading: false,
        checkBoxLoading: false,
    });
    const [currentTemplate, setCurrentTempalte] = useState({});
    const [data, setData] = useState([])
    const [flag, setFlag] = useState(0)
    const [option, setOption] = useState([]); // 下拉列表数据
    const [treeLoading, setTreeLoading] = useState(false);

    useEffect(() => {
        getTemplateList()
        selectFocus()
    }, [flag])

    const getTemplateList = (obj) => {
        setTreeLoading(true)
        GetMessageTemplate(obj).then(
            res => {
                setTreeLoading(false)
                let list = []
                if (res.code === 0) {
                    res.data.map((item, index) => {
                        list.push({
                            key: item.Id,
                            Id: item.Id,
                            name: item.LikeName,
                            type: item.Type,
                            third_name: item.Name,
                            third_id: item.No,
                            template_params: item.TDescription,
                            analysis_params: item.ParsingRules,
                            desc: item.ParsingDescription
                        })
                    })
                    setData(list)
                }
            }
        ).catch(e=>{
            setTreeLoading(false)
        })
    }

    const selectFocus = (obj) => {
        GetThirdpartyTemplates(obj).then(res => {
            if (res.msg === "Ok") {
                setOption(res.data);
            } else {
                notification.error({
                    message: '提示',
                    duration: 15,
                    description: res.message,
                });
            }
        })
            .catch(err => {
                console.error(err);
            });
    };

    const columns = [
        {
            title: '编号',
            dataIndex: 'Id',
            key: 'Id',
            align: 'center',
            width: 80,
            render: text => <a>{text}</a>,
        },
        {
            title: '模板名称',
            dataIndex: 'name',
            key: 'name',
            align: 'center',
        },
        {
            title: '模板类型',
            dataIndex: 'type',
            key: 'type',
            align: 'center',
        },
        {
            title: '第三方模板名称',
            dataIndex: 'third_name',
            key: 'third_name',
            align: 'center',
        },
        {
            title: '第三方模版编号',
            dataIndex: 'third_id',
            key: 'third_id',
            align: 'center',
        },
        {
            title: '模板参数',
            dataIndex: 'template_params',
            key: 'template_params',
            align: 'center',
        },
        {
            title: '模板参数说明',
            dataIndex: 'desc',
            key: 'desc',
            align: 'center',
        },
        {
            title: '解析参数',
            dataIndex: 'analysis_params',
            key: 'analysis_params',
            align: 'center',
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            width: 150,
            ellipsis: true,
            render: (text, record) => (
                <Space>
                    <Tooltip title="编辑">
                        <EditTwoTone
                            type="primary"
                            size="small"
                            onClick={() => {
                                changeDesc(record);
                            }}
                            style={{ fontSize: '16px' }}
                        />
                    </Tooltip>
                    <Tooltip title="删除">
                        <div onClick={e => e.stopPropagation()}>
                            <Popconfirm
                                placement="bottomRight"
                                title="是否删除该模板?"
                                okText="确认"
                                cancelText="取消"
                                onConfirm={() => {
                                    delTemplate(record);
                                }}
                            >
                                <DeleteOutlined style={{ fontSize: '16px', color: '#e86060' }} />
                            </Popconfirm>
                        </div>
                    </Tooltip>
                </Space>
            ),
        },

    ];

    const placeholder = '请输入模板名称'
    const handleSearch = (value) => {
        getTemplateList({ queryInfo: value })
    }
    const handleReset = () => {
        getTemplateList()
    }
    const handleSelectType = (value) => {
        if (value === '全部') {
            getTemplateList()
        } else {
            getTemplateList({ tempType: value })
        }
    }
    const changeDesc = (record) => {
        setCurrentTempalte(record)
        handleShowModal("editVisible", true)
    }
    const AddTemplate = () => {
        handleShowModal("addVisible", true)
    }
    const delTemplate = (record) => {
        DeleteMessageTemplate({
            id: record.Id
        }).then(
            res => {
                if (res.code === 0) {
                    message.success("模板删除成功!")
                    setFlag(flag + 1)
                } else {
                    message.warn("模板删除失败!")
                }
            }
        )
    }
    // 弹出模态框
    const handleShowModal = (key, value) => {
        setvisibleParams({ ...visibleParams, [key]: value });
    };
    //编辑
    const editModal = () => {
        handleShowModal("editVisible", false)
    }
    const onSubmit = (result) => {
        UpdateMessageTemplate({
            Id: result.Id,
            Type: result.type,
            LikeName: result.name,
            Name: result.third_name,
            No: result.third_id,
            ParsingRules: result.analysis_params,
            ParsingDescription: result.desc,
            TDescription: result.params
        }).then(
            res => {
                if (res.code === 0) {
                    message.success("模板保存成功!")
                    handleShowModal("editVisible", false)
                    setFlag(flag + 1)
                } else {
                    message.warn("模板保存失败!")
                }
            }
        )
    }
    //新增
    const addModal = () => {
        handleShowModal("editVisible", false)
    }
    const onAddSubmit = (result) => {
        InsertMessageTemplate({
            Type: result.type,
            LikeName: result.name,
            Name: result.third_name,
            No: result.third_id,
            ParsingRules: result.analysis_params,
            ParsingDescription: result.desc,
            TDescription: result.params
        }).then(
            res => {
                if (res.code === 0) {
                    message.success("模板添加成功!")
                    handleShowModal("addVisible", false)
                    setFlag(flag + 1)
                } else {
                    message.warn("模板添加失败!")
                }
            }
        )
    }

    return (
        <div className={styles.template_container}>
            <Spin tip="loading..." spinning={treeLoading}>
                <div className={styles.operate_bar}>
                    <div className={styles.template_type}>
                        <div className={styles.title}>模板类型</div>
                        <Select placeholder="请选择是否!" defaultValue="全部" style={{ width: "150px" }} onChange={handleSelectType} className={styles.select}>
                            <Option value="全部">全部</Option>
                            <Option value="公众号">公众号</Option>
                            <Option value="短信">短信</Option>
                            <Option value="APP">APP</Option>
                            <Option value="WEB">WEB</Option>
                        </Select>
                    </div>
                    <div className={styles.fast_search}>
                        <div className={styles.title}>快速检索</div>
                        <Search
                            allowClear
                            placeholder={placeholder}
                            onSearch={handleSearch}
                            // onChange={handleChange}
                            enterButton
                            style={{ width: "300px" }}
                        />
                    </div>
                    <Button type="primary" onClick={handleReset}>重置</Button>

                    <Button type="primary" style={{ marginLeft: "10px" }} icon={<PlusCircleOutlined style={{ verticalAlign: "middle" }} />} onClick={AddTemplate}><span style={{ marginTop: "-3px" }}>新增</span></Button>

                </div>
                <div className={styles.list_view}>
                    <Table
                        columns={columns}
                        dataSource={data}
                        bordered
                        pagination={{ pageSize: '10' }}
                        scroll={{ y: '500px' }}
                    />
                </div>
                <EditModal
                    visible={visibleParams.editVisible}
                    template={currentTemplate}
                    onCancel={() => handleShowModal('editVisible', false)}
                    option={option}
                    confirmModal={editModal}
                    onSubmit={onSubmit}
                />
                <AddModal
                    visible={visibleParams.addVisible}
                    template={currentTemplate}
                    onCancel={() => handleShowModal('addVisible', false)}
                    option={option}
                    confirmModal={addModal}
                    onSubmit={onAddSubmit}
                />
            </Spin>
        </div>
    )
}
export default TemplateManage;