import { useChartEditStore } from '@/store/modules/chartEditStore/chartEditStore';
import { mapFun } from '@/hooks/ceshiFun.hook';
import { router } from '@/router';
import { previewUrl } from '@/utils';
import { EventBus } from '@/utils/eventBus';
import axiosInstance from '@/api/axios';
import { translateStr } from '@/api/http';
import {
  RequestParamsObjType,
} from '@/enums/httpEnum';

const chartEditStore = useChartEditStore();
const ceshiFunction = mapFun();
//递归获取某个id在数组里的位置或者父id
export const queryFun = (array, value, peg?: any) => {
  var res = [];
  function _find(array, value, peg) {
    array.forEach((item, index) => {
      if (item.id === value) {
        if (peg) {
          res.push(peg);
        }
        res.push(index);
        return;
      } else if (item.groupList instanceof Array) {
        _find(item.groupList, value, index);
      }
    });
  }
  _find(array, value, peg);
  return res;
};

export const eventCommonHandler = (
  componentList: any,
  elementList: any,
  type: string,
  params: any = null,
) => {
  let obj: any = {};
  let index = 0;
  for (let i = 0; i < componentList.length; i++) {
    for (let j = 0; j < elementList.length; j++) {
      if (elementList[j].movement == 'newaddress') {
        // 打开新页面
        if (elementList[j].openNewPage) {
          if (elementList[j].skipType == 'routeLink') {
            const routeUrl = router.resolve({
              path: elementList[j].url,
            });
            window.open(routeUrl.href, '_blank');
            return;
          } else if (elementList[j].skipType == 'publishLink') {
            const routeUrl = router.resolve({
              path: previewUrl(elementList[j].url),
            });
            window.open(routeUrl.href, '_blank');
            return;
          } else {
            window.open(elementList[j].url, '_blank');
            return;
          }
        } else {
          if (elementList[j].skipType == 'routeLink') {
            router.replace(elementList[j].url);
            return;
          } else if (elementList[j].skipType == 'publishLink') {
            const routeUrl = router.resolve({
              path: previewUrl(elementList[j].url),
            });
            window.open(routeUrl.href, '_self');
            return;
          } else {
            window.open(elementList[j].url, '_self');
            return;
          }
        }
      } else if (elementList[j].movement == 'reveal') {
        // 显示
        for (let k = 0; k < elementList[j].elementId.length; k++) {
          //获取位置
          const arr = queryFun(componentList, elementList[j].elementId[k]);
          // console.log(arr);
          if (arr.length > 1) {
            obj = componentList[arr[0]].groupList[arr[1]];
            obj.status.hide = false;
            // console.log(obj);
            // chartEditStore.updateComponentList(arr[0], obj, arr[1]);
          } else if (arr.length == 1) {
            obj = componentList[arr[0]];
            obj.status.hide = false;
            // console.log(obj);

            // 海康视频组件单独处理
            if(obj.isGroup && obj.groupList.some((li) => li.key == 'ZhiGan_ModalVideo')) {
              obj.groupList.forEach((g) => {
                  if(g.key == 'ZhiGan_ModalVideo'){
                    g.status.hide = false;
                  }
              });
            }
            // chartEditStore.updateComponentList(arr[0], obj);
          }
          // if (componentList[i].id == elementList[j].elementId[k]) {
          //   obj = componentList[i];
          //   index = i;
          //   obj.status.hide = false;
          //   chartEditStore.updateComponentList(index, obj);
          // }
        }
      } else if (elementList[j].movement == 'hidden') {
        // 隐藏
        for (let k = 0; k < elementList[j].elementId.length; k++) {
          //获取位置
          const arr = queryFun(componentList, elementList[j].elementId[k]);    
          if (arr.length > 1) {
            obj = componentList[arr[0]].groupList[arr[1]];
            obj.status.hide = true;
            // chartEditStore.updateComponentList(arr[0], obj, arr[1]);
          } else if (arr.length == 1) {
            obj = componentList[arr[0]];
            obj.status.hide = true;

            // 海康视频组件单独处理
            if(obj.isGroup && obj.groupList.some((li) => li.key == 'ZhiGan_ModalVideo')) {
              obj.groupList.forEach((g) => {
                  if(g.key == 'ZhiGan_ModalVideo'){
                    g.status.hide = true;
                  }
              });
            }
            // chartEditStore.updateComponentList(arr[0], obj);
          }
          // if (componentList[i].id == elementList[j].elementId[k]) {
          //   obj = componentList[i];
          //   index = i;
          //   obj.status.hide = true;
          //   chartEditStore.updateComponentList(index, obj);
          // }
        }
      } else if (elementList[j].movement == 'map') {
        // 地图事件联动
        for (let k = 0; k < elementList[j].elementId.length; k++) {
          if (componentList[i].id == elementList[j].elementId[k]) {
            if (elementList[j].params) {
              ceshiFunction[elementList[j].funName](elementList[j].params);
            } else {
              ceshiFunction[elementList[j].funName]();
            }
          }
        }
      } else if (elementList[j].movement == 'communication') {
    
        // 组件通信
        for (let k = 0; k < elementList[j].elementId.length; k++) {
          if (componentList[i].id == elementList[j].elementId[k]) {
            
            EventBus.emit(elementList[j].elementId[k] + type, params);
            
            // 分组内所有组件默认添加通信
            componentList[i]?.groupList?.forEach((groupItem,idx)=>{
              EventBus.emit(groupItem.id +"dataupdate", params);
            })
          }

        }

        
      } else if (elementList[j].movement == 'graphic') {

        for (let k = 0; k < elementList[j].elementId.length; k++) {
          if (componentList[i].id == elementList[j].elementId[k]) {
            EventBus.emit(elementList[j].elementId[k] + type, params);
          }
        }
      } else if (elementList[j].movement == 'style') {
        //获取位置
        const arr = queryFun(componentList, elementList[j].elementId);
        if (arr.length > 1) {
          obj = componentList[arr[0]].groupList[arr[1]];
          obj.option = elementList[j].option;
          // chartEditStore.updateComponentList(arr[0], obj, arr[1]);
        } else if (arr.length == 1) {
          obj = componentList[arr[0]];
          obj.option = elementList[j].option;
          // chartEditStore.updateComponentList(arr[0], obj);
        }
      } else if (elementList[j].movement == 'callBackRequest') { 
        const {    
          requestUrl,
          requestApi,
          requestContentType,
          requestDataType,
          requestHttpType,
          requestParams
        } = elementList[j].callBackRequest;

        // 处理头部
        let headers: RequestParamsObjType = Object.fromEntries(requestParams.Header.map(item => [item.key.toLowerCase(), item.value]));
        if(!headers['x-token']){
          headers['x-token'] = localStorage.getItem('X-Token');
        }
        // 清除掉空项
        for (const key in headers) {
          if (key === "") {
            delete headers[key];
          }
        }

        // params 参数
        let params: RequestParamsObjType = Object.fromEntries(requestParams.Params.map(item => [item.key, item.value]));

        try {
          const url = new Function(
            'return `' +
              `${requestApi.includes('https://') || requestApi.includes('http://') ? requestApi : requestUrl + requestApi}`.trim() +
              '`',
          )();
          return axiosInstance({
            url,
            method: requestHttpType,
            data: {},
            params: translateStr(params),
            headers: translateStr(headers),
          });
        } catch (error) {
          console.log(error);
          window['$message'].error('URL地址格式有误！');
        }
      }
    }
  }
};
// 交互事件
export const eventHandlerHook = (
  componentList: any,
  interactConfigEvents: any,
  type: string,
  params: any = null,
) => {
  const elementList: any = [];
  for (let i = 0; i < interactConfigEvents.length; i++) {
    if (interactConfigEvents[i].type == type) {
      if (!interactConfigEvents[i].movementList) {
        return false;
      }
      for (let j = 0; j < interactConfigEvents[i].movementList.length; j++) {
        elementList.push(interactConfigEvents[i].movementList[j]);
      }
    }
  }

  if (componentList.length == 0 || elementList.length == 0) {
    return false;
  }
  eventCommonHandler(componentList, elementList, type, params);
};
// websocket事件
export const websocketEvent = (interactConfigEvents: any, params: any = null) => {
  console.log('websocketEvent', interactConfigEvents, params);
  interactConfigEvents.forEach((element) => {
    if (element.messageType == params.type) {
      element.elementId.forEach((item) => {
        EventBus.emit(item + 'websocket', params);
      });
    }
  });
};
