/**
 * 执法记录仪弹框
 * @param type: 
 */
import RreactDom from 'react-dom';
import { message, Modal, Button } from "antd";
import React, { Component } from "react";
const { confirm } = Modal;
import { getTerminalByUserId, trackTrsearch, getDomainInfo, attendanceGetTypeData } from '@services/api';
import InitTraietory, { removePathSimplifierIns } from '@mapModule/Traiectory/InitTraietory';
import { timestamp } from '../../../../utils/utils';
import MouseMovement from '../../../../components/MouseMovement';
import { APictureAddPictueMarks } from "../../GIS/APicture/func"
import eventCenter from "@common/events"; // 引入 EventEmitter
import { recordAdd } from '@common/recordHistory';
import { showAttendPointInfo, showCompanyPointInfo } from '@gis/biz';

export default function (data, type = '', marker) {
  console.log(data);
  data = {
    ...data,
    name: data.equipmentName,
    companyName: "顺国电子科技有限公司123",
    phone: data.equipmentId,
    mobilePhone: data.equipmentId,
    ATTENDANCESITENAME: ''
  }
  // console.log(data);
  const { mapStyle } = this.props
  const { name, photoUrl, mobilePhone, DEPTNAME, companyName, securityName, time, domainid, ATTENDANCESITEID, ATTENDANCESITENAME } = data;
  var content = [];
  const imgHeader = [];
  const that = this;
  if (photoUrl) {
    imgHeader.push("<img src=" + photoUrl + "/><span class='img-name'>" + name + "</span>");
  } else {
    imgHeader.push(
      "<span class='img-span'>" +
      name.substring(name.length - 2, name.length) +
      "</span><span class='img-name'>" + name + "</span>"
    );
  }

  switch (type) {
    //一张图
    default:
      content.push(
        "<div><div class='image'>" +
        imgHeader +
        "</div></div>"
      );
      break;
  }
  content.join("<br/>");
  var infoDiv = document.createElement("div");
  infoDiv.className = mapStyle;
  var info = document.createElement("div");
  info.className = "content-window-card-trajectory";
  infoDiv.appendChild(info);
  //可以通过下面的方式修改自定义窗体的宽高
  //  info.style.width = "400px";
  // 定义内容
  var middle = document.createElement("div");
  middle.className = "info-middle";
  middle.innerHTML = content;

  var componeyDiv = document.createElement("div");
  componeyDiv.className = "text";
  componeyDiv.innerHTML = "所属公司：";
  var componey = document.createElement("span");
  componey.className = "text";
  componey.innerHTML = companyName;
  // componey.onclick = () => {
  //   recordAdd({
  //     from: 'CreateTrajectoryInfoWindow',
  //     to: 'ComponeyInfo',
  //     fromData: data,
  //     toID: domainid
  //   });
  //   showCompanyPointInfo({
  //     doMainId: domainid,
  //     success: function (info) {
  //       that.props.dispatch({
  //         type: 'command/setSelectComponeyInfo',
  //         payload: info
  //       })
  //     }
  //   })
  // }
  componeyDiv.appendChild(componey);
  var attendanceDiv = document.createElement("div");
  attendanceDiv.className = "text";
  attendanceDiv.innerHTML = "所属驻勤点：";
  var attendance = document.createElement("span");
  attendance.className = "text";
  attendance.innerHTML = ATTENDANCESITENAME;
  // attendance.innerHTML = "驻勤点";
  attendanceDiv.appendChild(attendance);
  // attendance.onclick = () => {
  //   recordAdd({
  //     from: 'CreateTrajectoryInfoWindow',
  //     to: 'AttendInfo',
  //     fromData: data,
  //     toID: ATTENDANCESITEID
  //   });
  //   showAttendPointInfo({
  //     aid: ATTENDANCESITEID,
  //     companyName: companyName,
  //     doMainId: domainid,
  //     success: function (result) {
  //       that.props.dispatch({
  //         type: 'command/setSelectAttendInfo',
  //         payload: result
  //       })
  //     }
  //   });
  // }
  var phone = document.createElement("div");
  phone.className = "text";
  phone.innerHTML = "手机号：" + mobilePhone;
  middle.appendChild(componeyDiv);
  middle.appendChild(attendanceDiv);
  middle.appendChild(phone);
  info.appendChild(middle);
  //定义详情
  var detail = document.createElement("div");
  detail.className = "detail-div";
  info.appendChild(detail);
  //定义关闭按钮
  var detail = document.createElement("div");
  detail.className = "close-div";
  var a = document.createElement("a");
  a.innerHTML = "x";
  a.onclick = () => {
    // this.state.map.clearInfoWindow();
    //因为police的图层的打点跟列表的选中，没有做更多处理，直接传选中点的信息在这更改，避免需要在生命周期中监听修改的麻烦
    if (type == 'police') {
      this.clear('setPoliceSelectIndex')
      marker.setContent(
        '<div class="amap_lib_placeSearch_poi poibox-icon">' +
        marker.w.indexText +
        "</div>"
      );
    } else {
      this.clear('setPersonSelectIndex')
      eventCenter.emit('checkedMapTag', {
        type: 'securityResource',
        checked: false
      });
    }
  };
  detail.appendChild(a);
  info.appendChild(detail);
  // 定义定位信息
  var top = document.createElement("div");
  top.className = "info-button";
  var titleDiv = document.createElement("div");
  titleDiv.className = "title";
  titleDiv.innerHTML = '定位信息';
  top.appendChild(titleDiv)
  var locationDiv = document.createElement("div");
  locationDiv.className = "location-time";
  locationDiv.innerHTML = "该定位上传时间：" + (time != undefined ? time : '');
  top.appendChild(locationDiv);
  // 暂时不显示定位信息
  // info.appendChild(top);
  //定义4个指挥调度按钮
  var top = document.createElement("div");
  top.className = "info-button";
  var titleDiv = document.createElement("div");
  titleDiv.className = "title";
  titleDiv.innerHTML = '指挥调度'
  top.appendChild(titleDiv)
  var button2 = document.createElement("span");
  button2.className = "button";
  button2.innerHTML = "语音";
  button2.onclick = () => {
    this.clear('setPersonSelectIndex')
    this.voice(data);
  };
  var button3 = document.createElement("span");
  button3.className = "button";
  button3.innerHTML = "视频调度";
  var button4 = document.createElement("span");
  button4.className = "button";
  button4.innerHTML = "视频上拉";
  const _this = this;
  button3.onclick = () => {
    _this.clear('setPersonSelectIndex')
    _this.props.dispatch({
      type: 'command/fetchVideoGenre',
      payload: 0
    })
    // _this.video([data], "个人调度", [mobilePhone]);
    eventCenter.emit('clickTextScheduling', {
      item: [data],
      isNeedRecord: [mobilePhone],
      type: "video"
    });
  };
  button4.onclick = () => {
    _this.clear('setPersonSelectIndex')
    _this.props.dispatch({
      type: 'command/fetchVideoGenre',
      payload: 1
    })
    // _this.video([data], "个人调度", [mobilePhone]);
    eventCenter.emit('clickTextScheduling', {
      item: [data],
      isNeedRecord: [mobilePhone],
      type: "video"
    });
  }
  top.appendChild(button2);
  top.appendChild(button3);
  top.appendChild(button4);
  info.appendChild(top);
  //定义2个轨迹服务按钮
  var top = document.createElement("div");
  top.className = "info-button";
  var titleDiv = document.createElement("div");
  titleDiv.className = "title";
  titleDiv.innerHTML = '轨迹服务'
  top.appendChild(titleDiv)
  var button21 = document.createElement("span");
  button21.className = "button";
  button21.innerHTML = "轨迹查询";
  button21.onclick = () => {
    this.clear('setPoliceSelectIndex')
    if (type == 'police') {
      marker.setContent(
        '<div class="amap_lib_placeSearch_poi poibox-icon">' +
        marker.w.indexText +
        "</div>"
      );
    }
    _getTerminalByUserId.call(this, data, marker, type)
  };
  var button22 = document.createElement("span");
  button22.className = "button";
  button22.innerHTML = "轨迹上拉";
  button22.onclick = () => {
  };
  top.appendChild(button21);
  top.appendChild(button22);
  info.appendChild(top);
  // 定义底部内容
  var bottom = document.createElement("div");
  bottom.className = "info-bottom";
  bottom.style.position = "relative";
  bottom.style.top = "19px";
  bottom.style.margin = "0 auto";
  //  var sharp = document.createElement("img");
  //  sharp.src = "https://webapi.amap.com/images/sharp.png";
  var sharp = document.createElement("div");
  sharp.className = "sharp";
  bottom.appendChild(sharp);
  info.appendChild(bottom);
  return infoDiv;
}

