import React, { useState, useRef, useEffect } from "react";
import { ResultFlowResult } from "@/components"
import { Select, Input, Button, Table, message, Pagination, Popover, Modal, Col, Row, Form, Tabs } from 'antd'
import {
  pageSizeOptions
} from '@/config/character.config.js'
import { SearchOutlined, DeleteOutlined, PlayCircleOutlined, EditOutlined, PlusCircleOutlined, InfoCircleOutlined } from '@ant-design/icons';
import ajax from '@/services'
import "./index.scss";
import { useSessionStorageState } from "ahooks"
function Road(props) {
  const [form] = Form.useForm()
  const [ajaxLoading, setAjaxLoading] = useState(false)
  const [deviceDetail, setDeviceDetail] = useState({})
  const [editModalVisible, setEditModalVisible] = useState(false)
  const [editStatus, setEditStatus] = useState(false)
  const [storeData, setStoreData] = useState([]) //所属商户
  const [deviceTypeData, setDeviceTypeData] = useState([{ label: '全部', value: -1 }]) //设备类型
  const [brandData, setBrandData] = useState([{ label: '全部', value: -1 }]) // 品牌list
  const [resultData, setResultData] = useState({
      data: [],
      total_records: 0,
      export_url: '',
      process_url: ""
  })
  const parameter = {
      device_name: '',
      device_code: '',
      pole_position_code: '',
      type_id: -1, //设备类型
      road_name: '',
      operator: "0", //所属商户
      operate_status: -1, //运营状态
      device_status: -1, //设备状态
      pn: 1,
      length: Number(pageSizeOptions[0]),  // 每页条数
  }
  const [formData, setFormData] = useState(parameter)
  const [lastFormData, setLastFormData] = useState(formData)
  const lastFormDataRef = useRef(formData)
  const getOperatorData = () => {
      ajax.getOperator().then((e) => {
          setStoreData([
              ...storeData,
              ...e.data
          ])
      })
  }
  const getDeviceType = () => {
    ajax.getDeviceTypeList().then((e) => {
        setDeviceTypeData([
            ...deviceTypeData,
            ...e.data
        ])
    })
  }
  const getBrandData = () => {
      ajax.getAllBrandNameList().then((e) => {
          setBrandData([
              ...brandData,
              ...e.data
          ])
      })
  }

  const handleDelToServer = (id) => {
      return new Promise((resolved, rejected) => {
          ajax.nvrDel(id).then((e) => {
              if (e.status == 20000) {
                  resolved(e.message)
              }
          }).catch((err) => {
              rejected(err)
          })
      })
  }

  const getDeviceDetail = (id) => {
    return new Promise((resolved, rejected) => {
        ajax.getDeviceDimensionDetail({id: id}).then((e) => {
            if (e.status == 20000) {
                resolved(e.data)
            }
        }).catch((err) => {
            rejected(err)
        })
    })
  }
  const handleEdit = (item) => {
      getDeviceDetail(item.id).then((data) => {
        setEditStatus(true)
        form.setFieldsValue({
            ...data
        })
        setDeviceDetail(data)
        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: '设备名称',
        dataIndex: 'name'
    },
    {
        title: '设备编号',
        dataIndex: 'code'
    },
    {
        title: '设备类型',
        dataIndex: 'type_name',
    },
    {
        title: '所属路段',
        dataIndex: 'road_name',
    },
    {
        title: '对应杆位号',
        dataIndex: 'pole_position_code',
    },
    {
        title: '区域',
        dataIndex: 'region_name',
    },
    {
        title: '设备厂商',
        dataIndex: 'operqator',
    },
    {
        title: '运营状态',
        dataIndex: 'operate_status',
    },
    {
        title: '设备状态',
        dataIndex: 'device_status',
        render: (text, record, index) => {
            return (
                <div className="device_status">
                    <div className={(text == '在线' || text == '上线') ? 'text-online' : 'text-offline'}>{text}</div>
                </div>
            )
        }
    },
    {
        title: '更新时间',
        dataIndex: 'update_time',
    },
    {
        title: '操作',
        width: 135,
        // render: (text, record, index) => {
        //     return <>
        //         <div className="action-wrapper">
        //             <Button type="primary" shape="circle" s size="middle" icon={<InfoCircleOutlined />} onClick={() => handleEdit(record)}/>
        //         </div>
        //     </>
        // },
        render: (text, record) => {
            return <>
                <Popover content={
                    <div className="black">
                        <div className="yisa-btn" onClick={() => handleEdit(record)}>查看设备</div>
                    </div>}>
                    <Button type="primary" size="middle">操作</Button>
                </Popover>
            </>
        },
    }
  ]

  // 获取列表数据
  const getData = (data = formData) => {
      setAjaxLoading(true)
      ajax.getDeviceDimensionList(data).then(res => {
          setAjaxLoading(false)
          if (res.status === 20000) {
              let resDataArr = 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 changePn = (pn, length) => {
      if (lastFormData.length === length) {
        setFormData(Object.assign({}, formData, { pn: pn, length: length}))
          setLastFormData(Object.assign({}, lastFormData, { pn: pn, length: length }))
          lastFormDataRef.current = Object.assign({}, lastFormData, { pn: pn , length: length})
          getData(Object.assign({}, formData, { pn: pn, length: length }))
      }
  }
  //切换每页条数
  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({}, formData, { pn: 1, length: length }))
  }
  //检索数据
  const getSearchData = (data = formData) => {
      getData(data)
  }
  //重置表单
  const formReset = () => {
      setFormData({
          ...parameter
      })
      getData({...parameter})
  }

  const handleExport = () => {
    ajax.deviceDimensionExport(formData).then(e => {
        if (e.status == 20000) {
            window.open(e.data.url)
        }
    })
  }

 
  const brandEdit = (params) => {
      return new Promise((resolved, rejected) => {
          ajax.brandEdit(params).then((e) => {
              if (e.status == 20000) {
                  resolved(e.message)
              }
          }).catch(err => {
              rejected(err)
          })
      })
  }
  const brandAdd = (params) => {
      return new Promise((resolved, rejected) => {
          ajax.brandAdd(params).then((e) => {
              if (e.status == 20000) {
                  resolved(e.message)
              }
          }).catch(err => {
              rejected(err)
          })
      })
  }
  const [sessionTabList, setSessionTabList] = useSessionStorageState('equipmentStatus', {
    value: {
    }
})
useEffect(() => {
    if (sessionTabList && Object.values(sessionTabList).length > 0) {
        setFormData({
            device_name: sessionTabList?.device_name,
            device_code: sessionTabList?.device_code,
            pole_position_code: sessionTabList?.pole_position_code,
            type_id: -1,
            road_name: sessionTabList?.road_name,
            operator: "0",
            device_status: -1,
            operate_status: -1
        })
    }
}, [])
useEffect(() => {
    setSessionTabList({
        ...formData
    })
}, [formData])
  useEffect(() => {
      getData()
      getOperatorData()
      getDeviceType()
      getBrandData()
  }, [])
  return (
    <>
      <div className="road-container">
          <div className="road-search">
            <label className="search">查询条件</label>
            <div className="yisa-search">
              <label>设备名称</label>
              <Input
                placeholder="请输入设备名称"
                style={{ width: 260, marginLeft: 14 }}
                value={formData.device_name}
                onChange={(e) => setFormData({...formData, device_name: e.target.value})}
              />
            </div>
            <div className="yisa-search">
              <label>设备编号</label>
              <Input
                placeholder="请输入设备编号"
                style={{ width: 260, marginLeft: 14 }}
                value={formData.device_code}
                onChange={(e) => setFormData({...formData, device_code: e.target.value})}
              />
            </div>
            <div className="yisa-search">
              <label>对应杆位</label>
              <Input
                placeholder="请输入对应杆位"
                style={{ width: 260, marginLeft: 14 }}
                value={formData.pole_position_code}
                onChange={(e) => setFormData({...formData, pole_position_code: e.target.value})}
              />
            </div>
            <div className="yisa-search">
                <label>设备类型</label>
                <Select
                    style={{ width: 260, marginLeft: 14 }}
                    placeholder="请选择"
                    value={formData.type_id}
                    options={deviceTypeData}
                    onChange={(v) => setFormData({...formData, type_id: 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>
              <Select
                style={{ width: 260, marginLeft: 42 }}
                placeholder="请选择"
                value={formData.operator}
                options={storeData}
                onChange={(v) => setFormData({...formData, operator: v})}
              />
            </div>
            <div className="yisa-search">
              <label>运营状态</label>
              <Select
                style={{ width: 260, marginLeft: 14 }}
                placeholder="请选择"
                value={formData.operate_status}
                options={[
                  {
                    value: -1,
                    label: '全部'
                  },
                  {
                    value: '1',
                    label: '上线'
                  }, {
                    value: '2',
                    label: '下线'
                  }
                ]}
                onChange={(v) => {
                    if (v == 2) {
                        setFormData({...formData, operate_status: v, device_status: -1})
                    } else {
                        setFormData({...formData, operate_status: v})
                    }
                }}
              />
            </div>
            {
                formData.operate_status != 2 ? (
                    <div className="yisa-search">
                        <label>设备状态</label>
                        <Select
                            style={{ width: 260, marginLeft: 14 }}
                            placeholder="请选择"
                            value={formData.device_status}
                            options={[
                            {
                                value: -1,
                                label: '全部'
                            },
                            {
                                value: '1',
                                label: '在线'
                            }, {
                                value: '2',
                                label: '离线'
                            }
                            ]}
                            onChange={(v) => setFormData({...formData, device_status: v})}
                        />
                        </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" icon={<PlusCircleOutlined />} onClick={() => { handleAdd() }}>
                        添加
                    </Button> */}
                </div>
            </div>
        </div>
        <div className="road-result">
            <div className="result">
                <div className="result-title">
                    <span className="font">共检索到<em>{resultData.total_records}</em>条结果</span>
                    <div className="export-btn" onClick={handleExport}>导出</div>
                </div>
                <ResultFlowResult ajaxLoad={ajaxLoading} resultData={resultData.data ? resultData.data : []}>
                    <Table
                        bordered
                         className='yisa-table'
                        dataSource={resultData.data}
                        columns={
                            handleColumns()
                        }
                        scroll={{y: 560}}
                        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="device-detail"
            title={'设备详情'}
        >
            <div className="device-detail-container">
                <Tabs
                    className="yisa-tabs"
                    defaultActiveKey={1}
                    destroyInactiveTabPane={true}
                    items={[
                        {
                            label: `设备基本信息`,
                            key: 1,
                            children: (
                                <>
                                    <div className="device-detail-wrapper">
                                        <div className="device-row">
                                            <div className="device-item">
                                                <div className="device-label">设备名称：</div>
                                                <div className="device-content">{deviceDetail.name}</div>
                                            </div>
                                            <div className="device-item">
                                                <div className="device-label">硬件编码：</div>
                                                <div className="device-content">{deviceDetail.code}</div>
                                            </div>
                                        </div>
                                        <div className="device-row">
                                            <div className="device-item">
                                                <div className="device-label">设备类型：</div>
                                                <div className="device-content">{deviceDetail.type_name}</div>
                                            </div>
                                            <div className="device-item">
                                                <div className="device-label">设备品牌：</div>
                                                <div className="device-content">{deviceDetail.brand_name}</div>
                                            </div>
                                        </div>
                                        <div className="device-row">
                                            <div className="device-item">
                                                <div className="device-label">设备功能：</div>
                                                <div className="device-content">{deviceDetail.function}</div>
                                            </div>
                                            <div className="device-item">
                                                <div className="device-label">备注：</div>
                                                <div className="device-content">{deviceDetail.note}</div>
                                            </div>
                                        </div>
                                        <div className="device-row">
                                            <div className="device-item">
                                                <div className="device-label">对应泊位号：</div>
                                                <div className="device-content">{deviceDetail.berth}</div>
                                            </div>
                                            <div className="device-item">
                                                <div className="device-label"></div>
                                                <div className="device-content"></div>
                                            </div>
                                        </div>
                                    </div>
                                </>
                            )
                        },
                        {
                            label: `设备运营信息`,
                            key: 2,
                            children: (
                                <>
                                    <div className="device-detail-wrapper">
                                        <div className="device-row">
                                            <div className="device-item">
                                                <div className="device-label">设备厂商：</div>
                                                <div className="device-content">{deviceDetail.brand_name}</div>
                                            </div>
                                            <div className="device-item">
                                                <div className="device-label">运营状态：</div>
                                                <div className="device-content">{deviceDetail.operate_status}</div>
                                            </div>
                                        </div>
                                        <div className="device-row">
                                            <div className="device-item">
                                                <div className="device-label">设备状态：</div>
                                                <div className="device-content">
                                                    <div className={(deviceDetail.device_status == '在线' || deviceDetail.device_status == '上线') ? 'text-online' : 'text-offline'}>{deviceDetail.device_status}</div>
                                                </div>
                                            </div>
                                            <div className="device-item">
                                                <div className="device-label">状态变更时间：</div>
                                                <div className="device-content">{deviceDetail.status_change_time}</div>
                                            </div>
                                        </div>
                                    </div>
                                </>
                            )
                        },
                    ]}
                />
            </div>
        </Modal>
      </div>
    </>
  )
}

export default Road;