// 数据解析
import { Store, utils } from 'amos-tool';
import { PubSub } from 'ray-eventpool';
import { transitionHelper } from 'amos-3d/lib/helpers';
import { eventTopics, pointTopicMapping, operateTypes } from './consts';
import { searchLinkAction } from 'SERVICES/3dService';
import conf from './conf';

const lsTool = Store.lsTool;
const { BaseObjHelper } = transitionHelper;

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

/**
 * 触发演练详情
 * @param {string} type
 * @param {any} data
 */
export const tirggerPlanTopic = (type, data) => {
  PubSub.publish(type, {
    operateType: type,
    target: 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 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 = title;
            let level;
            if ('riskSource' === type.replace(/(^\s*)|(\s*$)/g, '')) {
              titleContent = title;
              level = bizobj.riskLevel
            }
           
            if('risk' === type.replace(/(^\s*)|(\s*$)/g, '')){
              level = bizobj.nodeState
            }
            needUpdate = true;
            return {
              ...ma,
              showInfo,
              title: titleContent,
              level:level
            };
          }
          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, fireTruckRoute } = 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 if (type === 'fireCar') {
    const fireTruckMarkerCache = instance.markerList[type];
    let i = 0;
    for (let fireTruck of fireTruckMarkerCache.getValues()) {
      if (fireTruckRoute) {
        objRunning(fireTruck, JSON.parse(fireTruckRoute), i);
        i = i + 500;
      }
    }
  } 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) {
              if (mc.extData.type === 'fireCar') {
                mc.node.visible = visible;
                mc.object2DPipe.pipeNode.show();
              } else {
                mc.show();
              }
            } else {
              if (mc.extData.type === 'fireCar') {
                mc.node.visible = visible;
                mc.object2DPipe.pipeNode.hide();
              } 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){
        // 过滤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);
};

export const objRunning = (markerObj, routePath, delayTime) => {
  let obj = markerObj.node;
  if (!markerObj.objHelper) {
    markerObj.objHelper = new BaseObjHelper({ obj });
  } else {
    markerObj.objHelper.setObj(obj);
  }
  markerObj.objHelper.movePath({
    orientToPath: true,
    path: routePath,
    speed: 20,
    delayTime,
    onComplete() {
      console.log('firetruck Running completed'); // 路径结束回调
    }
  });
};