//历史轨迹
// function trajectory(data, marker, terminalData, type) {
//   const _this = this
//   const { mapStyle } = this.props
//   const { name, photoUrl, mobilePhone, companyName, DEPTNAME } = data;
//   var content = [];
//   const imgHeader = [];
//   if (photoUrl) {
//     imgHeader.push("<img src=" + photoUrl + "/><span class='img-name'>" + name + "</span>");
//   } else {
//     imgHeader.push(
//       "<span class='img-span'>" +
//       name.substring(name.length - 2, name.length) +
//       "</span><span class='img-name'>" + name + "</span>"
//     );
//   }

//   switch (type) {
//     //警保联动
//     case 'police':
//       content.push(
//         "<div><div class='image'>" +
//         imgHeader +
//         "</div><div class='content-text'><div class='text'>所属公司：" +
//         companyName +
//         "</div><div class='text'>手机号：" +
//         mobilePhone +
//         "</div></div>"
//       );
//       break;
//     //一张图
//     default:
//       content.push(
//         "<div><div class='image'>" +
//         imgHeader +
//         "</div><div class='content-text'><div class='text'>所属部门：" +
//         DEPTNAME +
//         "</div><div class='text'>手机号：" +
//         mobilePhone +
//         "</div></div>"
//       );
//       break;
//   }
//   content.join("<br/>");
//   var infoDiv = document.createElement("div");
//   infoDiv.className = mapStyle;
//   var info = document.createElement("div");
//   info.className = "content-window-card-trajectory";
//   infoDiv.appendChild(info);
//   //可以通过下面的方式修改自定义窗体的宽高
//   //  info.style.width = "400px";
//   // 定义内容
//   var middle = document.createElement("div");
//   middle.className = "info-middle";
//   middle.innerHTML = content;
//   info.appendChild(middle);
//   //定义详情
//   var detail = document.createElement("div");
//   detail.className = "detail-div";
//   info.appendChild(detail);
//   //定义关闭按钮
//   var detail = document.createElement("div");
//   detail.className = "close-div";
//   var a = document.createElement("a");
//   a.innerHTML = "x";
//   a.onclick = () => {
//     this.clear('setPoliceSelectIndex')
//     if (type == 'police') {
//       marker.setContent(
//         '<div class="amap_lib_placeSearch_poi poibox-icon">' +
//         marker.w.indexText +
//         "</div>"
//       );
//     }
//   };
//   detail.appendChild(a);
//   info.appendChild(detail);
//   //时间选择器
//   var timeDiv = document.createElement("div");
//   timeDiv.className = 'time-div'
//   var timeSpan = document.createElement("span");
//   timeSpan.className = 'time-title'
//   timeSpan.innerHTML = '请先选择日期:'
//   timeDiv.appendChild(timeSpan)
//   //存放所有的轨迹list
//   var terminalListDiv = document.createElement("div");
//   terminalListDiv.id = 'terminal-list'

