/**
 * 南宁武装押运管控
 */
 import React, { Component } from "react";
 import { Icon, DatePicker, Form, Button, message, Select, Input, Switch } from 'antd';
 import { getHaiKangApiUrl } from '../../../../services/api';
 import { formItemLayout1 } from '../../../../constants/formItemLayout';
 import NanNingTraiectory from '../../mapModule/Traiectory/NanNingTraiectory';
 import moment from 'moment';
 import { connect } from "dva";
 import styles from './index.less';
 import Video from './Video';
 import MouseMovement from "../../../../components/MouseMovement"
 const FormItem = Form.Item;
 @Form.create()
 @connect((state) => ({
   mapStyle: state.command.mapStyle
 }))
 export default class NanNing extends Component {
   constructor(props) {
     super(props);
     this.state = {
       rootData: [],//组装成json树格式
       clickVehicle: null,//当前点击中的某个车辆id值
       showVideo: false,
       videoUrl: "",
       licensePlate: "", //车牌号码
       searchCarData: [], //查询车辆
       onlineSwitch: true,  //车辆是否在线
       text: {
         isDown: false,
         offsetLeft: 0,
         offsetTop: 0,
       },
     };
   }
   componentDidMount() {
     const allHeight = document.documentElement.clientHeight - 140 - 16;
     let treeListHeight = allHeight - 140
     this.setState({ allHeight, treeListHeight });
     this._getAllRegionsValue();
     // this.initH5Player();
   }
   //获取所有的区域数据
   _getAllRegionsValue(pageNo = 1, allRegionsData = []) {
     getHaiKangApiUrl({
       apiPath: "/artemis/api/resource/v1/regions",
       "pageNo": pageNo,
       "pageSize": 500,
       "treeCode": "0"
     }).then(res => {
       console.log(res);
       let value = JSON.parse(res.data)
       console.log(value)
       if (value) {
         let data = value.data
         let { list } = data
         let regionsData = allRegionsData.concat(list)
         let { pageNo, pageSize, total } = data
         if (total > pageNo * pageSize) {
           this._getAllRegionsValue(pageNo + 1, regionsData)
         } else {
           this.sort(regionsData)
         }
       }
     })
   }
   //对区域数据进行树节点排序组装
   sort(list) {
     const idMapping = list.reduce((acc, el, i) => {
       acc[el.indexCode] = i;
       return acc;
     }, {});
     let root;
     list.forEach((el, index) => {
       // 判断根节点
       if (el.parentIndexCode == '-1') {
         el.place = [0]
         el.open = true
         root = el;
         return;
       }
       // 用映射表找到父元素
       const parentEl = list[idMapping[el.parentIndexCode]];
       const parentPlace = JSON.parse(JSON.stringify(parentEl.place))
       let place = null
       if (parentEl.children) {
         place = parentPlace.concat(parentEl.children.length)
       } else {
         place = parentPlace.concat(0)
       }
       // 把当前元素添加到父元素的`children`数组中
       parentEl.children = [...(parentEl.children || []), { ...el, open: false, place }];
     });
     this.setState({
       rootData: [root]
     })
   }
   //获取该区域下的所有车辆,然后塞进root树中
   _getVehiclePage(pageNo = 1, id, place, allVehicleData = []) {
     getHaiKangApiUrl({
       apiPath: "/artemis/api/rtsm/v1/resource/findVehiclePage",
       "exactCondition": { "orgIndexCodes": [id] },
       "pageNo": pageNo,
       "pageSize": 5000,
       "treeCode": "0"
     }).then(res => {
       console.log(res);
       let value = JSON.parse(res.data)
       if (value) {
         let data = value.data
         if (data) {
           let { list } = data
           allVehicleData = allVehicleData.concat(list)
           let { pageNo, pageSize, total } = data
           if (total > pageNo * pageSize) {
             return this._getVehiclePage(pageNo + 1, id, place, allVehicleData)
           }
         }
       }
       const { rootData } = this.state
       const root = JSON.parse(JSON.stringify(rootData))
       let data = null
       place.map((item, index) => {
         if (index == 0) {//暂时根节点没有车辆信息
           data = root[item]
           if (index + 1 == place.length) {
             data.vehiclelist = allVehicleData
           }
         } else {
           data = data.children[item]
           if (index + 1 == place.length) {
             data.vehiclelist = allVehicleData
           }
         }
       })
       this.setState({
         rootData: root
       })
     })
   }
   //改变open的打开关闭状态
   changeOpenStatus(place) {
     const { rootData } = this.state
     const root = JSON.parse(JSON.stringify(rootData))
     let data = null
     place.map((item, index) => {
       if (index == 0) {
         data = root[item]
         if (index + 1 == place.length) {
           data.open = !data.open
         }
       } else {
         data = data.children[item]
         if (index + 1 == place.length) {
           data.open = !data.open
         }
       }
     })
     this.setState({
       rootData: root
     })
   }
   //根据车辆编号与设备编号获取监控点信息列表   0为全部  1为查询车辆
   _getMonitoringPoints(veh, pageNo = 1, place, type = 0) {
     //关联设备对象，默认是第一个
     getHaiKangApiUrl({
       apiPath: "/artemis/api/rtsm/v1/vehicle/findCameraPage",
       exactCondition: { "deviceIndexCodes": [veh.deviceResourceDTOList[0].deviceIndexCode], "vehicleIndexCodes": [veh.vehicleIndexCode] },
       "pageNo": pageNo,
       "pageSize": 100,
       "treeCode": "0"
     }).then(res => {
       console.log(res)
       let value = JSON.parse(res.data)
       if (value) {
         let data = value.data
         if (type == 0) {
           const { rootData } = this.state
           const root = JSON.parse(JSON.stringify(rootData))
           root[place[0]].children[place[1]].vehiclelist[place[2]].monitoringPointsList = data.list
           root[place[0]].children[place[1]].vehiclelist[place[2]].open = !root[place[0]].children[place[1]].vehiclelist[place[2]].open
           this.setState({
             rootData: root
           })
         } else {
           const { searchCarData } = this.state
           searchCarData[place].monitoringPointsList = data.list;
           searchCarData[place].open = !searchCarData[place].open
           this.setState({
             searchCarData
           })
         }
       }
     })
   }
   //根据监控点预览取流URL
   _getVideoStream(indexCode) {
     console.log(indexCode)
     getHaiKangApiUrl({
       apiPath: "/artemis/api/video/v1/cameras/previewURLs",
       "cameraIndexCode": indexCode,
       "streamType": 0,
       "protocol": "wss",
       "transmode": 1,
       "expand": "transcode=0",
     }).then(res => {
       console.log(res);
       let value = JSON.parse(res.data)
       if (value) {
         let data = value.data
         console.log(data);
         let { url } = data
         this.setState({
           showVideo: true,
           videoUrl: url,
         })
       }
     })
   }
   //根据车牌号查询车辆
   _getLicensePlate(licensePlate, onlineSwitch) {
     console.log(licensePlate)
     getHaiKangApiUrl({
       apiPath: "/artemis/api/rtsm/v1/resource/findVehicleByLicensePlate",
       vehicleLicensePlate: licensePlate
     }).then(res => {
       console.log(res);
       let value = JSON.parse(res.data)
       if (value.code === "0") {
         value = value.data;
         if (value.status == 1 || (value.status == 0 && !onlineSwitch)) {
           value.clicked = false;
           value.monitoringPointsList = [];
           value.open = false
           this.setState({
             searchCarData: [value],
             clickVehicle: null
           })
         } else {
           message.info('该车辆未在线');
           this.setState({
             searchCarData: [],
             clickVehicle: null
           })
         }
       } else {
         message.info('未查找到该车辆');
         this.setState({
           searchCarData: [],
           clickVehicle: null
         })
       }
     })
   }
   closeHaikangVideo() {
     this.setState({
       showVideo: false,
       videoUrl: '',
     })
   }
   // 渲染全部车辆数据
   renderChild(value) {
     const { clickVehicle } = this.state
     return value.map((item) => {
       return (
         <>
           <div onClick={() => {
             this.changeOpenStatus(item.place)
             if (!item.vehiclelist && item.parentIndexCode != '-1') {
               this._getVehiclePage(1, item.indexCode, item.place, [])
             }
           }}>
             <span style={{ color: (item.parentIndexCode != '-1' && item.open) ? '#0e70ff' : '' }}>
               <span>{item.name}</span>
               <Icon type={item.open ? 'up' : 'down'} />
             </span>
             {
               item.open && <div className='vehicle' style={{ marginLeft: '10px' }}>
                 {
                   item.vehiclelist && (item.vehiclelist.length > 0 ? <div>
                     {
                       item.vehiclelist.map((veh, index) => {
                         return (
                           <div key={index} onClick={(e) => { e.stopPropagation() }}>
                             <div
                               style={{ color: (clickVehicle && clickVehicle.vehicleIndexCode == veh.vehicleIndexCode) ? '#0e70ff' : '' }}
                               onClick={(e) => {
                                 e.stopPropagation()
                                 this.setState({
                                   clickVehicle: veh
                                 })
                                 if (veh.deviceResourceDTOList.length > 0) {
                                   this._getMonitoringPoints(veh, 1, item.place.concat(index))
                                 }
                               }}
                             >{veh.plateNo}</div>
                             <div style={{ marginLeft: '10px' }}>
                               {
                                 veh.open && (veh.monitoringPointsList.length > 0 && <div>{
                                   veh.monitoringPointsList.map(point => {
                                     return (
                                       <div key={point.vehicleIndexCode} className={styles.point} onClick={(e) => {
                                         e.stopPropagation()
                                         this._getVideoStream(point.indexCode)
                                       }}>
                                         <span>{point.cameraName}</span>
                                         <span className={styles.broadcast}>播放</span>
                                       </div>
                                     )
                                   })}</div>)
                               }
                             </div>
                           </div>
                         )
                       })
                     }
                   </div> : <div onClick={e => e.stopPropagation()}>无车辆信息...</div>)
                 }
               </div>
             }
           </div>
           {
             item.open && item.children && item.children.length > 0 && <div className="child" style={{ marginLeft: '10px' }}>{this.renderChild(item.children)}</div>
           }
         </>
       )
     })
   }
   // 渲染查询车辆数据
   renderSearchCar(value) {
     const { clickVehicle } = this.state
     return value.map((veh, index) => {
       return (
         <div key={index} onClick={(e) => { e.stopPropagation() }}>
           <div
             style={{ color: (clickVehicle && clickVehicle.vehicleIndexCode == veh.vehicleIndexCode) ? '#0e70ff' : '' }}
             onClick={(e) => {
               e.stopPropagation()
               this.setState({
                 clickVehicle: veh
               })
               if (veh.deviceResourceDTOList.length > 0) {
                 this._getMonitoringPoints(veh, 1, index, 1)
               }
             }}
           >{veh.plateNo}</div>
           <div style={{ marginLeft: '10px' }}>
             {
               veh.open && (veh.monitoringPointsList.length > 0 && <div>{
                 veh.monitoringPointsList.map(point => {
                   return (
                     <div key={point.vehicleIndexCode} className={styles.point} onClick={(e) => {
                       e.stopPropagation()
                       this._getVideoStream(point.indexCode)
                     }}>
                       <span>{point.cameraName}</span>
                       <span className={styles.broadcast}>播放</span>
                     </div>
                   )
                 })}</div>)
             }
           </div>
         </div>
       )
     })
   }
   //根据车辆编号及时段获取历史定位信息
   _getPosition(pageNo = 1, allPositionData = []) {
     const { _thisGIS } = this.props
     const { clickVehicle } = this.state
     console.log('this.props',this.props)
     console.log(this.props.form)
     this.props.form.validateFields((err, values) => {
       var millisecond = (values.endTime.diff(values.startTime, 'millisecond')) / 1000 / 3600
       if (millisecond > 24) {
         return message.warning("搜索时间段间隔必须在24小时以内")
       }
       if (!err && clickVehicle) {
         const beginTime = moment(values.startTime).format("YYYY-MM-DDTHH:MM:DD.123+08:00");
         const endTime = moment(values.endTime).format("YYYY-MM-DDTHH:MM:DD.123+08:00");
         getHaiKangApiUrl({
           apiPath: "/artemis/api/rtsm/v1/gps/findHistoryGps",
           "beginTime": beginTime, 
           "endTime": endTime, 
           "vehicleIndexCode": clickVehicle.vehicleIndexCode, 
           "pageNo": pageNo, 
           "pageSize": 500,
         }).then(res => {
             // let value = JSON.parse(res.data.data[0].data) && JSON.parse(res.data.data[0].data)
             let value = JSON.parse(res.data)
             console.log(value);
             if (value) {
               let data = value.data
               let { list } = data
               allPositionData = allPositionData.concat(list)
               // NanNingTraiectory.call(_thisGIS, allPositionData)
               let { pageNo, pageSize, total } = data
               if (total > pageNo * pageSize) {
                 this._getPosition(pageNo + 1, allPositionData)
               } else {
                 if (allPositionData.length > 0) {
                   allPositionData = allPositionData.filter(item => {
                     return item.latitude && item.longitude && item.time
                   })
                   let a = allPositionData.every(item => {
                     return item.latitude && item.longitude && item.time
                   })
                   console.log(a)
                  //  debugger
                   NanNingTraiectory.call(_thisGIS, allPositionData)
                 } else {
                   message.warning("暂无轨迹信息")
                 }
               }
             }
           })
   }
 })
   }
 // 根据车牌号查询车辆
 searchCar = () => {
   const { licensePlate, onlineSwitch } = this.state;
   if (!licensePlate) {
     message.info('请输入要查询的车辆');
     return;
   }
   this._getLicensePlate(licensePlate, onlineSwitch)
 }
 render() {
   const { rootData, clickVehicle, allHeight, treeListHeight, showVideo, videoUrl, licensePlate, onlineSwitch, searchCarData } = this.state;
   const { getFieldDecorator } = this.props.form;
   const { mapStyle } = this.props
   console.log(searchCarData)
   return (
     <div>
       <div className={'drawer_container_tab ' + styles[mapStyle]} style={{ width: '250px', padding: '10px 10px 0 ', height: allHeight, overflow: 'auto', opacity: '0.8' }}>
         <div className={styles.searchCar}>
           <div className={styles.title}>车辆搜索</div>
           <Select defaultValue="licensePlate" style={{ width: 104, marginRight: 10 }}>
             <Select.Option value="licensePlate">车牌号码</Select.Option>
           </Select>
           <Input style={{ width: 114 }} placeholder="请输入车牌号" value={licensePlate} onChange={(e) => { this.setState({ licensePlate: e.target.value }) }} />
           <div className={styles.onlineSwitch}>
             <div className={styles.title}>只显示在线车辆</div>
             <Switch checkedChildren="开" unCheckedChildren="关" checked={onlineSwitch} onClick={() => { this.setState({ onlineSwitch: !onlineSwitch }) }} />
           </div>
           <Button type="primary" onClick={this.searchCar}>车辆查询</Button>
         </div>
         <div className={styles.treeList} style={{ maxHeight: treeListHeight, overflow: 'auto', marginBottom: 16 }}>
           {
             searchCarData.length > 0 ? this.renderSearchCar(searchCarData) : ''
           }
         </div>
         <div className={styles.treeList} style={{ maxHeight: treeListHeight, overflow: 'auto' }}>
           {
             rootData.length > 0 ? this.renderChild(rootData) : '暂无数据...'
           }
         </div>
         <div className={styles.timeContent}>
           <Form style={{ marginTop: 24 }}>
             <FormItem {...formItemLayout1} label="" style={{ marginBottom: 'unset' }}>
               {getFieldDecorator('startTime', {
                 rules: [
                   {
                     required: true,
                     message: '请输入开始时间'
                   }
                 ]
               })(
                 <DatePicker showTime placeholder="开始时间" />
               )}
             </FormItem>
             <FormItem {...formItemLayout1} label="" style={{ marginBottom: 'unset' }}>
               {getFieldDecorator('endTime', {
                 rules: [
                   {
                     required: true,
                     message: '请输入结束时间'
                   }
                 ]
               })(
                 <DatePicker showTime placeholder="结束时间" />
               )}
             </FormItem>
             <Button type="primary" disabled={!clickVehicle} onClick={() => this._getPosition()}>查询</Button>
           </Form>
         </div>
       </div>
       {
         // showVideo ?
         showVideo ?
           <MouseMovement
             isDown={this.state.text.isDown}
             offsetLeft={this.state.text.offsetLeft}
             offsetTop={this.state.text.offsetTop}
           >
             {({ x, y, cursor = 'move' }) => (
 
               // <div className="video-text" ref="video-text" 
               <div className={'drawer_container_tab video-haikang'} ref="video-haikang"
                 style={{
                   width: '340px',
                   height: '340px',
                   padding: '20px',
                   cursor: 'move',
                   top: y == 0 ? '1' : y,
                   left: x == 0 ? '300px' : x,
                   backgroundColor: '#fff'
                 }}
                 onMouseDown={e => {
                   this.setState({
                     text: {
                       isDown: true,
                       offsetLeft: document.getElementsByClassName('video-haikang')[0].offsetLeft,
                       offsetTop: document.getElementsByClassName('video-haikang')[0].offsetTop
                     }
                   })
                 }}
                 onMouseUp={e => {
                   this.setState({
                     text: {
                       ...this.state.text,
                       isDown: false,
                     }
                   })
                 }}
               >
                 <Video videoUrl={videoUrl} ref="video"
                   closeHaikangVideo={this.closeHaikangVideo.bind(this)}
                 />
               </div>
             )}
           </MouseMovement> : ""
       }
 
 
     </div>
   );
 }
 }
 
