import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Select, InputNumber, TreeSelect, message, Button, Modal, Radio } from 'antd';
import ProTable from '@ant-design/pro-table';
import quickAPI from "../../service";
import styles from "./index.less";
import indexStyles from "../../index.less";
import { PlusOutlined } from '@ant-design/icons';

const key = "message";


const DeviceConfig = (props) => {
    const { Option, OptGroup } = Select;
    const [addDeviceTypeForm] = Form.useForm();
    const [editDeviceForm] = Form.useForm();

    //设备类型列表
    const [deviceTypeList, setDeviceTypeList] = useState([]);
    //设备分类
    const [deviceClassList, setDeviceClassList] = useState([]);
    const [deviceClassEnum, setDeviceClassEnum] = useState({});
    //组织树
    const [orgTree, setOrgTree] = useState([]);
    //设备版本
    const [deviceVersion, setDeviceVersion] = useState([]);
    //是否显示设备分类弹窗
    const [isModalOpen, setIsModalOpen] = useState(false);

    //当前操作的设备对象
    const [currentOption, setCurrentOption] = useState({ id: '' });

    //是否显示 新增/编辑 菜谱弹窗
    const [isShowModal, setIsShowModal] = useState(false);

    /**
     * 提交表单
     * @param {*} formValues
     */
    const onFinishSubmit = async (formValues) => {
        message.loading('正在配置', key);
        if (formValues.id) {
            const response = await quickAPI.UpdateDeviceInfo(formValues);
            if (response.succeeded) {
                message.success('修改成功');
                setIsShowModal(false);
                actionRef.current.reload();
            } else {
                message.error(response.errors || '修改出错');
            }
        } else {
            const response = await quickAPI.AddDeviceInfo(formValues);
            if (response.succeeded) {
                message.success('添加成功');
                actionRef.current.reload();
                setIsShowModal(false);
            } else {
                message.error(response.errors || '添加成出错');
            }
        }
        message.destroy(key);
        actionRef.current.reload();
    }

    /**
     * 获取设备类型列表
     */
    const onFetchDeviceTypeList = async () => {
        const response = await quickAPI.GetDicList('DeviceClientType');
        if (response.statusCode === 200) {
            response.data.forEach(item => {
                item.code = item.code;
                item.value = item.code;
            })
            setDeviceTypeList(response.data);
        } else {
            message.error(response.errors || '获取设备类型出错');
        }
    }

    //获取组织树
    const onFetchOrgTree = async () => {
        const response = await quickAPI.getOrgTree();
        if (response.statusCode === 200) {
            setOrgTree(response.data);
        } else {
            message.error(response.errors || '获取组织架构出错');
        }
    }

    /**
     * 获取设备分类
     */
    const onFetchDeviceClass = async () => {
        const response = await quickAPI.GetDeviceType();
        if (response.statusCode === 200) {
            const deviceEnum = {};
            response.data.forEach(item => {
                deviceEnum[item.id] = {
                    text: item.name
                }
            });
            setDeviceClassEnum(deviceEnum);
            setDeviceClassList(response.data);
        } else {
            message.error(response.errors || '获取设备分类出错');
        }
    }

    /**
     * 获取设备版本
     */
    const onFetchDeviceVersion = async () => {
        const response = await quickAPI.GetDeviceVersions();
        if (response.statusCode === 200) {
            setDeviceVersion(response.data);
        } else {
            message.error(response.errors || '获取设备版本出错');
        }
    }

    /**
     * 添加设备分类
     */
    const onSaveDeviceType = async (values) => {
        const response = await quickAPI.AddDeviceType(values);
        if (response.data) {
            message.success('设备分类添加成功！');
            setIsModalOpen(false);
            onFetchDeviceClass();
        } else {
            message.error(response.errors || '添加设备分类出错');
        }
    }

    const actionRef = useRef();
    const [selectedRowKeys, setSelectRowKeys] = useState([]);
    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            hideInSearch: true,
            hideInTable: true,
            tip: '规则名称是唯一的 key',
        },
        {
            title: '设备名称',
            dataIndex: 'deviceName',
            valueType: 'textarea',
        },
        {
            title: '所属门店',
            dataIndex: 'orgId',
            hideInSearch: true,
            render: (_, record) => {
                return <div>
                    {props.storeConfig.name}
                </div>
            }
        },
        {
            title: '设备类型',
            dataIndex: 'deviceTypeKey',
            valueEnum: deviceTypeList,
            hideInSearch: true,
        },
        {
            title: '设备分类',
            dataIndex: 'deviceTypeId',
            valueEnum: deviceClassEnum,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueEnum: {
                0: { text: '正常', status: 'Processing' },
                1: { text: '停用', status: 'Success' },
            },
            hideInSearch: true,
        },

        {
            title: '设备地址',
            dataIndex: 'deviceAddr',
            search: false,
            valueType: 'textarea',
        },
        {
            title: '坐标',
            dataIndex: 'deviceLoc',
            valueType: 'textarea',
            search: false,
        },
        {
            title: '设备通道数量',
            dataIndex: 'materialQuantity',
            valueType: 'textarea',
            search: false,
        },

        {
            title: '设备唯一key',
            dataIndex: 'autoKey',
            search: false,
        },
        {
            title: '归属门店唯一key',
            dataIndex: 'orgKey',
            search: false,
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        setCurrentOption(record);
                        setIsShowModal(true);
                        editDeviceForm.setFieldsValue(record);
                    }}>更新</a>
            ]
        }
    ];

    const [currentPage, setCurrentPage] = useState(0);
    const [pageSize, setPageSize] = useState(20);

    useEffect(() => {
        if (props.deviceConfig?.id) {
            setSelectRowKeys([props.deviceConfig.id]);
        }
        onFetchOrgTree();
        onFetchDeviceClass();
        onFetchDeviceTypeList();
        onFetchDeviceVersion();
    }, []);

    return <>
        <ProTable
            style={{ width: '100%' }}
            headerTitle="设备信息"
            actionRef={actionRef}
            rowKey="id"
            search={false}
            pagination={{
                current: currentPage,
                pageSize: pageSize,
                onChange: (page, pageSize) => {
                    setCurrentPage(page);
                    setPageSize(pageSize);
                }
            }}
            request={async (params) => {
                let data = [];
                let total = 0;
                await quickAPI.GetDeviceInfoPage(params).then((r) => {
                    data = r.data.data;
                    total = r.data.total;
                });
                data = data.filter(item => item.orgId === props.storeConfig.id);
                return {
                    data: data,
                    success: true,
                    total: total,
                };
            }}
            columns={columns}
            rowSelection={{
                type: 'radio',
                onChange: (selectedRowKeys, selectedRows) => {
                    setSelectRowKeys(selectedRowKeys);
                    props.onSelectedChange('deviceConfig', selectedRows[0]);
                },
                selectedRowKeys: selectedRowKeys
            }}
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    editDeviceForm.resetFields();
                    const temp = editDeviceForm.getFieldsValue();
                    temp.orgId = props.storeConfig.id;
                    temp.deviceLoc = props.storeConfig.store_Loc;
                    temp.deviceAddr = props.storeConfig.store_Addr;
                    editDeviceForm.setFieldsValue(temp);
                    setCurrentOption({ id: '' });
                    setIsShowModal(true);
                }}>
                    新建
                </Button>
            ]}
        />
        <Modal width={600} title={currentOption.id ? '编辑设备' : '新增设备'} visible={isShowModal} footer={false} onCancel={() => setIsShowModal(false)}>
            <Form
                layout="Horizontal"
                labelCol={{ span: 6 }}
                preserve={false}
                form={editDeviceForm}
                onFinish={onFinishSubmit}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item label={'设备名称'} name="deviceName" rules={[{ required: true, max: 50 }]}>
                    <Input />
                </Form.Item>

                <Form.Item label={'设备类型'} name="deviceTypeKey" rules={[{ required: true }]}>
                    <Select >
                        {deviceTypeList.map((item, index) => {
                            return (
                                <Select.Option index={index} value={item.code} key={item.code}>
                                    {item.value}
                                </Select.Option>
                            );
                        })}
                    </Select>
                </Form.Item>

                <Form.Item name="orgId" label="归属门店" rules={[{ required: true }]}>
                    <TreeSelect
                        disabled
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        treeData={orgTree}
                        placeholder="归属门店"
                        treeDefaultExpandAll
                    />
                </Form.Item>

                <div className={styles.add_row_content}>
                    <Form.Item label={'设备分类'} name="deviceTypeId" rules={[{ required: true }]} >
                        <Select style={{ width: '75%' }} >
                            {deviceClassList.map((item, index) => {
                                return (
                                    <Select.Option index={index} value={item.id} key={item.id}>
                                        {item.name}
                                    </Select.Option>
                                );
                            })}
                        </Select>
                    </Form.Item>
                    <Button type="primary" className={styles.add_row_btn} onClick={() => { setIsModalOpen(true); addDeviceTypeForm.resetFields(); }}>添加分类</Button>
                </div>

                <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.deviceTypeKey !== currentValues.deviceTypeKey}
                >
                    {({ getFieldValue }) =>
                        getFieldValue('deviceTypeKey') === 'TMC' ? (
                            <Form.Item name="deviceVersion" label="设备版本" initialValue="WorryFreeEdition">
                                <Select >
                                    {deviceVersion.map((item, index) => {
                                        return (
                                            <Select.Option index={index} value={item.code} key={item.code}>
                                                {item.name}
                                            </Select.Option>
                                        );
                                    })}
                                </Select>
                            </Form.Item>
                        ) : null
                    }
                </Form.Item>

                <Form.Item label={'设备坐标'} name="deviceLoc">
                    <Input placeholder="104.070734,30.575041" />
                </Form.Item>

                <Form.Item label={'状态'} name="status">
                    <Select placeholder="请选择状态" defaultValue={0}>
                        <OptGroup>
                            <Select.Option value={0}>正常</Select.Option>
                            <Select.Option value={1}>停用</Select.Option>
                        </OptGroup>
                    </Select>
                </Form.Item>

                <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.deviceTypeKey !== currentValues.deviceTypeKey}
                >
                    {({ getFieldValue }) =>
                        getFieldValue('deviceTypeKey') === 'TMC' ? (
                            <Form.Item label={'设备通道数量'} name="materialQuantity">
                                <InputNumber style={{ width: '100%' }} />
                            </Form.Item>
                        ) : null
                    }
                </Form.Item>

                <Form.Item label={'设备详细地址'} name="deviceAddr">
                    <Input placeholder="成都市武侯区桂溪街道环球中心N5-9111C" />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </Modal>

        <Modal title="添加设备分类" visible={isModalOpen} footer={false} onCancel={() => setIsModalOpen(false)}>
            <Form
                layout="vertical"
                onFinish={onSaveDeviceType}
                form={addDeviceTypeForm}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>
                <Form.Item label={"类型名称"} name="name" rules={[{ required: true, max: 50 }]} >
                    <Input />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    </>
}

export default DeviceConfig;