//   var timeButton = document.createElement("div");
//   timeButton.innerHTML = '确定'
//   timeButton.className = 'button'
//   timeButton.onclick = () => {
//     var date = document.getElementById("myDate").value;
//     if (date) {
//       trackTrsearch({
//         key: terminalData.key,
//         sid: terminalData.serviceId,
//         tid: terminalData.tid,
//         day: date
//       }).then(res => {
//         var terminal = document.getElementById('terminal-list')
//         var list = terminal.getElementsByClassName('list')
//         let length = list.length
//         if (list.length > 0) {
//           for (var i = 0; i < length; i++) {
//             terminal.removeChild(list[0]);
//           }
//         }
//         if (res.data && res.data.counts > 0) {
//           var terminalList = res.data.tracks
//           terminalList.map(item => {
//             var itemDiv = document.createElement("div")
//             itemDiv.className = 'list'
//             var itemName = document.createElement("div")
//             itemName.innerHTML = '轨迹时间:'
//             itemName.className = 'item-name'
//             var itemTime = document.createElement("span")
//             itemTime.innerHTML = timestamp(item.startPoint.locatetime) + '-' + timestamp(item.endPoint.locatetime)
//             itemTime.className = 'item-time'
//             var itembuttonList = document.createElement("div");
//             itembuttonList.className = 'item-button'
//             var itembutton1 = document.createElement("div");
//             itembutton1.className = "button";
//             itembutton1.innerHTML = "查看";
//             itembutton1.onclick = () => {
//               if (item.counts > 0) {
//                 InitTraietory.call(_this, item.points)
//               } else {
//                 message.warning("该人员暂无相关轨迹信息")
//               }
//             };
//             var itembutton2 = document.createElement("div");
//             itembutton2.className = "button";
//             itembutton2.innerHTML = "播放";
//             itembutton2.onclick = () => {

