import React, { useState, useEffect } from 'react';
import { Modal, Form, Row, Col, Select, Input, Divider, Table, TreeSelect, message } from 'antd'
import { SearchOutlined } from '@ant-design/icons'
import { connect } from 'umi'

import { dicFindUtils, DictBizType, createSystemTree } from '@/utils/utils'
import { dispatchHandle } from "@/utils/publicHandle";
import useFormTable from '@/useHooks/useFormTable';
import DeviceTree from '@/components/Customized/DeviceTree';

import style from '../index.less'

const { Option } = Select

const SelectDeviceModal = (props) => {
    const {
        dispatch,
        visible,
        loading,
        setVisible,
        selectDevice,
        type,
        dict: {
            dicTotalsList
        },
        statistical: {
            deviceList,
            supplierList,
            deviceSystemList,
            customList
        }
    } = props;
    const [form] = Form.useForm()
    const [selectedRowKeys, setSelectedRowKeys] = useState([])// 选中的行的key值
    const [selectedRow, setSelectedRow] = useState([])// 选中的行的key值
    const data = [{ name: "1" }, { name: "2" }]
    useEffect(() => {
        dispatchHandle(// 设备系统
            dispatch,
            'statistical/device_service_system_node_tree_post',
            {}
        )
        dispatchHandle(// 供应商
            dispatch,
            'statistical/common_service_t_supplier_info_post',
            {}
        )
        dispatchHandle(// 在用客户
            dispatch,
            'statistical/common_service_t_customer_info_post',
            {}
        )
    }, [])
    const getListItem = (payload = {}) => {
        dispatchHandle(
            dispatch,
            'statistical/device_service_device_post',
            payload,
        )
    }
    const { tableProps, search } = useFormTable(getListItem, {
        form
    })
    // 新增设备列表
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            key: 'index',
            render: (text, record, index) => <span>{index + 1}</span>
        },
        {
            title: '设备编号',
            dataIndex: 'code',
            key: 'code',
        },
        {
            title: '财产编码',
            dataIndex: 'belongingsCode',
            key: 'belongingsCode',
        },
        {
            title: '设备名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '类型',
            dataIndex: 'typeName',
            key: 'typeName',
        },
        {
            title: '设备系统',
            dataIndex: ['systemNode', 'name'],
            key: 'systemNodeName',
        },
        {
            title: '建筑',
            dataIndex: 'buildingName',
            key: 'buildingName',
        },
        {
            title: '型号规格',
            dataIndex: 'modelSpecification',
            key: 'modelSpecification'
        },
        {
            title: '供应商',
            dataIndex: 'supplierName',
            key: 'supplierName'
        },
        {
            title: '在用客户',
            key: 'activeCustomersName',
            align: 'center',
            dataIndex: 'activeCustomersName'

        },

    ];
    // 新增备件table所选项发生变化
    const rowSelection = {
        selectedRowKeys,
        type,
        onChange: (selectedRowKeys, selectedRows) => {
            console.log('标准selectedRowKeys changed: ', selectedRows, selectedRowKeys);
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRow(selectedRows)
        },
    };
    const handleOk = () => {
        // type === cycle 新增周期计划设备
        // type === special 新增专项计划设备
        selectDevice(selectedRow)
        setVisible(false)
        form.resetFields()
    }
    const handleCancel = () => {
        setVisible(false)
        form.resetFields()
    }
    // 设备系统
    const systemData = (deviceSystemList && createSystemTree(deviceSystemList, 'subList')) || [];
    // const systemData = deviceSystemList?.length > 0 ? deviceSystemList.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)
    // }) : []
    // 设备类型
    const deviceType = dicFindUtils(dicTotalsList, DictBizType.deviceType);
    return <Modal
        title="选择设备"
        visible={visible}
        destroyOnClose={true}
        width="80%"
        onOk={handleOk}
        onCancel={handleCancel}
    >
        <Form form={form} onValuesChange={search.submit} style={{ padding: '9px 0' }}>
            <Row justify="space-between" gutter={{ md: 24, xxl: 48 }}>
                <Col span={6}>
                    <Form.Item label="设备系统" name="systemNodeIdLike">
                        <TreeSelect
                            allowClear
                            placeholder="请选择"
                            treeData={systemData}
                            style={{ width: '100%' }}
                        />
                    </Form.Item>
                </Col>
                <Col span={5}>
                    <Form.Item label="类型" name="typeIdLike">
                        {/* <Select placeholder="请选择" allowClear>
                                {
                                    deviceType && deviceType.length > 0 && deviceType.map(i => <Option value={i.id} key={i.id}>{i.dicValue}</Option>)
                                }
                            </Select> */}
                        <DeviceTree />
                    </Form.Item>
                </Col>
                <Col span={5}>
                    <Form.Item label="供应商" name="supplierId">
                        <Select placeholder="请选择" allowClear>
                            {
                                supplierList && supplierList.length > 0 && supplierList.map(i => <Option value={i.id} key={i.id}>{i.supplierName}</Option>)
                            }
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={5}>
                    <Form.Item label="在用客户" name="activeCustomersId">
                        <Select
                            placeholder="请选择"
                            allowClear
                            showSearch
                            optionFilterProp="children"
                        >
                            {
                                customList && customList.length > 0 && customList.map(i => <Option key={i.id}>{i.name}</Option>)
                            }
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={4}>
                    <Form.Item label="查询" name='blurQuery'>
                        <Input placeholder="请输入设备名称/设备编号/财产编码" suffix={<SearchOutlined style={{ color: '#dadada' }} />} allowClear />
                    </Form.Item>
                </Col>
            </Row>
        </Form>
        <Divider style={{ margin: "0 0 10px" }} />
        <Table
            loading={loading}
            columns={columns}
            dataSource={deviceList.list}
            rowSelection={rowSelection}
            scroll={{
                x: 1300
            }}
            pagination={deviceList.pagination}
            {...tableProps}
            footer={() => {
                return (
                    <div
                        style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}
                    >
                        <span style={{ fontSize: 14 }}>
                            已选数量:<span style={{ margin: '0 10px', color: '#5ca6f3' }}>{selectedRowKeys.length}</span>
                        </span>
                    </div>
                );
            }}
        />
        {/* <p className={style.selected_num}><span>已选数量:</span><i>{selectedRowKeys.length}</i></p> */}
    </Modal>
}

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