/**
 * 驻勤点和保安员信息
 */
import React, { Component } from "react";
import { Icon, Button, Tooltip, Input, Modal } from 'antd';
import styles from "./index.less";
import { connect } from "dva";
import { getEventByLevel, getEventByLevelList, updateEventStatus } from '@services/api';
import backPng from "@assets/images/prevention/aPicture/back.png";
import eventYBPng from "@assets/images/prevention/aPicture/event-yb.png";
import eventJDPng from "@assets/images/prevention/aPicture/event-jd.png";
import eventZDPng from "@assets/images/prevention/aPicture/event-zd.png";
import eventTDPng from "@assets/images/prevention/aPicture/event-td.png";
import { isEmpty } from "@utils/utils";
import moment from "moment";
import eventCenter from "@common/events";
import classNames from 'classnames';
const { TextArea } = Input;

const _LEVEL = ['特别重大', '重大', '较大','一般'];
const _LEVEL_COLOR = ['#A80000', '#F48200', '#F6BD16', '#00B40C'];
const _DETAIL = [{
  name: '事件标题',
  type: 'item_eventname',
  default: '无',
  showType: 'text'
},{
  name: '上报者',
  type: 'item_username',
  default: '无',
  showType: 'text'
},{
  name: '上报时间',
  type: 'item_alarmtime',
  default: '无',
  showType: 'text'
},{
  name: '事发地点',
  type: 'item_eventplace',
  default: '无',
  showType: 'text'
},{
  name: '事件类型',
  type: 'item_eventtype',
  default: '无',
  showType: 'text'
},{
  name: '事件级别',
  type: 'item_eventlevelname',
  default: '无',
  showType: 'text'
},{
  name: '事件起因',
  type: 'item_eventcause',
  default: '',
  showType: 'input'
},{
  name: '已采取措施',
  type: 'item_localplan',
  default: '',
  showType: 'input'
},{
  name: '处理情况及发展趋势',
  type: 'item_situationandprogress',
  default: '',
  showType: 'input'
},{
  name: '进一步处置意见',
  type: 'item_nextdispose',
  default: '',
  showType: 'input'
},{
  name: '现场调度指导',
  type: 'item_remoteplan',
  default: '',
  showType: 'input'
}];