//             };
//             itembuttonList.appendChild(itembutton1)
//             itembuttonList.appendChild(itembutton2)
//             itemDiv.appendChild(itemName)
//             itemDiv.appendChild(itemTime)
//             itemDiv.appendChild(itembuttonList)
//             terminalListDiv.appendChild(itemDiv);
//           })
//         } else {
//           var noData = document.createElement("div")
//           noData.className = 'list'
//           noData.innerHTML = '暂无数据...'
//           terminalListDiv.appendChild(noData);
//         }
//       })
//     } else {
//       message.warning("请先选择日期")
//     }
//   }

//   var timeInput = document.createElement("input");
//   timeInput.id = 'myDate'
//   timeInput.type = 'date'
//   // timeInput.value = '2021-07-26'
//   timeInput.style.marginLeft = '10px'
//   timeDiv.appendChild(timeInput)
//   timeDiv.appendChild(timeButton)
//   info.appendChild(timeDiv)
//   //定义历史轨迹
//   var top = document.createElement("div");
//   top.className = "info-button";
//   var titleDiv = document.createElement("div");
//   titleDiv.className = "title";
//   titleDiv.innerHTML = '历史轨迹'

//   top.appendChild(titleDiv)
//   top.appendChild(terminalListDiv)
//   info.appendChild(top);
//   // 定义底部内容
//   var bottom = document.createElement("div");
//   bottom.className = "info-bottom";
//   bottom.style.position = "relative";
//   bottom.style.top = "19px";
//   bottom.style.margin = "0 auto";
//   var sharp = document.createElement("div");
//   sharp.className = "sharp";
//   bottom.appendChild(sharp);
//   info.appendChild(bottom);
//   return infoDiv;
// }

async function _getTerminalByUserId(data, marker, type) {
  // data.TUserID = 'track__5sfg3g1lSc0Snjkn1ZV__tNpV3Q9m0aCRzdrGxGs'
  if (data.TUserID) {
    var terminalData = await getTerminalByUserId({
      userid: data.TUserID
    }).then(res => {
      if (res.data) {
        return res.data
      }
    })
    if (terminalData) {
      const that = this
      // 删除组件
      const divs = document.getElementsByClassName('n_trajectory');
      if (divs) {
        Reflect.apply(Array.prototype.forEach, divs, [item => {
          RreactDom.unmountComponentAtNode(item);
          document.body.removeChild(item);
        }]);
      }
      this.props.dispatch({
        type: "command/setSwitchOpenStatus",
        payload: {
          type: 'all',
          value: true
        },
      });
      trajectoryList({ terminalData, personData: data, _thisGIS: that, type })
      // var infoWindow = new AMap.InfoWindow({
      //   isCustom: true, //使用自定义窗体
      //   content: trajectory.call(that, data, marker, terminalData, type),
      //   offset: new AMap.Pixel(16, -45),
      // });
      // infoWindow.open(that.state.map, marker.getPosition());
    } else {
      message.warning("该人员暂无相关轨迹信息")
    }
  } else {
    message.warning("没有相应的用户信息")
  }
}

