import React, { useEffect, useState } from 'react'
import { Modal, Form, Select, Row, Col, Input, Divider, Button, TreeSelect, Popconfirm, message } from 'antd'
import { BlockOutlined, QuestionCircleFilled, CloseCircleFilled } from '@ant-design/icons'
import { connect } from 'umi'
import _ from 'lodash'
import classnames from "classnames"

import TransferTables from './TransferTables'
import style from './index.less'
import { dispatchHandle } from '@/utils/publicHandle'
import { dicFindUtils, DictBizType } from '@/utils/utils'
import useFormTable from '@/useHooks/useFormTable'
import AssociatedOptVolume from './AssociatedOptVolume'

const { Option } = Select

const AddDeviceGroup = (props) => {
    const {
        dispatch,
        visible,
        setVisible,
        type,
        search,
        editId,
        dict: { dicTotalsList },
    } = props;
    const [form] = Form.useForm();
    const [leftForm] = Form.useForm()
    const [typeValue, setTypeValue] = useState()
    const [systemData, setSystemData] = useState([])
    const [leftList, setLeftList] = useState([])
    const [rightList, setRightList] = useState([])
    const [typeKey, setTypeKey] = useState()
    const [volumeVisible, setVolumeVisible] = useState(false)
    const [selectInfo, setSelectInfo] = useState({})
    const handleOk = (e) => {
        e.preventDefault()
        form.validateFields().then(values => {
            const deviceIds = leftList.map(item => item.id)
            const payload = {
                deviceIds,
                ...values,
                meterAttrId: selectInfo?.modelId || ''
            }
            if (type === 'add') {
                dispatchHandle(
                    dispatch,
                    'opsDevice/device_service_device_group_post',
                    payload,
                    () => {
                        search.submit()
                    }
                )
            } else if (type === 'edit') {
                payload.id = editId
                dispatchHandle(
                    dispatch,
                    'opsDevice/device_service_device_group_put',
                    payload,
                    () => {
                        search.submit()
                    }
                )
            }
            form.resetFields()
            setVisible(false)
            setLeftList([])
            setTypeValue()
            setTypeKey()
        })
            .catch(err => { })
    }
    const handleCancel = () => {
        form.resetFields()
        setVisible(false)
        setTypeValue()
        setTypeKey()
        setLeftList([])
    }
    // 类型选择
    const typeChange = (value, option) => {
        setTypeValue(value)
        setTypeKey(option.key || '')
    }
    // 未关联设备组设备列表
    const getListItem = (payload = {}) => {
        dispatchHandle(
            dispatch,
            'opsDevice/device_service_device_post_group',
            payload,
            res => {
                const arr = _.differenceBy(res, leftList, 'id')
                console.log(arr, leftList)
                setRightList(arr)
            }
        )
    }
    const { tableProps: rightTableProps, search: rightSearch } = useFormTable(getListItem, { form: leftForm })
    useEffect(() => {
        dispatchHandle(// 设备系统
            dispatch,
            'opsDevice/device_service_system_tree_post',
            {},
            res => {
                if (res && res.length > 0) {
                    const data = res.map((item, index) => {
                        item.id = `${index}-0`;
                        item.selectable = false;
                        const itemJson = JSON.stringify(item);
                        const jsonData = itemJson
                            .replace(/\bname\b/g, "title")
                            .replace(/\bid\b/g, "value")
                            .replace(/\bsystemNodeList\b/g, "children")
                            .replace(/\bsubList\b/g, "children");
                        return JSON.parse(jsonData)
                    })
                    setSystemData(data || [])
                }
            }
        )
        if (visible) {
            if (type === 'edit') {
                dispatchHandle(
                    dispatch,
                    'opsDevice/device_service_device_group_id_get',
                    { id: editId },
                    res => {
                        if (res) {
                            form.setFieldsValue({ ...res })
                            setTypeValue(res.type)
                            setSelectInfo({deviceName: res?.meterName || '' , modelName: res?.meterAttrName || ''})
                            if (res?.type === 539) {
                                setTypeKey('yunweirongliang')
                            }
                            if (res.deviceList && res.deviceList.length > 0) {
                                setLeftList([...leftList, ...res.deviceList])
                                dispatch({
                                    type: 'opsDevice/setModelsState',
                                    payload: {
                                        leftDeviceList: res?.deviceList || [],
                                    }
                                });
                            }
                        }
                    }
                )
            }
            getListItem({ noDeviceGroup: true })
        }
    }, [visible])
    const associatedVolumeAction = () => {
        setVolumeVisible(true)
    }
    const selectMeterArr = (data) => {
        setSelectInfo(data)
    }
    console.log(selectInfo)
    const deviceGroupType = dicFindUtils(dicTotalsList, DictBizType.deviceGroupType)
    const opsCapacityType = dicFindUtils(dicTotalsList, DictBizType.opsCapacityType)
    const unitType = dicFindUtils(dicTotalsList, DictBizType.unitType)
    return <Modal
        title={`${type === 'add' ? '添加' : '编辑'}设备组`}
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="85%"
    >
        <Form form={form}>
            <Row gutter={{ md: 8, xxl: 16 }}>
                <Col span={6}>
                    <Form.Item name="name" label="设备组名" rules={[{ required: true }]}>
                        <Input placeholder="请输入" allowClear />
                    </Form.Item>
                </Col>
                <Col span={6}>
                    <Form.Item name="code" label="编号" rules={[{ required: true }]}>
                        <Input placeholder="请输入" allowClear />
                    </Form.Item>
                </Col>
                <Col span={6}>
                    <Form.Item name="type" label="设备组类型" rules={[{ required: true }]}>
                        <Select
                            placeholder="请选择"
                            allowClear
                            onChange={typeChange}
                            showSearch
                            optionFilterProp="children"
                        >
                            {
                                deviceGroupType && deviceGroupType.length > 0 && deviceGroupType.map(i => <Option value={i.id} key={i.dicKey}>{i.dicValue}</Option>)
                            }
                        </Select>
                    </Form.Item>
                </Col>
                {
                    typeKey === 'yunweirongliang' ? (
                        <>
                            <Col span={6}>
                                <Form.Item name="icon" label="运维容量类型" rules={[{ required: true }]}>
                                    <Select
                                        placeholder="请选择"
                                        allowClear
                                        showSearch
                                        optionFilterProp="children"
                                    >
                                        {
                                            opsCapacityType && opsCapacityType.length > 0 && opsCapacityType.map(i => <Option value={i.dicKey} key={i.id}>{i.dicValue}</Option>)
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={6}>
                                <Form.Item name="unit" label="运维容量单位" rules={[{ required: true }]}>
                                    <Select
                                        placeholder="请选择"
                                        allowClear
                                        showSearch
                                        optionFilterProp="children"
                                    >
                                        {
                                            unitType && unitType.length > 0 && unitType.map(i => <Option value={i.id} key={i.id}>{i.dicValue}</Option>)
                                        }
                                    </Select>
                                </Form.Item>
                            </Col>
                            <Col span={10} style={{display: 'flex'}}>
                                <Button onClick={associatedVolumeAction} type="primary" icon={<BlockOutlined />}>关联实际运行容量</Button>
                                <QuestionCircleFilled style={{margin: '10px 16px 0' , fontSize: 18}}/>
                                <div className={style.associatedParams}>
                                    {
                                        (selectInfo?.deviceName && selectInfo?.modelName) && (<>
                                            <span className={classnames('btn_common', 'ellipsis_list')}>{selectInfo?.deviceName || ''}</span>
                                            <span className={classnames('btn_common', 'ellipsis_list')}>{selectInfo?.modelName || ''}</span>
                                            <CloseCircleFilled onClick={()=>setSelectInfo({})} style={{color: 'red',margin: '9px 0 0 5px'}} />
                                        </>)
                                    }
                                </div>
                            </Col>
                        </>
                    ) : null
                }
            </Row>
        </Form>
        <Divider style={{ margin: '0 0 24px' }} />
        <Row className={style.transfer_table} gutter={[8, 16]}>
            <TransferTables
                style={{ width: '100%' }}
                systemData={systemData}
                leftList={leftList}
                setLeftList={setLeftList}
                rightList={rightList}
                setRightList={setRightList}
                getListItem={getListItem}
                rightTableProps={rightTableProps}
                rightSearch={rightSearch}
                rForm={leftForm}
            />
        </Row>
        <AssociatedOptVolume visible={volumeVisible} setVisible={setVolumeVisible} selectMeterArr={selectMeterArr} />
    </Modal>
}

export default connect(({ opsDevice, dict, loading }) => ({
    opsDevice, dict,
    loading: loading.effects['opsDevice/device_service_device_post']
}))(AddDeviceGroup);