@connect((state) => ({
  //地图数据
  pictureMarkersList: state.command.pictureMarkersList,
  mapStyle: state.command.mapStyle,
  selectComponeyInfo: state.command.selectComponeyInfo,
  backStepInfo: state.command.backStepInfo
}))
export default class MapEventModule extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showStatus: 0, // 0: 事件模块 1：事件列表
      isDetail: false, // 是否显示详情页
      dataSource: {},
      searchValue: '',
      title: '事件模块',
      isBack: false,
      detailSource: {}
    };
    this.searchLevel = '';
    this.dataTemp = {};
  }

  _showEvent = ()=>{
    eventCenter.emit('clearMapTag', 'eventMarker')
    const { showStatus, searchValue } = this.state;
    console.log('showStatus', showStatus);
    const that = this;
    this.dataTemp = this.state.dataSource;
    if (showStatus == 0) {
      getEventByLevel().then(res=>{
        console.log('getEventByLevel', res);
        if (res.data) {
          // 打点信息
          let infos = [];
          _LEVEL.map((level)=>{
            res.data[level] && res.data[level].map((item, i)=>{
              let data = {};
              data.longitude = item.item_longitude;
              data.latitude = item.item_latitude;
              data.eventType = item.item_eventlevelname
              data.eventName = item.item_eventname
              data.eventNO = item.item_eventno
              data.eventPlace = item.item_eventplace
              data.alarmTime = moment(item.item_alarmtime.time).format("YYYY-MM-DD HH:MM:SS")
              data.userName = item.item_username
              if (!isEmpty(item.item_position) || !isEmpty(item.item_eventposition)) {
                try {
                  let position = JSON.parse(item.item_position)
                  data.longitude = position.longitude;
                  data.latitude = position.latitude;
                } catch (error) {
                }
                try {
                  let position = JSON.parse(item.item_eventposition)
                  data.longitude = position.longitude;
                  data.latitude = position.latitude;
                } catch (error) {
                }
                switch (item.item_eventlevelname) {
                  case '一般':
                    data.markerIcon = eventYBPng;
                    break;
                  case '较大':
                    data.markerIcon = eventJDPng;
                    break;
                  case '重大':
                    data.markerIcon = eventZDPng;
                    break;
                  case '特别重大':
                    data.markerIcon = eventTDPng;
                    break;
                }
                infos.push(data)
              }
            })
          })
          eventCenter.emit('addPictueMarks', {
            data: {
              data: infos,
            },
            type: 'eventMarker'
          });
          // 显示数据到地图上
          that.setState({
            dataSource: res.data,
            isBack: false,
            title: "事件模块"
          });
        }
      });
    } else {
      getEventByLevelList({
        name: searchValue,
        level: this.searchLevel
      }).then(res=>{
        console.log('getEventByLevelList', res);
        if (res.data.length > 0) {
          this._showMarker(res.data);
          // 显示数据到地图上
          if (this.state.isBack) {
            that.setState({
              dataSource: res.data
            });
          } else {
            that.setState({
              dataSource: res.data,
              isBack: false,
              title: "事件列表"
            });
          }
        }
      });
    }
  }
  componentDidMount() {
    this._showEvent();
  }
  // componentWillReceiveProps(nextProps) {
  //   const clickType = nextProps.selectComponeyInfo.clickType;
  //   const tabKey = clickType != 'personnel' ? "2" : "1";
  //   if(clickType && clickType != this.state.clickType) {
  //     if (tabKey !== this.state.tabKey) {
  //       this.setState({
  //         tabKey,
  //         personType: 'A',
  //         clickType
  //       });
  //     }
  //   }
  // }
  // 利用此事件来决定何时需要重新渲染组件。
  shouldComponentUpdate(nextProps, nextState) {
    if( nextState.showStatus !== this.state.showStatus ||
      nextState.title !== this.state.title ||
      nextState.isBack !== this.state.isBack ||
      nextState.dataSource !== this.state.dataSource ||
      nextState.detailSource !== this.state.detailSource ||
      nextState.searchValue !== this.state.searchValue ||
      nextState.isDetail !== this.state.isDetail)
    {
      return true;
    }
    return false;
  }
  _showMarker(list){
    eventCenter.emit('clearMapTag', 'eventMarker')
    // 打点信息
    let infos = [];
    list.map((item, i)=>{
      let data = {};
      data.longitude = item.item_longitude;
      data.latitude = item.item_latitude;
      data.eventType = item.item_eventlevelname
      data.eventName = item.item_eventname
      data.eventNO = item.item_eventno
      data.eventPlace = item.item_eventplace
      data.alarmTime = moment(item.item_alarmtime.time).format("YYYY-MM-DD HH:MM:SS")
      data.userName = item.item_username
      if (!isEmpty(item.item_position) || !isEmpty(item.item_eventposition)) {
        try {
          let position = JSON.parse(item.item_position)
          data.longitude = position.longitude;
          data.latitude = position.latitude;
        } catch (error) {
        }
        try {
          let position = JSON.parse(item.item_eventposition)
          data.longitude = position.longitude;
          data.latitude = position.latitude;
        } catch (error) {
        }
        switch (item.item_eventlevelname) {
          case '一般':
            data.markerIcon = eventYBPng;
            break;
          case '较大':
            data.markerIcon = eventJDPng;
            break;
          case '重大':
            data.markerIcon = eventZDPng;
            break;
          case '特别重大':
            data.markerIcon = eventTDPng;
            break;
        }
        infos.push(data)
      }
    })
    console.log('addPictueMarks-infos', infos);
    setTimeout(()=>{
      eventCenter.emit('addPictueMarks', {
        data: {
          data: infos,
        },
        type: 'eventMarker'
      });
    }, 200)
  }
  onChangeState=(state)=>{
    const that = this;
    that.state.showStatus = state;
    that.state.isBack = false;
    that._showEvent()
  }
  onBack=()=>{
    const { isDetail, isBack, dataSource } = this.state;
    console.log('onBack', isDetail);
    this.state.searchValue = '';
    this.searchLevel = '';
    if (isDetail) {
      this.setState({
        isDetail: false
      })
      this._showMarker(dataSource);
    } else if(isBack) {
      this.state.showStatus = 0
      this._showEvent();
    }
  }
  toList=(list, type)=>{
    if(list.length > 0){
      console.log('list', list);
      this.searchLevel = list[0]['item_eventlevel'];
    }
    this._showMarker(list);
    // 显示数据到地图上
    this.setState({
      dataSource: list,
      showStatus: 1,
      isBack: true,
      title: type+"事件区列表"
    });
  }
  renderModule=()=>{
    const { dataSource } = this.state;
    return (
      <div>
        {
          _LEVEL.map((level, idx)=>{
            const labelColor = _LEVEL_COLOR[idx];
            console.log('dataSource[level]', dataSource[level], dataSource);
            return <div className={styles.body_card}>
              <div className={styles.card_title}>
                <div className={styles.card_label} style={{backgroundColor: labelColor}}>{level}</div>
                <div className={styles.card_name}>{level + "事件区"}</div>
              </div>
              <div className={styles.card_content} onClick={this.toList.bind(this, dataSource[level], level)}>
                {dataSource[level] && dataSource[level].map((item, i)=>{
                  if (i < 4) {
                    return <div className={styles.card_item}><Tooltip title={item.item_eventname}>{item.item_eventname}</Tooltip></div>
                  } else if(i == 4) {
                    return <div className={styles.card_ellipsis}>...</div>
                  }
                })}
              </div>
              <div className={styles.card_sum}>{dataSource[level] && dataSource[level].length + "件"}</div>
            </div>
          })
        }
      </div>
    )
  }
  onClose=(item)=>{
    const that = this;
    Modal.confirm({
      title: '是否确认关闭事件，关闭事件后则默认事件状态为已处理',
      okText: '确认关闭',
      cancelText: '取消',
      onOk: ()=>{
        console.log('点击了 onClose');
        updateEventStatus({
          id: item.id,
          status: '已处理'
        })
        that.setState({
          showStatus: 1,
          isDetail: false
        })
        setTimeout(()=>{
          that._showEvent();
        }, 700)
      }
    });
  }
  renderDetail=()=>{
    const { detailSource } = this.state;
    console.log('item_alarmTime', detailSource);
    const nowTime = new Date().getTime();
    const duration = detailSource.item_alarmtime ? moment.duration(nowTime - detailSource.item_alarmtime.time) : 0;
    let alarmTime = "暂未上报";
    if (moment.isDuration(duration)) {
      alarmTime = duration.get('hours') + "小时" + duration.get('minutes') + "分钟";
    }
    return(
      <div className={styles.body_detail}>
        <div className={styles.detail_time}>{"距当前事发时长："+alarmTime}</div>
        {_DETAIL.map((item, index)=>{
          let content = !isEmpty(detailSource[item.type]) ? detailSource[item.type] : item.default
          const sty = index == 0 ? "15px" : "0";
          if (item.type == 'item_alarmtime') {
            content = !isEmpty(detailSource.item_alarmtime) ? moment(detailSource.item_alarmtime.time).format("YYYY-MM-DD HH:MM:SS") : ''
          }
          return <div className={styles.detail_item} style={{ paddingTop: sty }}>
            <div className={styles.item_title}>{item.name+":"}</div>
            <div className={styles.item_content}>
              {item.showType == 'input' && <TextArea autoSize={{minRows: 2, maxRows: 6}} placeholder="自动获取APP上传数据不可更改" disabled defaultValue={content} />}
              {item.showType == 'text' && <div className={item.text}>{content}</div>}
            </div>
          </div>
        })}
        <div className={styles.detail_bottom}>
          <Button style={{ marginRight: '20px' }} onClick={this.onClose.bind(this, detailSource)}>关闭事件</Button>
          {/* <Button style={{ marginLeft: '8px' }} type="primary">事件级别调整</Button> */}
        </div>
      </div>
    )
  }
  toDetail=(item)=>{
    this._showMarker([item]);
    this.setState({
      isDetail: true,
      detailSource: item,
      title: "事件详情"
    })
  }
  renderList=()=>{
    const { dataSource } = this.state;
    console.log('dataSource', dataSource);
    return (
      <div style={{ maxHeight: '630px', overflowY: 'auto', marginTop: '10px', paddingRight: '10px' }}>
        {
          dataSource && dataSource.map((item, i)=>{
            const level = item.item_eventlevelname;
            const idx = _LEVEL.indexOf(level);
            const labelColor = _LEVEL_COLOR[idx];
            const alarmTime = item.item_alarmtime ? moment(item.item_alarmtime.time).format("YYYY-MM-DD HH:MM:SS") : '暂未上报';
            const userName = !isEmpty(item.item_username) ? item.item_username : '' ;
            const phone = !isEmpty(item.item_phone) ? item.item_phone : '' ;

            return <div className={styles.body_card} onClick={this.toDetail.bind(this, item)}>
              <div className={styles.card_title}>
                <div className={styles.card_label} style={{backgroundColor: labelColor}}>{level}</div>
                <div className={styles.card_name}>{item.item_eventname}</div>
              </div>
              <div className={styles.card_content}>
                <div className={styles.card_item}>报警对象: <Tooltip title={userName +"   "+ phone}>{userName +"   "+ phone}</Tooltip></div>
                <div className={styles.card_item}>事件类型: <Tooltip title={item.item_eventtype}>{item.item_eventtype}</Tooltip></div>
                <div className={styles.card_item}>事发时间: <Tooltip title={alarmTime}>{alarmTime}</Tooltip></div>
                <div className={styles.card_item}>事发地点: <Tooltip title={item.item_eventplace}>{item.item_eventplace}</Tooltip></div>
              </div>
            </div>
          })
        }
      </div>
    )
  }
  onSearchInput=(e)=>{
    console.log('Change:', e.target.value);
    this.setState({
      searchValue: e.target.value
    })
  }
  render() {
    const {  mapStyle,selectComponeyInfo,pictureMarkersList } = this.props
    const { showStatus, title, isDetail, isBack, searchValue } = this.state
    console.log('MapEventModule-render');
    const cls = classNames('map-modal-optimizing-level1', styles.map_event_content);
    return (
      <div className={styles[mapStyle]}>
        <div className={cls}>
          <div className={styles.map_event_header}>
            <div className={styles.header_name}>{title}</div>
            {
              isDetail || isBack ? <div className={styles.header_back}>
                <img src={backPng} onClick={this.onBack.bind(this)} />
              </div> : <div className={styles.header_icon}>
                <img src={ showStatus == 0 ? require("@assets/images/prevention/aPicture/event-module-click.png") : require("@assets/images/prevention/aPicture/event-module.png")} onClick={this.onChangeState.bind(this, 0)} />
                <img src={ showStatus == 1 ? require("@assets/images/prevention/aPicture/event-list-click.png") : require("@assets/images/prevention/aPicture/event-list.png")}  onClick={this.onChangeState.bind(this, 1)} />
              </div>
            }
          </div>
          <div className={styles.map_event_body}>
            { !isDetail && showStatus == 1 && <Input placeholder="请输入事件名称" onChange={this.onSearchInput}
                onPressEnter={this._showEvent}
                style={{ marginRight: '16px', backgroundColor: '#F8F8FA', width: '270px' }}
                value={searchValue} /> }
            {
              isDetail ? this.renderDetail() : showStatus == 0 ? this.renderModule() : this.renderList()
            }
          </div>
        </div>
      </div >
    );
  }
}
