import React, { useState, useRef, useEffect } from "react";
import { ResultFlowResult, BaseMap, Marker } from "@/components"
import { Select, Input, Button, Table, message, Pagination, Cascader, Modal, TreeSelect, Form, Row, Col } from 'antd'
import {
    pageSizeOptions
} from '@/config/character.config.js'
import moment from "moment";
import "./index.scss";
import { useSessionStorageState } from "ahooks"
import { SearchOutlined, DeleteOutlined, PlayCircleOutlined, EditOutlined, PlusCircleOutlined } from '@ant-design/icons';
import ajax from '@/services'
const { SHOW_PARENT } = TreeSelect;
function Fence(props) {
    // const configData = props.sysConfig["lib-deploy"] || {};
    const [form] = Form.useForm()
    const [ajaxLoading, setAjaxLoading] = useState(false)
    const [getModalData, setGetModalData] = useState({
        attendDistance: '',
        effective: ''
    })
    const [getEditModal, setGetEditModal] = useState({
        attendDistance: '',
        attend: '',
        attendName: ''
    })
    const roadSelectRef = useRef()
    const [editModalVisible, setEditModalVisible] = useState(false)
    const [editStatus, setEditStatus] = useState(false)
    const [storeData, setStoreData] = useState([{ label: '全部', value: -1 }]) //所属商户
    const [getStatus, setGetStatus] = useState(2)
    const [deviceTypeData, setDeviceTypeData] = useState([])
    const [resultData, setResultData] = useState({
        data: [],
        total_records: 0,
        export_url: '',
        process_url: ""
    })
    const parameter = {
        address: '',
        device_name: '',
        road_name: '',//路段名称
        operator: -1,//运营商
        export: false,
        road_id: '',//所属路段
        pn: 1,
        length: Number(pageSizeOptions[0]),  // 每页条数
    }
    const [formData, setFormData] = useState(parameter)
    const [formSubmitData, setFormSubmitData] = useState({
        address: "",
        create_time: "",
        device_name: "",
        ip_address: "",
        network_mode: "",
        operator: "",
        id: '',
        password: "",
        port: "",
        road_name: "",
        road_id: "",
        type: "",
        user_name: "",
        video_port: ""
    })
    const [lastFormData, setLastFormData] = useState(formData)
    const lastFormDataRef = useRef(formData)
    const getOperatorData = () => {
        ajax.getOperator().then((e) => {
            setStoreData([
                ...storeData,
                ...e.data
            ])
        })
    }
    const handlePlay = (item) => {
        message.error(`播放数据暂未对接`)
    }
    const handleDel = (item, index) => {
        Modal.confirm({
            title: '确认删除？',
            content: `是否确认删除设备：${item.device_name} ？`,
            icon: <DeleteOutlined />,
            onOk: () => {
                handleDelToServer(item.id).then((msg) => {
                    message.success(msg || '删除成功')
                    let copyData = resultData.data
                    copyData.splice(index, 1)
                    setResultData({
                        ...resultData,
                        data: [...copyData]
                    })
                }).catch((err) => {
                    message.error(err)
                })
            }
        })
    }
    const getRoadById = (id) => {
        return new Promise((resolved, rejected) => {
            ajax.getAllRoad({ operator_id: id }).then((e) => {
                if (e.status == 20000) {
                    resolved(e.data)
                }
            }).catch((err) => {
                console.error(err)
                rejected(err)
            })
        })
    }
    const handleDelToServer = (id) => {
        return new Promise((resolved, rejected) => {
            ajax.nvrDel({ id: id }).then((e) => {
                if (e.status == 20000) {
                    resolved(e.message)
                }
            }).catch((err) => {
                rejected(err)
            })
        })
    }
    const handleEdit = (item) => {
        setEditStatus(true)
        getRoadById(item.operator_id).then((data) => {
            setRoadData(data)
        })
        form.setFieldsValue({
            ...item
        })
        setEditModalVisible(true)
    }
    const editModalCancel = () => {
        setEditModalVisible(false)
        form.resetFields()
    }
    //列表
    const handleColumns = (tab) => {
        let result = [...tableColumns];
        switch (tab) {
            case '1':
                result.splice(9, 1)
                break;

        }
        return result;
    }
    //列表
    const tableColumns = [{
        title: '序号',
        width: 60,
        render: (_, record, index) => {
            return index + 1
        }
    },
    {
        title: '设备名称',
        dataIndex: 'device_name'
    },
    {
        title: '所属商户',
        dataIndex: 'operqator'
    },
    {
        title: '所属路段',
        dataIndex: 'road_name',
    },
    {
        title: '地址',
        dataIndex: 'address',
    },
    {
        title: '网络模式',
        dataIndex: 'network_mode',
    },
    {
        title: 'IP地址/设备编码',
        width: 145,
        dataIndex: 'ip_address',
    },
    {
        title: '端口号',
        dataIndex: 'port',
    },
    {
        title: '视频端口号',
        width: 110,
        dataIndex: 'video_port',
    },
    {
        title: '用户名',
        dataIndex: 'user_name',
    },
    {
        title: '密码',
        dataIndex: 'password'
    },
    {
        title: '创建日期',
        dataIndex: 'create_time',
        width: 110
    },
    {
        title: '操作',
        width: 135,
        render: (text, record, index) => {
            return <>
                <div className="action-wrapper">
                    <Button type="primary" style={{ background: 'red', borderColor: 'red' }} shape="circle" size="middle" icon={<DeleteOutlined />} onClick={() => handleDel(record, index)} />
                    <Button type="primary" shape="circle" size="middle" icon={<PlayCircleOutlined />} onClick={() => handlePlay(record)} />
                    <Button type="primary" shape="circle" s size="middle" icon={<EditOutlined />} onClick={() => handleEdit(record)} />
                </div>
            </>
        }
    }
    ]
    // 获取列表数据
    const getData = (data = formData) => {
        setAjaxLoading(true)
        ajax.getNVRListData(data).then(res => {
            setAjaxLoading(false)
            if (res.status === 20000) {
                let resDataArr = res?.data?.list?.length ? res.data.list.map((item) => {
                    item.key = item.id
                    return item
                }) : []
                setResultData({
                    ...resultData,
                    data: resDataArr,
                    total_records: res.data.total
                })

            } else {
                setResultData({
                    data: [],
                    total_records: 0,
                    export_url: '',
                    process_url: ""
                })
                message.error(res.message)
            }
        }, err => {
            console.log(err)
        })
    }
    const getDeviceType = () => {
        ajax.getDeviceTypeList().then((e) => {
            setDeviceTypeData([
                ...deviceTypeData,
                ...e.data
            ])
        })
    }
    //切换分页
    const changePn = (pn, length) => {
        if (lastFormData.length === length) {
            setLastFormData(Object.assign({}, lastFormData, { pn: pn }))
            lastFormDataRef.current = Object.assign({}, lastFormData, { pn: pn })
            getData(Object.assign({}, lastFormData, { pn: pn }))
        }
    }
    //切换每页条数
    const changeLength = (pn, length) => {
        setFormData(Object.assign({}, formData, { pn: 1, length: length }))
        setLastFormData(Object.assign({}, lastFormData, { pn: 1, length: length }))
        lastFormDataRef.current = Object.assign({}, lastFormData, { pn: 1, length: length })
        getData(Object.assign({}, lastFormData, { pn: 1, length: length }))
    }
    //检索数据
    const getSearchData = (data = formData) => {
        getData(data)
    }
    //重置表单
    const formReset = () => {
        setFormData({
            ...parameter
        })
        getData({ ...parameter })
    }

  
    const handleEditFinish = () => {
        console.log('form finish')
    }
    const nvrUpdate = (params) => {
        return new Promise((resolved, rejected) => {
            ajax.nvrUpdate(params).then((e) => {
                if (e.status == 20000) {
                    resolved(e.message)
                }
            }).catch(err => {
                rejected(err)
            })
        })
    }
    const nvrAdd = (params) => {
        return new Promise((resolved, rejected) => {
            ajax.nvrAdd(params).then((e) => {
                if (e.status == 20000) {
                    resolved(e.message)
                }
            }).catch(err => {
                rejected(err)
            })
        })
    }
    const handleAdd = () => {
        setEditStatus(false)
        form.resetFields()
        setEditModalVisible(true)
    }
    const handleRoadChange = (v) => {
        ajax.getRoadInfo({ road_id: v }).then((e) => {
            if (e.status == 20000) {
                form.setFieldValue('address', e.data.address)
                form.setFieldValue('lng_lat', e.data.lng_lat)
            }
        })
    }
    const [roadData, setRoadData] = useState([]);
    const handleOperaChange = (id) => {
        // let roadSelect = document.querySelectorAll('.fenceModal .road-selector .ant-select-selection-item')
        // if (roadSelect.length) {
        //     roadSelect[0].innerText = ''
        // }
        setFormSubmitData({
            ...formSubmitData,
            road_name: undefined
        })
        form.setFieldValue('road_name', '')
        getRoadById(id).then((data) => {
            setRoadData(data)
        })
    }
    const handleSubmit = () => {
        if (editStatus) { // 编辑
            nvrUpdate(form.getFieldsValue()).then((msg) => {
                message.success(msg || '设备更新成功')
                setEditModalVisible(false)
                getData()
            })
        } else { // 新增
            nvrAdd(form.getFieldsValue()).then((msg) => {
                message.success(msg || '设备添加成功')
                setEditModalVisible(false)
                getData()
            })
        }
    }
    const [sessionTabList, setSessionTabList] = useSessionStorageState('nvrMgm', {
        value: {
        }
    })
    useEffect(() => {
        if (sessionTabList && Object.values(sessionTabList).length > 0) {
            setFormData({
                address: sessionTabList?.address,
                device_name: sessionTabList?.device_name,
                road_name: sessionTabList?.road_name,
                operator: sessionTabList?.operator
            })
        }
    }, [])
    useEffect(() => {
        setSessionTabList({
            ...formData
        })
    }, [formData])
      // 获取下拉菜单
  const getSelectList = () => {
    // 商户名称
    ajax.getOperator().then(
      (res) => {
        if (parseInt(res?.status) === 20000) {
          setStoreData(res?.data || []);
        } else {
          message.error(res?.message);
        }
      },
      (err) => {
        console.log(err);
      }
    );
  };
  const getAllRoad = (id, setData) => {
    ajax.getAllRoadByOperatort({ operator: id }).then(
      (res) => {
        setData(res?.data || []);
      },
      (err) => {
        console.log(err);
      }
    );
  };
    useEffect(() => {
        getSelectList();
        if (formData?.operator) {
          getAllRoad(formData?.operator, setRoadData);
        }
      }, []);
    useEffect(() => {
        getData()
        getOperatorData()
        getDeviceType()
    }, [])

    return <>
        <div className="paid-fence">
            <div className="paid-search">
                <label className="search">查询条件</label>
                <div className="yisa-search">
                    <label>设备名称</label>
                    <Input
                        placeholder="请输入设备名称"
                        value={formData.device_name}
                        style={{ width: 260, marginLeft: 14 }}
                        onChange={(e) => setFormData({ ...formData, device_name: e.target.value })}
                    />
                </div>
                <div className="yisa-search">
                    <label>商户名称</label>
                    <Select
                        style={{ width: 260, marginLeft: 14 }}
                        placeholder="请选择"
                        value={formData.operator}
                        options={storeData}
                        onChange={(v) => setFormData({ ...formData, operator: v })}
                    />
                </div>
                <div className="yisa-search">
                    <label>路段名称</label>
                    <Input
                        placeholder="请输入路段名称"
                        value={formData.road_name}
                        style={{ width: 260, marginLeft: 14 }}
                        onChange={(e) => setFormData({ ...formData, road_name: e.target.value })}
                    />
                </div>
                <div className="yisa-search">
                    <label>地址</label>
                    <Input
                        placeholder="请输入地址"
                        value={formData.address}
                        style={{ width: 260, marginLeft: 42 }}
                        onChange={(e) => setFormData({ ...formData, address: e.target.value })}
                    />
                </div>
                <div className="timePicker yisa-search">
                    <div className="btnBox">
                        <Button type="primary" className="yisa-btn colorBtn" icon={<SearchOutlined />} onClick={() => { getSearchData() }}>
                            搜索
                        </Button>
                        <Button type="primary" className="yisa-btn colorReset" icon={<DeleteOutlined />} onClick={() => { formReset() }}>
                            清空
                        </Button>
                        <Button type="primary" className="yisa-btn colorBtn" icon={<PlusCircleOutlined />} onClick={() => { handleAdd() }}>
                            添加
                        </Button>
                    </div>
                </div>
            </div>
            <div className="paid-result">
                <div className="result">
                    <span className="font">共检索到<em>{resultData.total_records}</em>条结果</span>
                    <ResultFlowResult ajaxLoad={ajaxLoading} resultData={resultData.data ? resultData.data : []}>
                        <Table
                            bordered
                             className='yisa-table'
                            dataSource={resultData.data}
                            columns={
                                handleColumns()
                            }
                            scroll={{ y: 660 }}
                            // rowKey={record => record.cap_id + "_" + record.bk_id}
                            pagination={false}
                            loading={ajaxLoading}
                        />
                        <Pagination
                            className="pagination-common"
                            showSizeChanger
                            showQuickJumper
                            showTotal={() => `共 ${resultData.total_records} 条`}
                            total={resultData.total_records}
                            current={lastFormData.pn}
                            pageSize={lastFormData.length}
                            pageSizeOptions={pageSizeOptions}
                            onChange={changePn}
                            onShowSizeChange={changeLength}
                        />
                    </ResultFlowResult>
                </div>
            </div>
            <Modal
                open={editModalVisible}
                onCancel={editModalCancel}
                footer={null}
                className="fence"
                title={editStatus ? '设备编辑' : '新增设备'}
            >
                <div className="fenceModal">
                    <div className="form-container">
                        <Form
                            form={form}
                            labelCol={{ span: 10 }}
                            name="edit-form"
                            onFinish={handleEditFinish}
                        >
                            <Row>
                                <Col span={12}>
                                    <Form.Item
                                        label={"设备名称"}
                                        name={"device_name"}
                                        rules={[{ required: true, message: '设备名称不能为空' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    {/* <Form.Item 
                                            label={"所属商户"}
                                            name={"operator"}
                                            rules={[{ required: true, message: '所属商户不能为空' }]}
                                        >
                                            <Input/>
                                        </Form.Item> */}
                                    <Form.Item
                                        label={"设备类型"}
                                        name={"id"}
                                        rules={[{ required: true, message: '设备类型不能为空' }]}
                                    >
                                        <Select
                                            ref={roadSelectRef}
                                            placeholder="请选择"
                                            value={form.device_id}
                                            onChange={(v) => console.log(v)}
                                            options={deviceTypeData}
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    {/* <Form.Item 
                                            label={"所属路段"}
                                            name={"road_name"}
                                            rules={[{ required: true, message: '所属路段不能为空' }]}
                                        >
                                            <Input/>
                                        </Form.Item> */}
                                    <Form.Item
                                        label={"所属商户"}
                                        name={"operator_id"}
                                        rules={[{ required: true, message: '所属商户不能为空' }]}
                                    >
                                        <Select
                                            placeholder="请选择"
                                            value={form.operator_id}
                                            onChange={handleOperaChange}
                                            options={storeData.filter((item) => item.label != '全部')}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={"所属路段"}
                                        name={"road_name"}
                                        rules={[{ required: true, message: '所属路段不能为空' }]}
                                    >
                                        <Select
                                            ref={roadSelectRef}
                                            placeholder="请选择"
                                            className="road-selector"
                                            value={form.road_name}
                                            onChange={handleRoadChange}
                                            options={roadData}
                                        />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item
                                        label={"经纬度"}
                                        name={"lng_lat"}
                                        rules={[{ required: true, message: '经纬度不能为空' }]}
                                    >
                                        <Input disabled />
                                    </Form.Item>

                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={"地址"}
                                        name={"address"}
                                        rules={[{ required: true, message: '地址不能为空' }]}
                                    >
                                        <Input disabled />
                                    </Form.Item>

                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item
                                        label={"网络模式"}
                                        name={"network_mode"}
                                        rules={[{ required: true, message: '网络模式不能为空' }]}
                                    >
                                        <Select
                                            placeholder="请选择"
                                            value={form.network_mode}
                                            options={[
                                                {
                                                    value: "固网",
                                                    label: "固网"
                                                },
                                                {
                                                    value: '无线网络',
                                                    label: "无线网络"
                                                }
                                            ]}
                                        />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={"视频端口号"}
                                        name={"video_port"}
                                        rules={[{ required: true, message: '视频端口号不能为空' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item
                                        label={"IP地址"}
                                        name={"ip_address"}
                                        rules={[{ required: true, message: 'ip地址不能为空' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={"端口号"}
                                        name={"port"}
                                        rules={[{ required: true, message: '端口号不能为空' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col span={12}>
                                    <Form.Item
                                        label={"用户名"}
                                        name={"user_name"}
                                        rules={[{ required: true, message: '用户名不能为空' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={12}>
                                    <Form.Item
                                        label={"密码"}
                                        name={"password"}
                                        rules={[{ required: true, message: '密码不能为空' }]}
                                    >
                                        <Input />
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </div>

                    <div className="submitBtn">
                        <button type="primary" className="submit" onClick={() => handleSubmit()}>
                            确定
                        </button>
                        <button type="primary" className="cancel" onClick={() => editModalCancel()}>
                            取消
                        </button>
                    </div>
                </div>
            </Modal>
        </div>
    </>
}

export default Fence;