//显示轨迹查看框
function trajectoryList(props) {
  const div = document.createElement('div');
  div.setAttribute('class', 'n_trajectory');
  document.body.appendChild(div);
  RreactDom.render(<TrajectoryModal  {...props} />, div);
}
class TrajectoryModal extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      //拖动参数
      isDown: false,
      offsetLeft: 0,
      offsetTop: 0,
      //轨迹列表
      terminalList: []
    };
  }
  render() {
    const { terminalData, _thisGIS, personData, type } = this.props
    const { name, photoUrl, mobilePhone, companyName, DEPTNAME } = personData;
    const { terminalList } = this.state
    return (
      <div>
        <MouseMovement
          isDown={this.state.isDown}
          offsetLeft={this.state.offsetLeft}
          offsetTop={this.state.offsetTop}
        >
          {({ x, y, cursor = 'move' }) => (
            <div className="video-text" ref="video-text" style={{
              cursor: 'move',
              position: 'absolute',
              top: y == 0 ? '70px' : y,
              left: x == 0 ? '16px' : x,
            }}
              onMouseDown={e => {
                this.setState({
                  isDown: true,
                  offsetLeft: document.getElementsByClassName('video-text')[0].offsetLeft,
                  offsetTop: document.getElementsByClassName('video-text')[0].offsetTop
                })
              }}
              onMouseUp={e => {
                this.setState({
                  isDown: false,
                })
              }}
            >
              <div className="content-window-card-trajectory">
                <div className="info-middle">
                  <div>
                    <div className="image">
                      {
                        photoUrl ? <>
                          <img src={photoUrl} /><span className="img-span">{name}</span>
                        </> :
                          <>
                            <span className="img-span">{name.substring(name.length - 2, name.length)}</span>
                            <span className="img-name">{name}</span>
                          </>
                      }
                    </div>
                    <div className="content-text">
                      {
                        type == 'police' ? <div className="text">所属公司：{companyName}</div> : <div className="text">所属部门：{DEPTNAME}</div>
                      }
                      <div className="text">手机号：{mobilePhone}</div>
                    </div>
                  </div>
                </div>
                <div className="close-div" onClick={() => {
                  // 删除组件
                  const divs = document.getElementsByClassName('n_trajectory');
                  Reflect.apply(Array.prototype.forEach, divs, [item => {
                    RreactDom.unmountComponentAtNode(item);
                    document.body.removeChild(item);
                  }]);
                  removePathSimplifierIns()
                  this.props._thisGIS.props.dispatch({
                    type: "command/setSwitchOpenStatus",
                    payload: {
                      type: 'all',
                      value: false
                    },
                  });
                }}>
                  <a>x</a>
                </div>
                <div className="time-div">
                  <span className="time-title">请先选择日期:</span>
                  <input id="myDate" type="date" style={{ marginLeft: '10px' }} />
                  <div className="button" onClick={() => {
                    var date = document.getElementById("myDate").value;
                    if (date) {
                      trackTrsearch({
                        key: terminalData.key,
                        sid: terminalData.serviceId,
                        tid: terminalData.tid,
                        day: date
                      }).then(res => {
                        if (res.data && res.data.counts > 0) {
                          this.setState({
                            terminalList: res.data.tracks
                          })
                        }
                      })
                    } else {
                      message.warning("请先选择日期")
                    }
                  }}>确定</div>
                </div>
                <div className="info-button">
                  <div className="title">历史轨迹</div>
                  <div id="terminal-list">
                    {
                      terminalList.length > 0 ? (
                        terminalList.map((item, index) => {
                          return (
                            <div className="list" key={index}>
                              <div className="item-name">轨迹时间:</div>
                              <span className="item-time">{timestamp(item.startPoint.locatetime) + '-' + timestamp(item.endPoint.locatetime)}</span>
                              <div className="item-button">
                                <div className="button" onClick={() => {
                                  if (item.counts > 0) {
                                    InitTraietory.call(_thisGIS, item.points)
                                  } else {
                                    message.warning("该人员暂无相关轨迹信息")
                                  }
                                }}>查看</div>
                                <div className="button">播放</div>
                              </div>
                            </div>
                          )
                        })
                      ) : <div className="list">暂无数据...</div>
                    }
                  </div>
                </div>
              </div>
            </div>
          )}
        </MouseMovement>
      </div>
    );
  }
}
