// 数据解析

import { Store, utils } from 'amos-tool';
import { PubSub } from 'ray-eventpool';
import { eventTopics, pointTopicMapping, operateTypes } from './consts';
import { searchLinkAction } from './../../services/3dService';
import conf from './conf';

const lsTool = Store.lsTool;

/**
 * 触发双屏通信
 * @param {string} type
 * @param {any} data
 */
export const tirggerTransTopic = (type, data) => {
  lsTool.write(type, JSON.stringify(data));
};

/**
 * 触发线路数据变化
 * @param {Array} links
 */
export const tirggerLinkDataChange = (links) => {
  PubSub.publish(eventTopics.linkdata_change, links);
};

/**
 * 触发 marker 点数据变化
 * @param {Object} data {markerType: '', markers: []}
 */
export const tirggerPointDataChange = (data) => {
  PubSub.publish(eventTopics.manual_operate, {
    operateType: operateTypes.POINT_CHANGE,
    target: data
  });
};

/**
 * 触发 批量 marker 点数据变化
 * @param {Object} data {markerType<String>: markers<Array>}
 */
export const tirggerBatchPointDataChange = (data) => {
  PubSub.publish(eventTopics.manual_operate, {
    operateType: operateTypes.BATCH_POINT_CHANGE,
    target: data
  });
};

export const isPoint = (type) => {

};

export const parseSearchMenuMarkers = (instance, content) => {
  if (content) {
    const { markers } = instance.state;
    content.map( (item) => {
      const { type } = item;
      const markersArr = markers[type.replace(/(^\s*)|(\s*$)/g, '')] || [];
      if (markersArr.length > 0){
        let needUpdate = false;
        const newArr = markersArr.map(ma => {
          if (ma.id === item.id){
            needUpdate = true;
            let twinkle = true;
            return {
              ...ma,
              twinkle
            };
          }
          return ma;
        });
        if (needUpdate){
          markers[type.replace(/(^\s*)|(\s*$)/g, '')] = newArr;
          instance.setState({
            markers
          });
        } else {
          markersArr.push(item);
          markers[type.replace(/(^\s*)|(\s*$)/g, '')] = markersArr;
          instance.setState({
            markers
          });
        }
      } else {
        markersArr.push(item);
        markers[type.replace(/(^\s*)|(\s*$)/g, '')] = markersArr;
      }
    });
  }
};

export const changeBubbleTitle = (instance, content) => {
  let { title } = content.data;
  instance.setState({ executeStatus: title });
};

export const parseBubbleMarkers = (instance, content) => {
  const { type, bizobj, showInfo, title } = content.data;
  // test
  if (type === 'person'){
    const personMarkerCache = instance.markerList[type];
    const target = personMarkerCache.get(type);
    // if (target){
    //   data.pathArr && target.moveAlong(data.pathArr, conf.moveDuration);
    // }
  } else {
    const topic = pointTopicMapping[type.replace(/(^\s*)|(\s*$)/g, '')];

    if (topic) {
      const { markers } = instance.state;
      const markersArr = markers[type.replace(/(^\s*)|(\s*$)/g, '')] || [];
      if (markersArr.length > 0){
        let needUpdate = false;
        const newArr = markersArr.map(ma => {
          if (bizobj && ma.id === bizobj.id){
            let titleContent = '';
            if ('riskSource' === type.replace(/(^\s*)|(\s*$)/g, '')) {
              titleContent = title;
            }
            needUpdate = true;
            // let { level } = bizobj;
            return {
              ...ma,
              showInfo,
              title: titleContent
            };
          }
          return ma;
        });
        if (needUpdate){
          markers[type.replace(/(^\s*)|(\s*$)/g, '')] = newArr;
          instance.setState({
            markers
          });
        }
      }
    } else {
      //
    }
  }
};

/**
 * 解析实时 marker 信息
 * @param {Context} instance
 * @param {string} topic
 * @param {any} data
 */
export const parseMarkers = (instance, topic, data) => {
  const { type, id, key } = data;
  // test
  if (type === 'person'){
    const personMarkerCache = instance.markerList[type];
    const target = personMarkerCache.get(key);
    if (target){
      data.pathArr && target.moveAlong(data.pathArr, conf.moveDuration);
    }
  } else {
    const pointTopic = pointTopicMapping[type];
    if (pointTopic){
      instance.updateMarkers(data);
    } else {
      //
    }
  }
};

export const executeView3dCMD = (instance, topic, data) => {
  const { key, value } = data;
  switch (topic) {
    // 多选操作
    // case eventTopics.innate_layer:
    //   instance.objsCache[key].visible = value;
    //   break;
    case eventTopics.innate_layer:
      if (key === 'all'){
        instance.objsCache.showAll();
      } else {
        instance.objsCache.onlyShow(key);
      }
      break;
    case eventTopics.innate_operater:
      instance.executeOperate(data);
      break;

    default:
      break;
  }
};

export const parseLevelFilter = (instance, topic, data) => {
  const { pointLevel, markerType, visible } = data;
  switch (topic) {
    // risk 级别过滤
    case eventTopics.level_filter_risk:
      switch (markerType) {
        case 'fireResource':
          (instance.markerList[pointLevel] || []).forEach(mc => {
            if (visible) {
              mc.show();
            } else {
              mc.hide();
            }
          });
          break;
        default:
          (instance.markerList[markerType] || []).forEach(mc => {
            const extData = mc.getExtData();
            if (extData.levelStr === pointLevel){
              if (visible) {
                mc.show();
              } else {
                mc.hide();
              }
            }
        });
          break;
      }

      break;
    default:
      break;
  }
};

/**
 * 解析手动操作
 */
export const parseManual = (instance, topic, data) => {
  const { operateType, target } = data;
  switch (operateType) {
    // 线路操作
    case operateTypes.LINK:
      if (target && target.key){
        // instance.linesCache.forEach((pl, key) => {
        //   if (key === target.key){
        //     pl.toggleSelect(true);
        //   } else {
        //     pl.toggleSelect(false);
        //   }
        // });
        // 过滤point
        searchLinkAction(target.key).then(d => {
          // 更新 marker
          instance.changeMarkersData(d.points);
          // 更新 link
          tirggerLinkDataChange(d.link);
        });
      }
      break;
    // marker 点变化
    case operateTypes.POINT_CHANGE:
      if (target && target.markerType){
        instance.changeMarkersData({
          [target.markerType]: target.markers
        });
      }
      break;
    // 批量 marker 点变化
    case operateTypes.BATCH_POINT_CHANGE:
      instance.changeMarkersData(target);
      break;

    case operateTypes.POINT_SEARCH:
      parseSearchMenuMarkers(instance, target);
      break;
    default:
      break;
  }
};

export const updateViewData = (args = {}) => {
  const { links, points } = args;
  // 更新 marker
  if (!utils.isEmpty(points)){
    tirggerBatchPointDataChange(points);
  }
  // 更新 link
  tirggerLinkDataChange(links);
};

export const update3DViewData = (args = {}) => {
  PubSub.publish(eventTopics.manual_operate, args);
};


