forked from drone/command-center-dashboard

shuishen
2025-04-02 e14358f85a7d32a753225f253ff223d17cf36c25
style: 风格处理
112 files modified
6293 ■■■■ changed files
.prettierrc.json 21 ●●●● patch | view | raw | blame | history
package.json 3 ●●●● patch | view | raw | blame | history
src/api/base/region.js 22 ●●●● patch | view | raw | blame | history
src/api/common.js 6 ●●●● patch | view | raw | blame | history
src/api/desk/notice.js 22 ●●●● patch | view | raw | blame | history
src/api/flow/flow.js 60 ●●●● patch | view | raw | blame | history
src/api/home/aggregation.js 20 ●●●●● patch | view | raw | blame | history
src/api/home/index.js 95 ●●●● patch | view | raw | blame | history
src/api/home/machineNest.js 33 ●●●● patch | view | raw | blame | history
src/api/job/jobinfo.js 34 ●●●● patch | view | raw | blame | history
src/api/job/jobserver.js 26 ●●●● patch | view | raw | blame | history
src/api/logs.js 26 ●●●● patch | view | raw | blame | history
src/api/report/report.js 10 ●●●● patch | view | raw | blame | history
src/api/resource/attach.js 22 ●●●● patch | view | raw | blame | history
src/api/resource/oss.js 26 ●●●● patch | view | raw | blame | history
src/api/resource/sms.js 30 ●●●● patch | view | raw | blame | history
src/api/system/client.js 22 ●●●● patch | view | raw | blame | history
src/api/system/dept.js 34 ●●●● patch | view | raw | blame | history
src/api/system/dict.js 38 ●●●● patch | view | raw | blame | history
src/api/system/dictbiz.js 38 ●●●● patch | view | raw | blame | history
src/api/system/menu.js 42 ●●●● patch | view | raw | blame | history
src/api/system/param.js 22 ●●●● patch | view | raw | blame | history
src/api/system/post.js 26 ●●●● patch | view | raw | blame | history
src/api/system/role.js 42 ●●●● patch | view | raw | blame | history
src/api/system/scope.js 42 ●●●● patch | view | raw | blame | history
src/api/system/tenant.js 50 ●●●● patch | view | raw | blame | history
src/api/system/tenantdatasource.js 22 ●●●● patch | view | raw | blame | history
src/api/system/tenantpackage.js 22 ●●●● patch | view | raw | blame | history
src/api/system/topmenu.js 34 ●●●● patch | view | raw | blame | history
src/api/system/user.js 62 ●●●● patch | view | raw | blame | history
src/api/tool/code.js 34 ●●●● patch | view | raw | blame | history
src/api/tool/codesetting.js 38 ●●●● patch | view | raw | blame | history
src/api/tool/datasource.js 22 ●●●● patch | view | raw | blame | history
src/api/tool/model.js 46 ●●●● patch | view | raw | blame | history
src/api/user.js 34 ●●●● patch | view | raw | blame | history
src/api/work/process.js 14 ●●●● patch | view | raw | blame | history
src/api/work/work.js 30 ●●●● patch | view | raw | blame | history
src/axios.js 178 ●●●● patch | view | raw | blame | history
src/components/basic-video/plugin.js 36 ●●●● patch | view | raw | blame | history
src/components/index.js 5 ●●●●● patch | view | raw | blame | history
src/config/env.js 4 ●●●● patch | view | raw | blame | history
src/config/iconList.js 2 ●●● patch | view | raw | blame | history
src/config/website.js 2 ●●● patch | view | raw | blame | history
src/const/tool/model.js 14 ●●●● patch | view | raw | blame | history
src/debug.js 26 ●●●● patch | view | raw | blame | history
src/directive/drag.js 13 ●●●● patch | view | raw | blame | history
src/directive/selectLoad.js 2 ●●● patch | view | raw | blame | history
src/error.js 26 ●●●● patch | view | raw | blame | history
src/lang/en.js 2 ●●● patch | view | raw | blame | history
src/lang/index.js 22 ●●●● patch | view | raw | blame | history
src/lang/zh.js 2 ●●● patch | view | raw | blame | history
src/main.js patch | view | raw | blame | history
src/mixins/crud.js 182 ●●●● patch | view | raw | blame | history
src/mixins/index.js 30 ●●●● patch | view | raw | blame | history
src/mockProdServer.js 12 ●●●● patch | view | raw | blame | history
src/option/job/jobinfo.js 16 ●●●● patch | view | raw | blame | history
src/option/job/jobserver.js 2 ●●● patch | view | raw | blame | history
src/option/system/dict.js 4 ●●●● patch | view | raw | blame | history
src/option/system/dictbiz.js 4 ●●●● patch | view | raw | blame | history
src/option/tool/code.js 6 ●●●● patch | view | raw | blame | history
src/option/tool/codesetting.js 2 ●●● patch | view | raw | blame | history
src/option/tool/formsetting.js 2 ●●● patch | view | raw | blame | history
src/option/user/info.js 2 ●●● patch | view | raw | blame | history
src/permission.js 56 ●●●● patch | view | raw | blame | history
src/router/avue-router.js 144 ●●●● patch | view | raw | blame | history
src/router/index.js 26 ●●●● patch | view | raw | blame | history
src/router/page/index.js 13 ●●●●● patch | view | raw | blame | history
src/router/views/index.js 16 ●●●●● patch | view | raw | blame | history
src/store/getters.js 8 ●●●● patch | view | raw | blame | history
src/store/index.js 20 ●●●● patch | view | raw | blame | history
src/store/modules/common.js 46 ●●●● patch | view | raw | blame | history
src/store/modules/dict.js 24 ●●●● patch | view | raw | blame | history
src/store/modules/home.js 15 ●●●● patch | view | raw | blame | history
src/store/modules/logs.js 28 ●●●● patch | view | raw | blame | history
src/store/modules/tags.js 38 ●●●● patch | view | raw | blame | history
src/store/modules/user.js 350 ●●●● patch | view | raw | blame | history
src/utils/auth.js 26 ●●●● patch | view | raw | blame | history
src/utils/cesium-tsa.js 666 ●●●● patch | view | raw | blame | history
src/utils/cesium/AmapMercatorTilingScheme/CoordTransform.js 144 ●●●●● patch | view | raw | blame | history
src/utils/cesium/AmapMercatorTilingScheme/index.js 38 ●●●●● patch | view | raw | blame | history
src/utils/cesium/ImageTrailMaterial.js 66 ●●●● patch | view | raw | blame | history
src/utils/cesium/common.js 215 ●●●●● patch | view | raw | blame | history
src/utils/cesium/compressImage.js 48 ●●●● patch | view | raw | blame | history
src/utils/cesium/compressImage2.js 40 ●●●● patch | view | raw | blame | history
src/utils/cesium/frustum/CreateFrustum.js 186 ●●●●● patch | view | raw | blame | history
src/utils/cesium/kmz.js 193 ●●●● patch | view | raw | blame | history
src/utils/cesium/mapUtil.js 67 ●●●●● patch | view | raw | blame | history
src/utils/cesium/use-kmz-tsa.js 264 ●●●● patch | view | raw | blame | history
src/utils/crypto.js 38 ●●●● patch | view | raw | blame | history
src/utils/date.js 34 ●●●● patch | view | raw | blame | history
src/utils/flow.js 8 ●●●● patch | view | raw | blame | history
src/utils/formatter.js 29 ●●●●● patch | view | raw | blame | history
src/utils/func.js 116 ●●●● patch | view | raw | blame | history
src/utils/http/config.js 7 ●●●● patch | view | raw | blame | history
src/utils/http/enums.js 2 ●●● patch | view | raw | blame | history
src/utils/module.js 30 ●●●● patch | view | raw | blame | history
src/utils/rem.js 5 ●●●●● patch | view | raw | blame | history
src/utils/sensitive.js 32 ●●●● patch | view | raw | blame | history
src/utils/sm2.js 8 ●●●● patch | view | raw | blame | history
src/utils/staticData/device.js 36 ●●●● patch | view | raw | blame | history
src/utils/staticData/enums.js 12 ●●●● patch | view | raw | blame | history
src/utils/store.js 78 ●●●● patch | view | raw | blame | history
src/utils/util.js 340 ●●●● patch | view | raw | blame | history
src/utils/validate.js 162 ●●●● patch | view | raw | blame | history
src/utils/websocket/connect-websocket.js 12 ●●●● patch | view | raw | blame | history
src/utils/websocket/drone-ws-control.js 107 ●●●●● patch | view | raw | blame | history
src/views/Home/Footer.vue 54 ●●●● patch | view | raw | blame | history
src/views/Home/components/HomeLeft/InspectionRaskDetails.vue 71 ●●●● patch | view | raw | blame | history
src/views/Home/useEventOperate/useEventOperate.js 178 ●●●● patch | view | raw | blame | history
src/views/Home/useUavHome/useUavHome.js 366 ●●●● patch | view | raw | blame | history
src/websocket/index.js 52 ●●●● patch | view | raw | blame | history
src/websocket/util/config.js 13 ●●●● patch | view | raw | blame | history
.prettierrc.json
@@ -1,9 +1,24 @@
{
  "printWidth": 120,
  "printWidth": 100,
  "tabWidth": 2,
  "semi": true,
  "semi": false,
  "singleAttributePerLine": false,
  "bracketSpacing": true,
  "singleQuote": true,
  "arrowParens": "avoid"
  "arrowParens": "avoid",
  "endOfLine": "crlf",
  "bracketSameLine": false,
  "proseWrap": "preserve",
  "useTabs": true,
  "trailingComma": "es5",
  "overrides": [
    {
      "files": "*.scss",
      "options": {
        "parser": "scss",
        "tabWidth": 4,
        "singleQuote": false
      }
    }
  ]
}
package.json
@@ -6,7 +6,8 @@
        "prod": "vite --mode production",
        "build:dev": "vite build --mode development",
        "build:prod": "vite build --mode production",
        "serve": "vite preview --host"
    "serve": "vite preview --host",
    "format": "prettier --write \"src/**/*.+(js|ts|jsx|tsx)\""
    },
    "dependencies": {
        "@element-plus/icons-vue": "^2.3.1",
src/api/base/region.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getLazyTree = (parentCode, params) => {
  return request({
@@ -20,8 +20,8 @@
      ...params,
      parentCode,
    },
  });
};
    })
}
export const getDetail = code => {
  return request({
@@ -30,8 +30,8 @@
    params: {
      code,
    },
  });
};
    })
}
export const remove = id => {
  return request({
@@ -40,13 +40,13 @@
    params: {
      id,
    },
  });
};
    })
}
export const submit = row => {
  return request({
    url: '/blade-system/region/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/common.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
/**
 * 文件流返回
@@ -11,5 +11,5 @@
    params: params,
    method: 'get',
    responseType: 'blob',
  });
};
    })
}
src/api/desk/notice.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -11,8 +11,8 @@
    },
    cryptoToken: false,
    cryptoData: false,
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -23,8 +23,8 @@
    },
    cryptoToken: false,
    cryptoData: false,
  });
};
    })
}
export const add = row => {
  return request({
@@ -33,8 +33,8 @@
    data: row,
    cryptoToken: false,
    cryptoData: false,
  });
};
    })
}
export const update = row => {
  return request({
@@ -43,8 +43,8 @@
    data: row,
    cryptoToken: false,
    cryptoData: false,
  });
};
    })
}
export const getNotice = id => {
  return request({
@@ -55,5 +55,5 @@
    },
    cryptoToken: false,
    cryptoData: false,
  });
};
    })
}
src/api/flow/flow.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const modelList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const managerList = (current, size, params) => {
  return request({
@@ -21,8 +21,8 @@
      current,
      size,
    },
  });
};
    })
}
export const followList = (current, size, params) => {
  return request({
@@ -33,8 +33,8 @@
      current,
      size,
    },
  });
};
    })
}
export const removeModel = ids => {
  return request({
@@ -43,32 +43,32 @@
    params: {
      ids,
    },
  });
};
    })
}
export const deployModel = params => {
  return request({
    url: '/blade-flow/model/deploy',
    method: 'post',
    params,
  });
};
    })
}
export const changeState = params => {
  return request({
    url: '/blade-flow/manager/change-state',
    method: 'post',
    params,
  });
};
    })
}
export const deployUpload = (category, tenantIds, files) => {
  const formData = new FormData();
  formData.append('category', category);
  formData.append('tenantIds', tenantIds);
    const formData = new FormData()
    formData.append('category', category)
    formData.append('tenantIds', tenantIds)
  files.forEach(file => {
    formData.append('files', file);
  });
        formData.append('files', file)
    })
  return request({
    headers: {
      'Content-Type': 'multipart/form-data',
@@ -76,8 +76,8 @@
    url: '/blade-flow/manager/deploy-upload',
    method: 'post',
    data: formData,
  });
};
    })
}
export const deleteDeployment = deploymentIds => {
  return request({
@@ -86,37 +86,37 @@
    params: {
      deploymentIds,
    },
  });
};
    })
}
export const deleteProcessInstance = params => {
  return request({
    url: '/blade-flow/follow/delete-process-instance',
    method: 'post',
    params,
  });
};
    })
}
export const submitModel = data => {
  return request({
    url: '/blade-flow/model/submit',
    method: 'post',
    data,
  });
};
    })
}
export const detail = params => {
  return request({
    url: '/blade-flow/model/detail',
    method: 'get',
    params,
  });
};
    })
}
export const modelView = params => {
  return request({
    url: '/blade-flow/process/model-view',
    method: 'get',
    params,
  });
};
    })
}
src/api/home/aggregation.js
@@ -1,19 +1,17 @@
import request from '@/axios';
import request from '@/axios'
export const getDeviceRegionCount = (params) => {
export const getDeviceRegionCount = params => {
  return request({
    url: '/drone-device-core/manage/api/v1/devices/getDeviceRegionCount',
    method: 'get',
    params
  });
};
        params,
    })
}
export const getDeviceRegion = (params) => {
export const getDeviceRegion = params => {
  return request({
    url: '/drone-device-core/manage/api/v1/devices/getDeviceRegion',
    method: 'get',
    params
  });
};
        params,
    })
}
src/api/home/index.js
@@ -1,110 +1,109 @@
import request from '@/axios';
import request from '@/axios'
// 巡检总任务数量
export const getTotalJobNum = (params) => {
export const getTotalJobNum = params => {
  return request({
    url: '/drone-device-core/wayline/waylineJobInfo/totalJobNum',
    method: 'get',
    params
  });
};
        params,
    })
}
// 巡检任务item数量
export const getJobStatistics = (data) => {
export const getJobStatistics = data => {
  return request({
    url: '/drone-device-core/wayline/waylineJobInfo/jobStatistics',
    method: 'post',
    data
  });
};
        data,
    })
}
// 巡检任务柱状图数据
export const getJobNumBar = (data) => {
export const getJobNumBar = data => {
  return request({
    url: '/drone-device-core/wayline/waylineJobInfo/jobNumBar',
    method: 'post',
    data
  });
};
        data,
    })
}
// 事件概况总数
export const getJobEventTotal = () => {
  return request({
    url: '/drone-device-core/jobEvent/total',
    method: 'get',
  });
};
    })
}
// 事件概况分类数
export const getJobEventByStatus = (data) => {
export const getJobEventByStatus = data => {
  return request({
    url: '/drone-device-core/jobEvent/eventByStatus',
    method: 'post',
    data
  });
};
export const getJobEventBrokerLine = (data) => {
        data,
    })
}
export const getJobEventBrokerLine = data => {
  return request({
    url: '/drone-device-core/jobEvent/eventBrokerLine',
    method: 'post',
    data
  });
};
        data,
    })
}
// 任务成果
export const getMediaFileCountBy = () => {
  return request({
    url: '/blade-resource/media/api/v1/workspaces/files/getMediaFileCountBy',
    method: 'get',
  });
};
    })
}
// 降本增效
export const optimizeCostEfficiency = () => {
  return request({
    url: '/drone-device-core/manage/api/v1/devices/optimizeCostEfficiency',
    method: 'get',
  });
};
    })
}
// 历史巡检任务列表
export const getBeforeJob = (data) => {
export const getBeforeJob = data => {
  return request({
    url: '/drone-device-core/wayline/waylineJobInfo/beforeJob',
    method: 'post',
    data
  });
};
        data,
    })
}
// 当前巡检任务列表
export const getTodayJob = (data) => {
export const getTodayJob = data => {
  return request({
    url: '/drone-device-core/wayline/waylineJobInfo/todayJob',
    method: 'post',
    data
  });
};
        data,
    })
}
// 巡检任务详情 柱状图
export const jobNumBar = (data) => {
export const jobNumBar = data => {
  return request({
    url: '/drone-device-core/wayline/waylineJobInfo/jobEventBar',
    method: 'post',
    data
  });
};
        data,
    })
}
// 巡检任务详情 饼图
export const eventNumPie = (data) => {
export const eventNumPie = data => {
  return request({
    url: '/drone-device-core/jobEvent/eventNumPie',
    method: 'post',
    data
  });
};
        data,
    })
}
// 获取区域
export const getRegion = (code) => {
export const getRegion = code => {
  return request({
    url: '/blade-system/region/select',
    method: 'get',
    params:{code}
  });
};
        params: { code },
    })
}
src/api/home/machineNest.js
@@ -1,13 +1,13 @@
import request from '@/axios';
import request from '@/axios'
// 机巢统计
export const getDeviceInfoNum = (params) => {
export const getDeviceInfoNum = params => {
  return request({
    url: '/drone-device-core/manage/api/v1/devices/getDeviceInfoNum',
    method: 'get',
    params,
  });
};
    })
}
// 机巢列表
export const selectDevicePage = ({ nickname,is_execute, ...params}) => {
  return request({
@@ -17,33 +17,32 @@
      nickname,
      is_execute,
    },
  });
};
    })
}
// 机巢数据
export const getFlightStatistics = (dockSn) => {
export const getFlightStatistics = dockSn => {
  return request({
    url: `/drone-device-core/manage/api/v1/devices/getFlightStatistics?dockSn=${dockSn}`,
    method: 'get',
    params: {},
  });
};
    })
}
// 机巢直播/无人机直播 均可使用
export const liveStart = (deviceSn) => {
export const liveStart = deviceSn => {
  return request({
    url: `/drone-device-core/manage/api/v1/live/streams/liveStart?deviceSn=${deviceSn}`,
    method: 'post',
    data: {},
    headers: {
      'areaCode': '',
            areaCode: '',
    },
  });
};
    })
}
// 单个机巢获取机巢详情
export const getDeviceDetail = (deviceSn) => {
export const getDeviceDetail = deviceSn => {
  return request({
    url: `/drone-device-core/manage/api/v1/devices/getDeviceDetail?deviceSn=${deviceSn}`,
    method: 'get',
    params: {},
  });
};
    })
}
src/api/job/jobinfo.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,24 +29,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-job/job-info/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-job/job-info/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const change = row => {
  return request({
@@ -56,8 +56,8 @@
      id: row.id,
      enable: row.enable,
    },
  });
};
    })
}
export const run = row => {
  return request({
@@ -66,13 +66,13 @@
    params: {
      id: row.id,
    },
  });
};
    })
}
export const sync = row => {
  return request({
    url: '/blade-job/job-info/sync',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/job/jobserver.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,29 +29,29 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-job/job-server/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-job/job-server/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const sync = row => {
  return request({
    url: '/blade-job/job-server/sync',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/logs.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getUsualList = (current, size) => {
  return request({
@@ -8,8 +8,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getApiList = (current, size) => {
  return request({
@@ -19,8 +19,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getErrorList = (current, size) => {
  return request({
@@ -30,8 +30,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getUsualLogs = id => {
  return request({
@@ -40,8 +40,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const getApiLogs = id => {
  return request({
    url: '/blade-log/api/detail',
@@ -49,8 +49,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const getErrorLogs = id => {
  return request({
    url: '/blade-log/error/detail',
@@ -58,5 +58,5 @@
    params: {
      id,
    },
  });
};
    })
}
src/api/report/report.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
    url: '/blade-report/report/rest/remove',
@@ -18,5 +18,5 @@
    params: {
      ids,
    },
  });
};
    })
}
src/api/resource/attach.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,21 +29,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-resource/attach/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-resource/attach/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/resource/oss.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,24 +29,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-resource/oss/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-resource/oss/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const enable = id => {
  return request({
@@ -55,5 +55,5 @@
    params: {
      id,
    },
  });
};
    })
}
src/api/resource/sms.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,24 +29,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-resource/sms/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-resource/sms/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const enable = id => {
  return request({
@@ -55,8 +55,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const send = (code, phones, params) => {
  return request({
@@ -67,5 +67,5 @@
      phones,
      params,
    },
  });
};
    })
}
src/api/system/client.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,21 +29,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/client/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/client/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/system/dept.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getLazyList = (parentId, params) => {
  return request({
@@ -20,8 +20,8 @@
      ...params,
      parentId,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -30,24 +30,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/dept/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/dept/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getDept = id => {
  return request({
@@ -56,8 +56,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const getDeptTree = tenantId => {
  return request({
@@ -66,8 +66,8 @@
    params: {
      tenantId,
    },
  });
};
    })
}
export const getDeptLazyTree = parentId => {
  return request({
@@ -76,5 +76,5 @@
    params: {
      parentId,
    },
  });
};
    })
}
src/api/system/dict.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getParentList = (current, size, params) => {
  return request({
@@ -21,8 +21,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getChildList = (current, size, parentId, params) => {
  return request({
@@ -34,8 +34,8 @@
      size,
      parentId: parentId,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -44,24 +44,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/dict/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/dict/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getDict = id => {
  return request({
@@ -70,19 +70,19 @@
    params: {
      id,
    },
  });
};
    })
}
export const getDictTree = () => {
  return request({
    url: '/blade-system/dict/tree?code=DICT',
    method: 'get',
  });
};
    })
}
export const getDictionary = params => {
  return request({
    url: '/blade-system/dict/dictionary',
    method: 'get',
    params,
  });
};
    })
}
src/api/system/dictbiz.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getParentList = (current, size, params) => {
  return request({
@@ -21,8 +21,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getChildList = (current, size, parentId, params) => {
  return request({
@@ -34,8 +34,8 @@
      size,
      parentId: parentId,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -44,24 +44,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/dict-biz/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/dict-biz/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getDict = id => {
  return request({
@@ -70,19 +70,19 @@
    params: {
      id,
    },
  });
};
    })
}
export const getDictTree = () => {
  return request({
    url: '/blade-system/dict-biz/tree?code=DICT',
    method: 'get',
  });
};
    })
}
export const getDictionary = params => {
  return request({
    url: '/blade-system/dict-biz/dictionary',
    method: 'get',
    params,
  });
};
    })
}
src/api/system/menu.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getLazyList = (parentId, params) => {
  return request({
@@ -20,8 +20,8 @@
      ...params,
      parentId,
    },
  });
};
    })
}
export const getLazyMenuList = (parentId, params) => {
  return request({
@@ -31,8 +31,8 @@
      ...params,
      parentId,
    },
  });
};
    })
}
export const getMenuList = (current, size, params) => {
  return request({
@@ -43,8 +43,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getMenuTree = tenantId => {
  return request({
@@ -53,8 +53,8 @@
    params: {
      tenantId,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -63,24 +63,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/menu/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/menu/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getMenu = id => {
  return request({
@@ -89,14 +89,14 @@
    params: {
      id,
    },
  });
};
    })
}
export const getTopMenu = () =>
  request({
    url: '/blade-system/menu/top-menu',
    method: 'get',
  });
    })
export const getRoutes = topMenuId =>
  request({
@@ -105,4 +105,4 @@
    params: {
      topMenuId,
    },
  });
    })
src/api/system/param.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,21 +29,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/param/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/param/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/system/post.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getPostList = tenantId => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      tenantId,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -29,8 +29,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -39,21 +39,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/post/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/post/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/system/role.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,14 +9,14 @@
      current,
      size,
    },
  });
};
    })
}
export const grantTree = () => {
  return request({
    url: '/blade-system/menu/grant-tree',
    method: 'get',
  });
};
    })
}
export const grant = (roleIds, menuIds, dataScopeIds, apiScopeIds) => {
  return request({
@@ -28,8 +28,8 @@
      dataScopeIds,
      apiScopeIds,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -38,24 +38,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/role/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/role/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getRole = roleIds => {
  return request({
@@ -64,8 +64,8 @@
    params: {
      roleIds,
    },
  });
};
    })
}
export const getRoleTree = tenantId => {
  return request({
@@ -74,8 +74,8 @@
    params: {
      tenantId,
    },
  });
};
    })
}
export const getRoleTreeById = roleId => {
  return request({
@@ -84,13 +84,13 @@
    params: {
      roleId,
    },
  });
};
    })
}
export const getRoleAlias = () => {
  return request({
    url: '/blade-system/role/alias',
    method: 'get',
    params: {},
  });
};
    })
}
src/api/system/scope.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getListDataScope = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const removeDataScope = ids => {
  return request({
@@ -19,24 +19,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const addDataScope = row => {
  return request({
    url: '/blade-system/data-scope/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const updateDataScope = row => {
  return request({
    url: '/blade-system/data-scope/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getMenuDataScope = id => {
  return request({
@@ -45,8 +45,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const getListApiScope = (current, size, params) => {
  return request({
@@ -57,8 +57,8 @@
      current,
      size,
    },
  });
};
    })
}
export const removeApiScope = ids => {
  return request({
@@ -67,24 +67,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const addApiScope = row => {
  return request({
    url: '/blade-system/api-scope/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const updateApiScope = row => {
  return request({
    url: '/blade-system/api-scope/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getMenuApiScope = id => {
  return request({
@@ -93,5 +93,5 @@
    params: {
      id,
    },
  });
};
    })
}
src/api/system/tenant.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,24 +19,24 @@
    params: {
      id,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/tenant/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/tenant/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const setting = (ids, form) => {
  return request({
@@ -46,8 +46,8 @@
      ...form,
      ids,
    },
  });
};
    })
}
export const datasource = (tenantId, datasourceId) => {
  return request({
@@ -57,8 +57,8 @@
      tenantId,
      datasourceId,
    },
  });
};
    })
}
export const info = domain => {
  return request({
@@ -67,8 +67,8 @@
    params: {
      domain,
    },
  });
};
    })
}
export const packageInfo = tenantId => {
  return request({
@@ -77,8 +77,8 @@
    params: {
      tenantId,
    },
  });
};
    })
}
export const packageSetting = (tenantId, packageId) => {
  return request({
@@ -88,8 +88,8 @@
      tenantId,
      packageId,
    },
  });
};
    })
}
export const recycle = ids => {
  return request({
@@ -98,8 +98,8 @@
    params: {
      ids,
    },
  });
};
    })
}
export const pass = ids => {
  return request({
@@ -108,8 +108,8 @@
    params: {
      ids,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -118,5 +118,5 @@
    params: {
      ids,
    },
  });
};
    })
}
src/api/system/tenantdatasource.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,21 +29,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/tenant-datasource/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/tenant-datasource/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/system/tenantpackage.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,21 +29,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/tenant-package/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/tenant-package/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/system/topmenu.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,31 +29,31 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/topmenu/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/topmenu/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const grantTree = () => {
  return request({
    url: '/blade-system/menu/grant-top-tree',
    method: 'get',
  });
};
    })
}
export const getTopTree = topMenuIds => {
  return request({
@@ -62,8 +62,8 @@
    params: {
      topMenuIds,
    },
  });
};
    })
}
export const grant = (topMenuIds, menuIds) => {
  return request({
@@ -73,5 +73,5 @@
      topMenuIds,
      menuIds,
    },
  });
};
    })
}
src/api/system/user.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params, deptId) => {
  return request({
@@ -10,8 +10,8 @@
      size,
      deptId,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -20,24 +20,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-system/user/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-system/user/update',
    method: 'post',
    data: row,
  });
};
    })
}
export const updatePlatform = (userId, userType, userExt) => {
  return request({
@@ -48,8 +48,8 @@
      userType,
      userExt,
    },
  });
};
    })
}
export const getUser = id => {
  return request({
@@ -58,8 +58,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const getUserPlatform = id => {
  return request({
@@ -68,15 +68,15 @@
    params: {
      id,
    },
  });
};
    })
}
export const getUserInfo = () => {
  return request({
    url: '/blade-system/user/info',
    method: 'get',
  });
};
    })
}
export const resetPassword = userIds => {
  return request({
@@ -85,8 +85,8 @@
    params: {
      userIds,
    },
  });
};
    })
}
export const updatePassword = (oldPassword, newPassword, newPassword1) => {
  return request({
@@ -97,16 +97,16 @@
      newPassword,
      newPassword1,
    },
  });
};
    })
}
export const updateInfo = row => {
  return request({
    url: '/blade-system/user/update-info',
    method: 'post',
    data: row,
  });
};
    })
}
export const grant = (userIds, roleIds) => {
  return request({
@@ -116,8 +116,8 @@
      userIds,
      roleIds,
    },
  });
};
    })
}
export const unlock = userIds => {
  return request({
@@ -126,8 +126,8 @@
    params: {
      userIds,
    },
  });
};
    })
}
export const auditPass = userIds => {
  return request({
@@ -136,8 +136,8 @@
    params: {
      userIds,
    },
  });
};
    })
}
export const auditRefuse = userIds => {
  return request({
@@ -146,5 +146,5 @@
    params: {
      userIds,
    },
  });
};
    })
}
src/api/tool/code.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const build = ids => {
  return request({
@@ -20,16 +20,16 @@
      ids,
      system: 'saber',
    },
  });
};
    })
}
export const buildFast = form => {
  return request({
    url: '/blade-develop/code/gen-code-fast',
    method: 'post',
    data: form,
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -38,24 +38,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-develop/code/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-develop/code/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const copy = id => {
  return request({
@@ -64,8 +64,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const getCode = id => {
  return request({
@@ -74,5 +74,5 @@
    params: {
      id,
    },
  });
};
    })
}
src/api/tool/codesetting.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,24 +29,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-develop/code-setting/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-develop/code-setting/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const enable = id => {
  return request({
@@ -55,16 +55,16 @@
    params: {
      id,
    },
  });
};
    })
}
export const getEnableDetail = () => {
  return request({
    url: '/blade-develop/code-setting/enable-detail',
    method: 'get',
    params: {},
  });
};
    })
}
export const getTableForm = tableName => {
  return request({
@@ -73,8 +73,8 @@
    params: {
      tableName,
    },
  });
};
    })
}
export const getTablePrototype = (tableName, datasourceId) => {
  return request({
@@ -84,5 +84,5 @@
      tableName,
      datasourceId,
    },
  });
};
    })
}
src/api/tool/datasource.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,21 +29,21 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-develop/datasource/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-develop/datasource/submit',
    method: 'post',
    data: row,
  });
};
    })
}
src/api/tool/model.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const getList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const getDetail = id => {
  return request({
@@ -19,8 +19,8 @@
    params: {
      id,
    },
  });
};
    })
}
export const remove = ids => {
  return request({
@@ -29,24 +29,24 @@
    params: {
      ids,
    },
  });
};
    })
}
export const add = row => {
  return request({
    url: '/blade-develop/model/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const update = row => {
  return request({
    url: '/blade-develop/model/submit',
    method: 'post',
    data: row,
  });
};
    })
}
export const getTableList = datasourceId => {
  return request({
@@ -55,8 +55,8 @@
    params: {
      datasourceId,
    },
  });
};
    })
}
export const getTableInfo = (modelId, datasourceId) => {
  return request({
@@ -66,8 +66,8 @@
      modelId,
      datasourceId,
    },
  });
};
    })
}
export const getTableInfoByName = (tableName, datasourceId) => {
  return request({
@@ -77,8 +77,8 @@
      tableName,
      datasourceId,
    },
  });
};
    })
}
export const getModelPrototype = (modelId, datasourceId) => {
  return request({
@@ -88,16 +88,16 @@
      modelId,
      datasourceId,
    },
  });
};
    })
}
export const submitModelPrototype = row => {
  return request({
    url: '/blade-develop/model-prototype/submit-list',
    method: 'post',
    data: row,
  });
};
    })
}
export const prototypeDetail = modelId => {
  return request({
@@ -106,5 +106,5 @@
    params: {
      modelId,
    },
  });
};
    })
}
src/api/user.js
@@ -1,7 +1,7 @@
import request from '@/axios';
import request from '@/axios'
import website from '@/config/website';
import func from '@/utils/func';
import website from '@/config/website'
import func from '@/utils/func'
export const loginByUsername = (tenantId, deptId, roleId, username, password, type, key, code) =>
  request({
@@ -22,7 +22,7 @@
      scope: 'all',
      type,
    },
  });
    })
export const loginBySocial = (tenantId, source, code, state) =>
  request({
@@ -39,7 +39,7 @@
      grant_type: 'social',
      scope: 'all',
    },
  });
    })
export const loginBySso = (state, code) =>
  request({
@@ -55,7 +55,7 @@
      scope: 'all',
      redirect_uri: website.oauth2.redirectUri,
    },
  });
    })
export const loginByPhone = (tenantId, phone, id, value) =>
  request({
@@ -72,7 +72,7 @@
      grant_type: 'sms_code',
      scope: 'all',
    },
  });
    })
export const refreshToken = (refresh_token, tenantId, deptId, roleId) =>
  request({
@@ -89,7 +89,7 @@
      grant_type: 'refresh_token',
      scope: 'all',
    },
  });
    })
export const registerUser = (tenantId, name, account, password, phone, email) =>
  request({
@@ -108,7 +108,7 @@
      grant_type: 'register',
      scope: 'all',
    },
  });
    })
export const registerGuest = (form, oauthId) =>
  request({
@@ -121,47 +121,47 @@
      password: form.password,
      oauthId,
    },
  });
    })
export const getButtons = () =>
  request({
    url: '/blade-system/menu/buttons',
    method: 'get',
  });
    })
export const getCaptcha = () =>
  request({
    url: '/blade-auth/oauth/captcha',
    method: 'get',
    authorization: false,
  });
    })
export const logout = () =>
  request({
    url: '/blade-auth/oauth/logout',
    method: 'get',
    authorization: false,
  });
    })
export const getUserInfo = () =>
  request({
    url: '/blade-auth/oauth/user-info',
    method: 'get',
  });
    })
export const sendLogs = list =>
  request({
    url: '/blade-auth/oauth/logout',
    method: 'post',
    data: list,
  });
    })
export const clearCache = () =>
  request({
    url: '/blade-auth/oauth/clear-cache',
    method: 'get',
    authorization: false,
  });
    })
export const sendSms = (tenantId, phone) =>
  request({
@@ -171,4 +171,4 @@
      tenantId,
      phone,
    },
  });
    })
src/api/work/process.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
// =====================参数===========================
@@ -9,8 +9,8 @@
    params: {
      processInstanceId,
    },
  });
};
    })
}
// =====================请假流程===========================
@@ -19,8 +19,8 @@
    url: '/blade-desk/process/leave/start-process',
    method: 'post',
    data,
  });
};
    })
}
export const leaveDetail = businessId => {
  return request({
@@ -29,5 +29,5 @@
    params: {
      businessId,
    },
  });
};
    })
}
src/api/work/work.js
@@ -1,4 +1,4 @@
import request from '@/axios';
import request from '@/axios'
export const startList = (current, size, params) => {
  return request({
@@ -9,8 +9,8 @@
      current,
      size,
    },
  });
};
    })
}
export const claimList = (current, size, params) => {
  return request({
@@ -21,8 +21,8 @@
      current,
      size,
    },
  });
};
    })
}
export const todoList = (current, size, params) => {
  return request({
@@ -33,8 +33,8 @@
      current,
      size,
    },
  });
};
    })
}
export const sendList = (current, size, params) => {
  return request({
@@ -45,8 +45,8 @@
      current,
      size,
    },
  });
};
    })
}
export const doneList = (current, size, params) => {
  return request({
@@ -57,8 +57,8 @@
      current,
      size,
    },
  });
};
    })
}
export const claimTask = taskId => {
  return request({
@@ -67,13 +67,13 @@
    params: {
      taskId,
    },
  });
};
    })
}
export const completeTask = data => {
  return request({
    url: '/blade-flow/work/complete-task',
    method: 'post',
    data,
  });
};
    })
}
src/axios.js
@@ -5,75 +5,75 @@
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios';
import store from '@/store/';
import router from '@/router/';
import { serialize } from '@/utils/util';
import { getToken, removeToken, removeRefreshToken } from '@/utils/auth';
import { isURL, validatenull } from '@/utils/validate';
import { ElMessage } from 'element-plus';
import website from '@/config/website';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
import { Base64 } from 'js-base64';
import { baseUrl } from '@/config/env';
import crypto from '@/utils/crypto';
import axios from 'axios'
import store from '@/store/'
import router from '@/router/'
import { serialize } from '@/utils/util'
import { getToken, removeToken, removeRefreshToken } from '@/utils/auth'
import { isURL, validatenull } from '@/utils/validate'
import { ElMessage } from 'element-plus'
import website from '@/config/website'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { Base64 } from 'js-base64'
import { baseUrl } from '@/config/env'
import crypto from '@/utils/crypto'
// 全局未授权错误提示状态,只提示一次
let isErrorShown = false;
let isErrorShown = false
// 全局锁机制相关变量
let isRefreshing = false; // 标记当前是否正在刷新token
let refreshTokenPromise = null; // 刷新token的Promise,避免重复请求
let isRefreshing = false // 标记当前是否正在刷新token
let refreshTokenPromise = null // 刷新token的Promise,避免重复请求
axios.defaults.timeout = 10000;
axios.defaults.timeout = 10000
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
    return status >= 200 && status <= 500 // 默认的
}
//跨域请求,允许保存cookie
axios.defaults.withCredentials = true;
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false,
});
})
//http request拦截
axios.interceptors.request.use(
  config => {
    // start progress bar
    NProgress.start();
        NProgress.start()
    // 初始化错误提示状态
    isErrorShown = false;
        isErrorShown = false
    //地址为已经配置状态则不添加前缀
    if (!isURL(config.url) && !config.url.startsWith(baseUrl)) {
      config.url = baseUrl + config.url;
            config.url = baseUrl + config.url
    }
    config.headers['areaCode'] = store.state.user.selectedAreaCode;
        config.headers['areaCode'] = store.state.user.selectedAreaCode
    //安全请求header
    config.headers['Blade-Requested-With'] = 'BladeHttpRequest';
        config.headers['Blade-Requested-With'] = 'BladeHttpRequest'
    //headers判断是否需要
    const authorization = config.authorization === false;
        const authorization = config.authorization === false
    if (!authorization) {
      config.headers['Authorization'] = `Basic ${Base64.encode(
        `${website.clientId}:${website.clientSecret}`
      )}`;
            )}`
    }
    // 根据后端要求,post的data为空的话传{}
    if (config.method === 'post') {
      config.data = config.data || {};
            config.data = config.data || {}
    }
    //headers判断请求是否携带token
    const meta = config.meta || {};
    const isToken = meta.isToken === false;
        const meta = config.meta || {}
        const isToken = meta.isToken === false
    //headers传递token是否加密
    const cryptoToken = config.cryptoToken === true;
        const cryptoToken = config.cryptoToken === true
    //判断传递数据是否加密
    const cryptoData = config.cryptoData === true;
    const token = getToken();
        const cryptoData = config.cryptoData === true
        const token = getToken()
    if (token && !isToken) {
      config.headers[website.tokenHeader] = cryptoToken
        ? 'crypto ' + crypto.encryptAES(token, crypto.cryptoKey)
        : 'bearer ' + token;
                : 'bearer ' + token
    }
    // 开启报文加密
    // if (cryptoData) {
@@ -88,123 +88,123 @@
    // }
    //headers中配置text请求
    if (config.text === true) {
      config.headers['Content-Type'] = 'text/plain';
            config.headers['Content-Type'] = 'text/plain'
    }
    //headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta.isSerialize === true) {
      config.data = serialize(config.data);
            config.data = serialize(config.data)
    }
    return config;
        return config
  },
  error => {
    return Promise.reject(error);
        return Promise.reject(error)
  }
);
)
//http response拦截
axios.interceptors.response.use(
  res => {
    NProgress.done();
        NProgress.done()
    //获取配置信息
    const config = res.config;
    const cryptoData = config.cryptoData === true;
        const config = res.config
        const cryptoData = config.cryptoData === true
    //解析加密报文
    if (cryptoData) {
      res.data = JSON.parse(crypto.decryptAES(res.data, crypto.aesKey));
            res.data = JSON.parse(crypto.decryptAES(res.data, crypto.aesKey))
    }
    //获取状态信息
    const status = res.data.error_code || res.data.code || res.status;
    const statusWhiteList = website.statusWhiteList || [];
    const message = res.data.msg || res.data.error_description || '系统错误';
        const status = res.data.error_code || res.data.code || res.status
        const statusWhiteList = website.statusWhiteList || []
        const message = res.data.msg || res.data.error_description || '系统错误'
    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res);
        if (statusWhiteList.includes(status)) return Promise.reject(res)
    // 如果是401并且没有重试过,尝试刷新token
    if (status === 401 && !config._retry) {
      config._retry = true;
            config._retry = true
      // 如果当前已经在刷新token,等待刷新完成
      if (isRefreshing) {
        return refreshTokenPromise.then(() => {
          const meta = config.meta || {};
          const isToken = meta.isToken === false;
          const cryptoToken = config.cryptoToken === true;
          const token = getToken();
                    const meta = config.meta || {}
                    const isToken = meta.isToken === false
                    const cryptoToken = config.cryptoToken === true
                    const token = getToken()
          if (token && !isToken) {
            config.headers[website.tokenHeader] = cryptoToken
              ? 'crypto ' + crypto.encryptAES(token, crypto.cryptoKey)
              : 'bearer ' + token;
                            : 'bearer ' + token
          }
          return axios(config);
        });
                    return axios(config)
                })
      }
      // 开始刷新token
      isRefreshing = true;
            isRefreshing = true
      // 调用RefreshToken action来刷新token
      refreshTokenPromise = store
        .dispatch('RefreshToken')
        .then(() => {
          isRefreshing = false; // 重置刷新标志
          const meta = config.meta || {};
          const isToken = meta.isToken === false;
          const cryptoToken = config.cryptoToken === true;
                    isRefreshing = false // 重置刷新标志
                    const meta = config.meta || {}
                    const isToken = meta.isToken === false
                    const cryptoToken = config.cryptoToken === true
          // 获取刷新后的token
          const token = getToken();
                    const token = getToken()
          if (token && !isToken) {
            config.headers[website.tokenHeader] = cryptoToken
              ? 'crypto ' + crypto.encryptAES(token, crypto.cryptoKey)
              : 'bearer ' + token;
                            : 'bearer ' + token
          }
          return axios(config);
                    return axios(config)
        })
        .catch(() => {
          isRefreshing = false; // 重置刷新标志
                    isRefreshing = false // 重置刷新标志
          // 首次报错时提示
          if (!isErrorShown) {
            isErrorShown = true;
                        isErrorShown = true
            ElMessage({
              message: '用户令牌不可用,请重新登录',
              type: 'error',
            });
                        })
          }
          // 清除token信息
          removeToken();
          removeRefreshToken();
                    removeToken()
                    removeRefreshToken()
          // 重定向到登录页
          store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }));
          return Promise.reject(new Error(message));
        });
                    store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }))
                    return Promise.reject(new Error(message))
                })
      return refreshTokenPromise;
            return refreshTokenPromise
    }
    // 如果是401并且已经重试过,直接跳转到登录页面
    if (status === 401 && config._retry) {
      if (!isErrorShown) {
        isErrorShown = true;
                isErrorShown = true
        ElMessage({
          message: '用户令牌不可用,请重新登录',
          type: 'error',
        });
                })
      }
      removeToken();
      removeRefreshToken();
      store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }));
      return Promise.reject(new Error(message));
            removeToken()
            removeRefreshToken()
            store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }))
            return Promise.reject(new Error(message))
    }
    // 如果请求为oauth2错误码则首次报错时提示
    if (status > 2000 && !validatenull(res.data.error_description)) {
      if (!isErrorShown) {
        isErrorShown = true;
                isErrorShown = true
        ElMessage({
          message: message,
          type: 'error',
        });
                })
      }
      return Promise.reject(new Error(message));
            return Promise.reject(new Error(message))
    }
    // 如果请求为非200则默认统一处理
@@ -212,15 +212,15 @@
      ElMessage({
        message: message,
        type: 'error',
      });
      return Promise.reject(new Error(message));
            })
            return Promise.reject(new Error(message))
    }
    return res;
        return res
  },
  error => {
    NProgress.done();
    return Promise.reject(new Error(error));
        NProgress.done()
        return Promise.reject(new Error(error))
  }
);
)
export default axios;
export default axios
src/components/basic-video/plugin.js
@@ -5,9 +5,9 @@
   * @param  {Object}   videoObj 视频对象
   */
  constructor(videoObj) {
    this.video = videoObj;
    this.mediaRecorder = null;
    this.chunks = [];
        this.video = videoObj
        this.mediaRecorder = null
        this.chunks = []
  }
  /**
@@ -33,27 +33,27 @@
        .then(stream => {
          // 检测是否支持 srcObject,该属性在新的浏览器支持
          if ('srcObject' in this.video) {
            this.video.srcObject = stream;
                        this.video.srcObject = stream
          } else {
            // 兼容旧的浏览器
            this.video.src = window.URL.createObjectURL(stream);
                        this.video.src = window.URL.createObjectURL(stream)
          }
          // 当视频的元数据已经加载时触发
          this.video.addEventListener('loadmetadata', () => {
            this.video.play();
          });
          this.mediaRecorder = new MediaRecorder(stream);
                        this.video.play()
                    })
                    this.mediaRecorder = new MediaRecorder(stream)
          this.mediaRecorder.addEventListener('dataavailable', e => {
            this.chunks.push(e.data);
          });
          resovle();
                        this.chunks.push(e.data)
                    })
                    resovle()
        })
        // 异常抓取,包括用于禁用麦克风、摄像头
        .catch(error => {
          reject(error);
        });
    });
                    reject(error)
                })
        })
  }
  /**
@@ -61,7 +61,7 @@
   */
  startRecord() {
    if (this.mediaRecorder.state === 'inactive') {
      this.mediaRecorder.start();
            this.mediaRecorder.start()
    }
  }
@@ -70,7 +70,7 @@
   */
  stopRecord() {
    if (this.mediaRecorder.state === 'recording') {
      this.mediaRecorder.stop();
            this.mediaRecorder.stop()
    }
  }
@@ -80,9 +80,9 @@
   * @return {boolean} 当前浏览器是否支持
   */
  isSupport() {
    const flag = navigator.mediaDevices && navigator.mediaDevices.getUserMedia;
        const flag = navigator.mediaDevices && navigator.mediaDevices.getUserMedia
    if (flag) {
      return true;
            return true
    }
  }
}
src/components/index.js
@@ -5,12 +5,11 @@
        // 匹配当前目录下所有.vue文件(包括子目录)
        const components = import.meta.glob('./global/*.vue', { eager: true })
        for (const [path, module] of Object.entries(components)) {
            // 提取组件名(去除路径和扩展名)
            const name = path.split('/').pop()?.replace('.vue', '') || ''
            // 注册组件
            app.component(name, (module).default)
            app.component(name, module.default)
        }
    }
    },
}
src/config/env.js
@@ -1,2 +1,2 @@
let baseUrl = import.meta.env.VITE_APP_API;
export { baseUrl };
let baseUrl = import.meta.env.VITE_APP_API
export { baseUrl }
src/config/iconList.js
@@ -377,4 +377,4 @@
      'iconfont icon-guanbi',
    ],
  },
];
]
src/config/website.js
@@ -78,4 +78,4 @@
    // 规则设计引擎地址
    edgeUrl: 'http://localhost:1880',
  },
};
}
src/const/tool/model.js
@@ -7,7 +7,7 @@
    label: '',
    value: 1,
  },
];
]
export const entityDic = [
  {
@@ -38,7 +38,7 @@
    label: 'Date',
    value: 'java.util.Date',
  },
];
]
export const componentDic = [
  {
@@ -77,7 +77,7 @@
    label: '日期框',
    value: 'date',
  },
];
]
export const queryDic = [
  {
@@ -120,7 +120,7 @@
    label: '右模糊',
    value: 'likeright',
  },
];
]
export const templateDic = [
  {
@@ -135,7 +135,7 @@
    label: '树表',
    value: 'tree',
  },
];
]
export const option = {
  height: 'auto',
@@ -231,7 +231,7 @@
      span: 24,
    },
  ],
};
}
export const optionModel = {
  border: true,
@@ -341,4 +341,4 @@
      cell: true,
    },
  ],
};
}
src/debug.js
@@ -1,5 +1,5 @@
import DisableDevtool from 'disable-devtool';
import { ElMessageBox } from 'element-plus';
import DisableDevtool from 'disable-devtool'
import { ElMessageBox } from 'element-plus'
/**
 * 安全警告的HTML模板, 使用Tailwind CSS样式
@@ -17,7 +17,7 @@
      如您频繁此类操作,系统将记录上报。
    </p>
  </div>
</div>`;
</div>`
/**
 * Element Plus 消息框配置选项
@@ -29,22 +29,22 @@
  closeOnClickModal: false,
  closeOnPressEscape: false,
  dangerouslyUseHTMLString: true,
};
}
export default () => {
  if (import.meta.env.VITE_APP_DEBUG_SWITCH === 'false') return;
    if (import.meta.env.VITE_APP_DEBUG_SWITCH === 'false') return
  const debugKey = import.meta.env.VITE_APP_DEBUG_KEY;
  let flag = false;
    const debugKey = import.meta.env.VITE_APP_DEBUG_KEY
    let flag = false
  DisableDevtool({
    md5: DisableDevtool.md5(debugKey),
    disableMenu: false,
    ondevtoolopen: (type, next) => {
      if (!flag) ElMessageBox.alert(SECURITY_WARNING_TEMPLATE, '安全警告', ALERT_OPTIONS);
      flag = true;
            if (!flag) ElMessageBox.alert(SECURITY_WARNING_TEMPLATE, '安全警告', ALERT_OPTIONS)
            flag = true
      setTimeout(() => {
        next();
      }, 5000);
                next()
            }, 5000)
    },
  });
};
    })
}
src/directive/drag.js
@@ -1,18 +1,17 @@
const drag = {
  mounted(el, binding) {
    const dragBox = document.querySelector('#' + binding.arg)
    //鼠标点击距离box盒子left的距离
    let spotToBoxLeft = 0
    let spotToBoxTop = 0
    const mouseupFun = (e) => {
        const mouseupFun = e => {
      window.removeEventListener('mousemove', mousemoveFun)
      window.removeEventListener('mouseup', mouseupFun)
    }
    const mousemoveFun = (evt) => {
      console.log(66666);
        const mousemoveFun = evt => {
            console.log(66666)
      //获取body宽高,获取拖动盒子的宽高
      const {offsetWidth: bodyWidth, offsetHeight: bodyHeight} = document.body
      const {offsetWidth: boxWidth, offsetHeight: boxHeight} = dragBox
@@ -23,18 +22,18 @@
      dragBox.style.top = Math.min(top, bodyHeight - boxHeight) + 'px'
    }
    el.__mousedownFun = (evt) => {
        el.__mousedownFun = evt => {
      //鼠标坐标减去 box盒子相对于父盒子body 的距离
      spotToBoxLeft = evt.clientX - dragBox.offsetLeft
      spotToBoxTop = evt.clientY - dragBox.offsetTop
      window.addEventListener('mousemove', mousemoveFun)
      window.addEventListener('mouseup', mouseupFun)
    }
    el.addEventListener('mousedown', el.__mousedownFun);
        el.addEventListener('mousedown', el.__mousedownFun)
  },
  // 绑定元素的父组件卸载前调用
  beforeUnmount(el, binding,) {
    beforeUnmount(el, binding) {
    el.removeEventListener('mousedown', el.__mousedownFun)
  },
}
src/directive/selectLoad.js
@@ -7,7 +7,7 @@
        binding.value()
      }
    })
  }
    },
}
export default selectLoad
src/error.js
@@ -1,4 +1,4 @@
import store from './store';
import store from './store'
export default {
  install: app => {
@@ -8,18 +8,18 @@
        message: err.message,
        stack: err.stack,
        info,
      });
            })
      if (process.env.NODE_ENV === 'development') {
        console.group('>>>>>> 错误信息 >>>>>>');
        console.log(info);
        console.groupEnd();
        console.group('>>>>>> Vue 实例 >>>>>>');
        console.log(vm);
        console.groupEnd();
        console.group('>>>>>> Error >>>>>>');
        console.log(err);
        console.groupEnd();
                console.group('>>>>>> 错误信息 >>>>>>')
                console.log(info)
                console.groupEnd()
                console.group('>>>>>> Vue 实例 >>>>>>')
                console.log(vm)
                console.groupEnd()
                console.group('>>>>>> Error >>>>>>')
                console.log(err)
                console.groupEnd()
      }
    };
        }
  },
};
}
src/lang/en.js
@@ -133,4 +133,4 @@
    closeOthers: 'Close Others',
    closeAll: 'Close All',
  },
};
}
src/lang/index.js
@@ -1,11 +1,11 @@
import { createI18n } from 'vue-i18n';
import Store from '@/store';
import elementEnLocale from 'element-plus/es/locale/lang/en';
import elementZhLocale from 'element-plus/es/locale/lang/zh-cn';
import enLocale from './en';
import zhLocale from './zh';
import AvueEnLocale from '@smallwei/avue/lib/locale/lang/en';
import AvueZhLocale from '@smallwei/avue/lib/locale/lang/zh';
import { createI18n } from 'vue-i18n'
import Store from '@/store'
import elementEnLocale from 'element-plus/es/locale/lang/en'
import elementZhLocale from 'element-plus/es/locale/lang/zh-cn'
import enLocale from './en'
import zhLocale from './zh'
import AvueEnLocale from '@smallwei/avue/lib/locale/lang/en'
import AvueZhLocale from '@smallwei/avue/lib/locale/lang/zh'
export const messages = {
  en: {
@@ -18,9 +18,9 @@
    ...AvueZhLocale,
    ...elementZhLocale,
  },
};
export const language = Store.getters.language;
}
export const language = Store.getters.language
export default createI18n({
  locale: language,
  messages,
});
})
src/lang/zh.js
@@ -133,4 +133,4 @@
    closeOthers: '关闭其它',
    closeAll: '关闭所有',
  },
};
}
src/main.js
src/mixins/crud.js
@@ -1,8 +1,8 @@
import { mapGetters } from 'vuex';
import { mapGetters } from 'vuex'
export default (app, option = {}) => {
  let optionObj = import.meta.glob(`../option/**/**`)[`../option/${option.name}.js`];
  let apiObj = import.meta.glob(`../api/**/**`)[`../api/${option.name}.js`];
    let optionObj = import.meta.glob(`../option/**/**`)[`../option/${option.name}.js`]
    let apiObj = import.meta.glob(`../api/**/**`)[`../api/${option.name}.js`]
  let mixins = {
    data() {
      return {
@@ -13,23 +13,23 @@
        api: {},
        loading: false,
        page: {},
      };
            }
    },
    created() {
      optionObj().then(mode => (this.option = mode.default));
            optionObj().then(mode => (this.option = mode.default))
      apiObj().then(mode => {
        this.api = mode;
        this.getList();
      });
                this.api = mode
                this.getList()
            })
    },
    computed: {
      ...mapGetters(['userInfo', 'permission', 'roles']),
      ids() {
        const ids = [];
                const ids = []
        this.selectionList.forEach(ele => {
          ids.push(ele[this.rowKey]);
        });
        return ids.join(',');
                    ids.push(ele[this.rowKey])
                })
                return ids.join(',')
      },
      bindVal() {
        return {
@@ -37,7 +37,7 @@
          option: this.option,
          data: this.data,
          tableLoading: this.loading,
        };
                }
      },
      onEvent() {
        return {
@@ -49,114 +49,114 @@
          'refresh-change': this.refreshChange,
          'search-reset': this.searchChange,
          'search-change': this.searchChange,
        };
                }
      },
      rowKey() {
        return option.rowKey || 'id';
                return option.rowKey || 'id'
      },
    },
    methods: {
      getList() {
        const callback = () => {
          this.loading = true;
          this.data = [];
                    this.loading = true
                    this.data = []
          this.api[option.list || 'getList'](
            this.page.currentPage,
            this.page.pageSize,
            this.params
          ).then(res => {
            this.loading = false;
            let data;
                        this.loading = false
                        let data
            if (option.res) {
              data = option.res(res.data);
                            data = option.res(res.data)
            } else {
              data = res.data.data;
                            data = res.data.data
            }
            this.page.total = data[option.total || 'total'];
            const result = data[option.data || 'records'];
            this.data = result;
                        this.page.total = data[option.total || 'total']
                        const result = data[option.data || 'records']
                        this.data = result
            if (this.listAfter) {
              this.listAfter(data);
                            this.listAfter(data)
            }
          });
        };
                    })
                }
        if (this.listBefore) {
          this.listBefore();
                    this.listBefore()
        }
        callback();
                callback()
      },
      rowSave(row, done, loading) {
        const callback = () => {
          delete this.form.params;
                    delete this.form.params
          this.api[option.add || 'add'](this.form)
            .then(data => {
              this.getList();
                            this.getList()
              if (this.addAfter) {
                this.addAfter(data);
                                this.addAfter(data)
              } else {
                this.$message.success('新增成功');
                                this.$message.success('新增成功')
              }
              done();
                            done()
            })
            .catch(() => {
              loading();
            });
        };
        if (this.addBefore) {
          this.addBefore();
                            loading()
                        })
        }
        callback();
                if (this.addBefore) {
                    this.addBefore()
                }
                callback()
      },
      rowUpdate(row, index, done, loading) {
        const callback = () => {
          delete this.form.params;
                    delete this.form.params
          this.api[option.update || 'update'](this.form)
            .then(data => {
              this.getList();
                            this.getList()
              if (this.updateAfter) {
                this.updateAfter(data);
                                this.updateAfter(data)
              } else {
                this.$message.success('更新成功');
                                this.$message.success('更新成功')
              }
              done();
                            done()
            })
            .catch(() => {
              loading();
            });
        };
        if (this.updateBefore) {
          this.updateBefore();
                            loading()
                        })
        }
        callback();
                if (this.updateBefore) {
                    this.updateBefore()
                }
                callback()
      },
      rowDel(row, index) {
        const callback = () => {
          this.api[option.del || 'del'](row[this.rowKey], row).then(data => {
            this.getList();
                        this.getList()
            if (this.delAfter) {
              this.delAfter(data, row, index);
                            this.delAfter(data, row, index)
            } else {
              this.$message.success('删除成功');
                            this.$message.success('删除成功')
            }
          });
        };
                    })
                }
        if (this.delBefore) {
          this.delBefore();
          callback();
                    this.delBefore()
                    callback()
        } else {
          this.$confirm('确定将选择数据删除?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            callback();
          });
                        callback()
                    })
        }
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
                    this.$message.warning('请选择至少一条数据')
                    return
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
@@ -164,54 +164,54 @@
          type: 'warning',
        }).then(() => {
          this.api[option.del || 'remove'](this.ids).then(data => {
            this.getList();
                        this.getList()
            if (this.delMultiAfter) {
              this.delMultiAfter(data, this.ids);
                            this.delMultiAfter(data, this.ids)
            } else {
              this.$message.success('删除成功');
                            this.$message.success('删除成功')
            }
          });
        });
                    })
                })
      },
      searchChange(params, done) {
        if (done) done();
        this.params = params;
        this.page.currentPage = 1;
        this.getList();
                if (done) done()
                this.params = params
                this.page.currentPage = 1
                this.getList()
      },
      dateChange(date) {
        if (date) {
          this.params.createTime_dategt = date[0];
          this.params.createTime_datelt = date[1];
                    this.params.createTime_dategt = date[0]
                    this.params.createTime_datelt = date[1]
        } else {
          delete this.params.createTime_dategt;
          delete this.params.createTime_datelt;
                    delete this.params.createTime_dategt
                    delete this.params.createTime_datelt
        }
        this.page.currentPage = 1;
        this.getList();
                this.page.currentPage = 1
                this.getList()
      },
      selectionChange(list) {
        this.selectionList = list;
                this.selectionList = list
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
                this.selectionList = []
                this.$refs.crud.toggleSelection()
      },
      refreshChange() {
        this.getList();
                this.getList()
      },
      sizeChange(val) {
        this.page.currentPage = 1;
        this.page.pageSize = val;
        this.getList();
                this.page.currentPage = 1
                this.page.pageSize = val
                this.getList()
      },
      currentChange(val) {
        this.page.currentPage = val;
        this.getList();
                this.page.currentPage = val
                this.getList()
      },
    },
  };
  app.mixins = app.mixins || [];
  app.mixins.push(mixins);
  return app;
};
    }
    app.mixins = app.mixins || []
    app.mixins.push(mixins)
    return app
}
src/mixins/index.js
@@ -1,5 +1,5 @@
import { validatenull } from '@/utils/validate';
import { getStore } from '@/utils/store.js';
import { validatenull } from '@/utils/validate'
import { getStore } from '@/utils/store.js'
export default {
  data() {
@@ -8,7 +8,7 @@
      refreshLock: false,
      //刷新token的时间
      refreshTime: '',
    };
        }
  },
  created() {
    //实时检测刷新token
@@ -22,24 +22,24 @@
          getStore({
            name: 'token',
            debug: true,
          }) || {};
        let date1 = this.$dayjs(token.datetime);
        let date2 = this.$dayjs();
        const date = date2.diff(date1, 'seconds');
        if (validatenull(date)) return;
                    }) || {}
                let date1 = this.$dayjs(token.datetime)
                let date2 = this.$dayjs()
                const date = date2.diff(date1, 'seconds')
                if (validatenull(date)) return
        if (date >= this.website.tokenTime && !this.refreshLock) {
          this.refreshLock = true;
                    this.refreshLock = true
          this.$store
            .dispatch('RefreshToken')
            .then(() => {
              this.refreshLock = false;
                            this.refreshLock = false
            })
            .catch(err => {
              console.log(err);
              this.refreshLock = false;
            });
                            console.log(err)
                            this.refreshLock = false
                        })
        }
      }, 1000);
            }, 1000)
    },
  },
};
}
src/mockProdServer.js
@@ -1,9 +1,9 @@
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer';
import { createProdMockServer } from 'vite-plugin-mock/es/createProdMockServer'
import menuModule from '../mock/menu';
import userModule from '../mock/user';
import crudModule from '../mock/crud';
import menuModule from '../mock/menu'
import userModule from '../mock/user'
import crudModule from '../mock/crud'
export const setupProdMockServer = () => {
  createProdMockServer([...menuModule, ...userModule, ...crudModule]);
};
    createProdMockServer([...menuModule, ...userModule, ...crudModule])
}
src/option/job/jobinfo.js
@@ -19,7 +19,7 @@
    label: '工作流',
    value: 5,
  },
];
]
export const executeTypeDic = [
  {
@@ -34,7 +34,7 @@
    label: 'MapReduce',
    value: 3,
  },
];
]
export const processorTypeDic = [
  {
@@ -45,7 +45,7 @@
    label: '外部处理器(动态加载)',
    value: 4,
  },
];
]
export const dispatchStrategyDic = [
  {
@@ -56,7 +56,7 @@
    label: 'RANDOM',
    value: 2,
  },
];
]
export const enableDic = [
  {
@@ -67,7 +67,7 @@
    label: '启用',
    value: 1,
  },
];
]
export const logTypeDic = [
  {
@@ -90,7 +90,7 @@
    label: 'NULL',
    value: 999,
  },
];
]
export const logLevelDic = [
  {
@@ -113,7 +113,7 @@
    label: 'OFF',
    value: 99,
  },
];
]
export default {
  height: 'auto',
@@ -512,4 +512,4 @@
      ],
    },
  ],
};
}
src/option/job/jobserver.js
@@ -75,4 +75,4 @@
      span: 24,
    },
  ],
};
}
src/option/system/dict.js
@@ -85,7 +85,7 @@
      hide: true,
    },
  ],
};
}
export const optionChild = {
  height: 'auto',
@@ -207,4 +207,4 @@
      hide: true,
    },
  ],
};
}
src/option/system/dictbiz.js
@@ -86,7 +86,7 @@
      hide: true,
    },
  ],
};
}
export const optionChild = {
  height: 'auto',
@@ -208,4 +208,4 @@
      hide: true,
    },
  ],
};
}
src/option/tool/code.js
@@ -1,4 +1,4 @@
import { templateDic } from '@/const/tool/model';
import { templateDic } from '@/const/tool/model'
export const codeOption = {
  height: 'auto',
@@ -373,7 +373,7 @@
      ],
    },
  ],
};
}
export const genOption = {
  labelWidth: 120,
@@ -662,4 +662,4 @@
      ],
    },
  ],
};
}
src/option/tool/codesetting.js
@@ -226,4 +226,4 @@
      ],
    },
  ],
};
}
src/option/tool/formsetting.js
@@ -92,4 +92,4 @@
      ],
    },
  ],
};
}
src/option/user/info.js
@@ -81,4 +81,4 @@
      ],
    },
  ],
};
}
src/permission.js
@@ -1,32 +1,32 @@
import router from './router/';
import store from './store';
import { getToken } from '@/utils/auth';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style
NProgress.configure({ showSpinner: false });
const lockPage = '/lock'; //锁屏页
import router from './router/'
import store from './store'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false })
const lockPage = '/lock' //锁屏页
router.beforeEach((to, from, next) => {
  const meta = to.meta || {};
  const isMenu = meta.menu === undefined ? to.query.menu : meta.menu;
  store.commit('SET_IS_MENU', isMenu === undefined);
    const meta = to.meta || {}
    const isMenu = meta.menu === undefined ? to.query.menu : meta.menu
    store.commit('SET_IS_MENU', isMenu === undefined)
  if (getToken()) {
    if (store.getters.isLock && to.path !== lockPage) {
      //如果系统激活锁屏,全部跳转到锁屏页
      next({ path: lockPage });
            next({ path: lockPage })
    } else if (to.path === '/login') {
      //如果登录成功访问登录页跳转到主页
      next({ path: '/' });
            next({ path: '/' })
    } else {
      if (store.getters.token.length === 0) {
        store.dispatch('FedLogOut').then(() => {
          next({ path: '/login' });
        });
                    next({ path: '/login' })
                })
      } else {
        const meta = to.meta || {};
        const query = to.query || {};
                const meta = to.meta || {}
                const query = to.query || {}
        if (meta.target) {
          window.open(query.url.replace(/#/g, '&'));
          return;
                    window.open(query.url.replace(/#/g, '&'))
                    return
        } else if (meta.isTab !== false) {
          store.commit('ADD_TAG', {
            name: query.name || to.name,
@@ -35,24 +35,24 @@
            params: to.params,
            query: to.query,
            meta: meta,
          });
                    })
        }
        next();
                next()
      }
    }
  } else {
    //判断是否需要认证,没有登录访问去登录页
    if (meta.isAuth === false) {
      next();
            next()
    } else {
      next('/login');
            next('/login')
    }
  }
});
})
router.afterEach(to => {
  NProgress.done();
  let title = router.$avueRouter.generateTitle(to, { label: 'name' });
  router.$avueRouter.setTitle(title);
  store.commit('SET_IS_SEARCH', false);
});
    NProgress.done()
    let title = router.$avueRouter.generateTitle(to, { label: 'name' })
    router.$avueRouter.setTitle(title)
    store.commit('SET_IS_SEARCH', false)
})
src/router/avue-router.js
@@ -1,53 +1,53 @@
import website from '@/config/website';
import website from '@/config/website'
const modules = import.meta.glob('../**/**/*.vue');
const modules = import.meta.glob('../**/**/*.vue')
function isURL(s) {
  return /^http[s]?:\/\/.*/.test(s);
    return /^http[s]?:\/\/.*/.test(s)
}
let RouterPlugin = function () {
  this.$router = null;
  this.$store = null;
};
    this.$router = null
    this.$store = null
}
RouterPlugin.install = function (option = {}) {
  this.$router = option.router;
  this.$store = option.store;
  let i18n = option.i18n.global;
    this.$router = option.router
    this.$store = option.store
    let i18n = option.i18n.global
  this.$router.$avueRouter = {
    safe: this,
    // 设置标题
    setTitle: title => {
      const defaultTitle = i18n.t('title');
      title = title ? `${title} | ${defaultTitle}` : defaultTitle;
      document.title = title;
            const defaultTitle = i18n.t('title')
            title = title ? `${title} | ${defaultTitle}` : defaultTitle
            document.title = title
    },
    closeTag: value => {
      let tag = value || this.$store.getters.tag;
            let tag = value || this.$store.getters.tag
      if (typeof value === 'string') {
        tag = this.$store.getters.tagList.find(ele => ele.fullPath === value);
                tag = this.$store.getters.tagList.find(ele => ele.fullPath === value)
      }
      this.$store.commit('DEL_TAG', tag);
            this.$store.commit('DEL_TAG', tag)
    },
    generateTitle: (item, props = {}) => {
      let query = item[props.query || 'query'] || {};
      let title = query.name || item[props.label || 'label'];
      let meta = item[props.meta || 'meta'] || {};
      let key = meta.i18n;
            let query = item[props.query || 'query'] || {}
            let title = query.name || item[props.label || 'label']
            let meta = item[props.meta || 'meta'] || {}
            let key = meta.i18n
      if (key) {
        const hasKey = i18n.te('route.' + key);
        if (hasKey) return i18n.t('route.' + key);
                const hasKey = i18n.te('route.' + key)
                if (hasKey) return i18n.t('route.' + key)
      }
      return title ? title.split(',')[0] : title;
            return title ? title.split(',')[0] : title
    },
    //动态路由
    formatRoutes: function (aMenu = [], first) {
      const aRouter = [];
      const propsDefault = website.menu;
            const aRouter = []
            const propsDefault = website.menu
      if (aMenu && aMenu.length === 0) return;
            if (aMenu && aMenu.length === 0) return
      for (let i = 0; i < aMenu.length; i++) {
        const oMenu = aMenu[i];
                const oMenu = aMenu[i]
        let path = oMenu[propsDefault.path],
          isComponent = true,
          component = oMenu.component,
@@ -55,11 +55,11 @@
          icon = oMenu[propsDefault.icon],
          children = oMenu[propsDefault.children],
          query = oMenu[propsDefault.query],
          meta = oMenu[propsDefault.meta];
                    meta = oMenu[propsDefault.meta]
        if (option.keepAlive) {
          meta.keepAlive = option.keepAlive;
                    meta.keepAlive = option.keepAlive
        }
        const isChild = !!(children && children.length !== 0);
                const isChild = !!(children && children.length !== 0)
        const oRouter = {
          path: path,
          component: (() => {
@@ -69,18 +69,18 @@
                option.store.getters.isMacOs || !website.setting.menu
                  ? '../page/index/layout.vue'
                  : '../page/index/index.vue'
              ];
                            ]
              // 判断是否为多层路由
            } else if (isChild && !first) {
              return modules['../page/index/layout.vue'];
                            return modules['../page/index/layout.vue']
              // 判断是否为最终的页面视图
            } else {
              let result = modules[`../${component}.vue`];
              if (result) result().then(mod => (mod.default.name = path));
                            let result = modules[`../${component}.vue`]
                            if (result) result().then(mod => (mod.default.name = path))
              else {
                isComponent = false;
                                isComponent = false
              }
              return result;
                            return result
            }
          })(),
          name,
@@ -88,18 +88,18 @@
          meta,
          query,
          redirect: (() => {
            if (!isChild && first) return `${path}`;
            else return '';
                        if (!isChild && first) return `${path}`
                        else return ''
          })(),
          // 处理是否为一级路由
          children: !isChild
            ? (() => {
                if (first) {
                  oMenu[propsDefault.path] = `${path}`;
                  let result = modules[`../${component}.vue`];
                  if (result) result().then(mod => (mod.default.name = path));
                                    oMenu[propsDefault.path] = `${path}`
                                    let result = modules[`../${component}.vue`]
                                    if (result) result().then(mod => (mod.default.name = path))
                  else {
                    isComponent = false;
                                        isComponent = false
                  }
                  return [
                    {
@@ -110,62 +110,62 @@
                      query: query,
                      path: '',
                    },
                  ];
                                    ]
                }
                return [];
                                return []
              })()
            : (() => {
                return this.formatRoutes(children, false);
                                return this.formatRoutes(children, false)
              })(),
        };
        if (!isURL(path) && isComponent) aRouter.push(oRouter);
                }
                if (!isURL(path) && isComponent) aRouter.push(oRouter)
      }
      if (first) {
        aRouter.forEach(ele => this.safe.$router.addRoute(ele));
                aRouter.forEach(ele => this.safe.$router.addRoute(ele))
      } else {
        return aRouter;
                return aRouter
      }
    },
  };
};
    }
}
export const formatPath = (ele, first) => {
  const propsDefault = website.menu;
  const icon = ele[propsDefault.icon];
  ele[propsDefault.icon] = !icon ? propsDefault.iconDefault : icon;
    const propsDefault = website.menu
    const icon = ele[propsDefault.icon]
    ele[propsDefault.icon] = !icon ? propsDefault.iconDefault : icon
  ele.meta = {
    keepAlive: ele.isOpen === 2,
  };
  const iframeComponent = 'components/iframe/main';
    }
    const iframeComponent = 'components/iframe/main'
  const iframeSrc = href => {
    return href.replace(/&/g, '#');
  };
  const isChild = !!(ele[propsDefault.children] && ele[propsDefault.children].length !== 0);
        return href.replace(/&/g, '#')
    }
    const isChild = !!(ele[propsDefault.children] && ele[propsDefault.children].length !== 0)
  if (!isChild && first) {
    ele.component = 'views' + ele[propsDefault.path];
        ele.component = 'views' + ele[propsDefault.path]
    if (isURL(ele[propsDefault.href])) {
      let href = ele[propsDefault.href];
      ele.component = iframeComponent;
            let href = ele[propsDefault.href]
            ele.component = iframeComponent
      ele[propsDefault.query] = {
        url: iframeSrc(href),
      };
            }
    }
  } else {
    ele[propsDefault.children] &&
      ele[propsDefault.children].forEach(child => {
        child.component = 'views' + child[propsDefault.path];
                child.component = 'views' + child[propsDefault.path]
        child.meta = {
          keepAlive: child.isOpen === 2,
        };
                }
        if (isURL(child[propsDefault.href])) {
          let href = child[propsDefault.href];
          child[propsDefault.path] = ele[propsDefault.path] + '/' + child.code;
          child.component = iframeComponent;
                    let href = child[propsDefault.href]
                    child[propsDefault.path] = ele[propsDefault.path] + '/' + child.code
                    child.component = iframeComponent
          child[propsDefault.query] = {
            url: iframeSrc(href),
          };
        }
        formatPath(child);
      });
  }
};
export default RouterPlugin;
                formatPath(child)
            })
    }
}
export default RouterPlugin
src/router/index.js
@@ -1,34 +1,34 @@
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router';
import PageRouter from './page/';
import ViewsRouter from './views/';
import AvueRouter from './avue-router';
import i18n from '@/lang';
import Store from '@/store/';
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import PageRouter from './page/'
import ViewsRouter from './views/'
import AvueRouter from './avue-router'
import i18n from '@/lang'
import Store from '@/store/'
//创建路由
const Router = createRouter({
  base: import.meta.env.VITE_APP_BASE,
  history: createWebHashHistory(import.meta.env.VITE_APP_BASE),
  routes: [...PageRouter, ...ViewsRouter],
});
})
AvueRouter.install({
  store: Store,
  router: Router,
  i18n: i18n,
});
})
Router.$avueRouter.formatRoutes(Store.getters.menuAll, true);
Router.$avueRouter.formatRoutes(Store.getters.menuAll, true)
export function resetRouter() {
  // 重置路由 比如用于身份验证失败,需要重新登录时 先清空当前的路有权限
  const newRouter = createRouter({
    history: createWebHashHistory(import.meta.env.VITE_APP_BASE),
  });
  Router.matcher = newRouter.matcher; // reset router
    })
    Router.matcher = newRouter.matcher // reset router
  AvueRouter.install(Vue, {
    router: Router,
    store: Store,
    i18n: i18n,
  });
    })
}
export default Router;
export default Router
src/router/page/index.js
@@ -1,11 +1,10 @@
import Store from '@/store/';
import Store from '@/store/'
export default [
  {
    path: '/login',
    name: '登录页',
    component: () =>
      import('@/page/login/index.vue'),
        component: () => import('@/page/login/index.vue'),
    meta: {
      keepAlive: true,
      isTab: false,
@@ -15,8 +14,7 @@
  {
    path: '/oauth/redirect/:source',
    name: '第三方登录',
    component: () =>
      import('@/page/login/index.vue'),
        component: () => import('@/page/login/index.vue'),
    meta: {
      keepAlive: true,
      isTab: false,
@@ -26,8 +24,7 @@
  {
    path: '/lock',
    name: '锁屏页',
    component: () =>
      import('@/page/lock/index.vue'),
        component: () => import('@/page/lock/index.vue'),
    meta: {
      keepAlive: true,
      isTab: false,
@@ -69,4 +66,4 @@
    name: '主页',
    redirect: '/index',
  },
];
]
src/router/views/index.js
@@ -1,6 +1,6 @@
import Index from '@/layout/index.vue';
import Store from '@/store/';
import Layout from '@/page/index/layout.vue';
import Index from '@/layout/index.vue'
import Store from '@/store/'
import Layout from '@/page/index/layout.vue'
export default [
  {
@@ -23,7 +23,10 @@
          i18n: 'dashboard',
          menu: false,
        },
        component: () => import(/* webpackChunkName: "TaskManage" */ '@/views/SignMachineNest/SignMachineNest.vue'),
                component: () =>
                    import(
                        /* webpackChunkName: "TaskManage" */ '@/views/SignMachineNest/SignMachineNest.vue'
                    ),
      },
      {
        path: 'taskManage',
@@ -32,7 +35,8 @@
          i18n: 'dashboard',
          menu: false,
        },
        component: () => import(/* webpackChunkName: "TaskManage" */ '@/views/TaskManage/TaskManage.vue'),
                component: () =>
                    import(/* webpackChunkName: "TaskManage" */ '@/views/TaskManage/TaskManage.vue'),
      },
    ],
  },
@@ -48,4 +52,4 @@
      },
    ],
  },
];
]
src/store/getters.js
@@ -18,9 +18,9 @@
  tagsKeep: (state, getters) => {
    return getters.tagList
      .filter(ele => {
        return (ele.meta || {}).keepAlive;
                return (ele.meta || {}).keepAlive
      })
      .map(ele => ele.fullPath);
            .map(ele => ele.fullPath)
  },
  tagWel: state => state.tags.tagWel,
  token: state => state.user.token,
@@ -34,5 +34,5 @@
  logsFlag: (state, getters) => getters.logsLen === 0,
  flowRoutes: state => state.dict.flowRoutes,
  singleUavHome: state => state.home.singleUavHome,
};
export default getters;
}
export default getters
src/store/index.js
@@ -1,11 +1,11 @@
import { createStore } from 'vuex';
import user from './modules/user';
import common from './modules/common';
import tags from './modules/tags';
import logs from './modules/logs';
import dict from './modules/dict';
import getters from './getters';
import home from '@/store/modules/home';
import { createStore } from 'vuex'
import user from './modules/user'
import common from './modules/common'
import tags from './modules/tags'
import logs from './modules/logs'
import dict from './modules/dict'
import getters from './getters'
import home from '@/store/modules/home'
const store = createStore({
  modules: {
@@ -17,6 +17,6 @@
    home,
  },
  getters,
});
})
export default store;
export default store
src/store/modules/common.js
@@ -1,5 +1,5 @@
import { setStore, getStore, removeStore } from 'utils/store';
import website from '@/config/website';
import { setStore, getStore, removeStore } from 'utils/store'
import website from '@/config/website'
const common = {
  state: {
@@ -25,69 +25,69 @@
  },
  mutations: {
    SET_LANGUAGE: (state, language) => {
      state.language = language;
            state.language = language
      setStore({
        name: 'language',
        content: state.language,
      });
            })
    },
    SET_COLLAPSE: state => {
      state.isCollapse = !state.isCollapse;
            state.isCollapse = !state.isCollapse
    },
    SET_IS_MENU: (state, menu) => {
      state.isMenu = menu;
            state.isMenu = menu
    },
    SET_IS_REFRESH: (state, refresh) => {
      state.isRefresh = refresh;
            state.isRefresh = refresh
    },
    SET_IS_SEARCH: (state, search) => {
      state.isSearch = search;
            state.isSearch = search
    },
    SET_FULLSCREN: state => {
      state.isFullScren = !state.isFullScren;
            state.isFullScren = !state.isFullScren
    },
    SET_LOCK: state => {
      state.isLock = true;
            state.isLock = true
      setStore({
        name: 'isLock',
        content: state.isLock,
        type: 'session',
      });
            })
    },
    SET_COLOR_NAME: (state, colorName) => {
      state.colorName = colorName;
            state.colorName = colorName
      setStore({
        name: 'colorName',
        content: state.colorName,
      });
            })
    },
    SET_THEME_NAME: (state, themeName) => {
      state.themeName = themeName;
            state.themeName = themeName
      setStore({
        name: 'themeName',
        content: state.themeName,
      });
            })
    },
    SET_LOCK_PASSWD: (state, lockPasswd) => {
      state.lockPasswd = lockPasswd;
            state.lockPasswd = lockPasswd
      setStore({
        name: 'lockPasswd',
        content: state.lockPasswd,
        type: 'session',
      });
            })
    },
    CLEAR_LOCK: state => {
      state.isLock = false;
      state.lockPasswd = '';
            state.isLock = false
            state.lockPasswd = ''
      removeStore({
        name: 'lockPasswd',
        type: 'session',
      });
            })
      removeStore({
        name: 'isLock',
        type: 'session',
      });
            })
    },
  },
};
export default common;
}
export default common
src/store/modules/dict.js
@@ -1,6 +1,6 @@
import { getStore, setStore } from '@/utils/store';
import { getStore, setStore } from '@/utils/store'
import { getDictionary } from '@/api/system/dict';
import { getDictionary } from '@/api/system/dict'
const dict = {
  state: {
@@ -11,13 +11,13 @@
      return new Promise((resolve, reject) => {
        getDictionary({ code: 'flow' })
          .then(res => {
            commit('SET_FLOW_ROUTES', res.data.data);
            resolve();
                        commit('SET_FLOW_ROUTES', res.data.data)
                        resolve()
          })
          .catch(error => {
            reject(error);
          });
      });
                        reject(error)
                    })
            })
    },
  },
  mutations: {
@@ -26,11 +26,11 @@
        return {
          routeKey: `${item.code}_${item.dictKey}`,
          routeValue: item.remark,
        };
      });
      setStore({ name: 'flowRoutes', content: state.flowRoutes });
                }
            })
            setStore({ name: 'flowRoutes', content: state.flowRoutes })
    },
  },
};
}
export default dict;
export default dict
src/store/modules/home.js
@@ -1,4 +1,4 @@
import { set } from "lodash";
import { set } from 'lodash'
import { EDeviceTypeName } from '@/utils/staticData/enums'
const home = {
@@ -35,7 +35,7 @@
  actions: {},
  mutations: {
    setSingleUavHome: (state, data) => {
      state.singleUavHome = data;
            state.singleUavHome = data
    },
    setSelectedWorkSpaceId: (state, id) => {
      state.selectedWorkSpaceId = id
@@ -47,7 +47,7 @@
      window.localStorage.setItem('bs_osd', JSON.stringify(info))
    },
    setWsMessage: (state, data) => {
      state.wsMessage = data.host;
            state.wsMessage = data.host
    },
    setDeviceInfo: (state, data) => {
      const info = data.data
@@ -72,8 +72,7 @@
      const dock = state.deviceState.dockInfo[info.sn]
      if (info.host.mode_code !== undefined) {
        dock.basic_osd = info.host
        state.deviceState.drone_charge_state_new =
          dock.basic_osd.drone_charge_state
                state.deviceState.drone_charge_state_new = dock.basic_osd.drone_charge_state
        return
      }
      if (info.host.sdr) {
@@ -88,8 +87,8 @@
  getters:{
    test(state) {
      return state.singleUavHome.id.toString() + '65'
        },
    },
    }
  }
};
export default home;
export default home
src/store/modules/logs.js
@@ -1,6 +1,6 @@
import { setStore, getStore } from 'utils/store';
import dayjs from 'dayjs';
import { sendLogs } from '@/api/user';
import { setStore, getStore } from 'utils/store'
import dayjs from 'dayjs'
import { sendLogs } from '@/api/user'
const logs = {
  state: {
@@ -12,13 +12,13 @@
      return new Promise((resolve, reject) => {
        sendLogs(state.logsList)
          .then(() => {
            commit('CLEAR_LOGS');
            resolve();
                        commit('CLEAR_LOGS')
                        resolve()
          })
          .catch(error => {
            reject(error);
          });
      });
                        reject(error)
                    })
            })
    },
  },
  mutations: {
@@ -36,14 +36,14 @@
            info: info.toString(),
          }
        )
      );
      setStore({ name: 'logsList', content: state.logsList });
            )
            setStore({ name: 'logsList', content: state.logsList })
    },
    CLEAR_LOGS: state => {
      state.logsList = [];
      setStore({ name: 'logsList', content: state.logsList });
            state.logsList = []
            setStore({ name: 'logsList', content: state.logsList })
    },
  },
};
}
export default logs;
export default logs
src/store/modules/tags.js
@@ -1,7 +1,7 @@
import { setStore, getStore } from 'utils/store';
import website from '@/config/website';
import { setStore, getStore } from 'utils/store'
import website from '@/config/website'
const tagWel = website.fistPage;
const tagWel = website.fistPage
const navs = {
  state: {
    tagList: getStore({ name: 'tagList' }) || [],
@@ -10,29 +10,29 @@
  },
  mutations: {
    ADD_TAG: (state, action) => {
      if (typeof action.name == 'function') action.name = action.name(action.query);
      state.tag = action;
      setStore({ name: 'tag', content: state.tag });
      if (state.tagList.some(ele => ele.fullPath == action.fullPath)) return;
      state.tagList.push(action);
      setStore({ name: 'tagList', content: state.tagList });
            if (typeof action.name == 'function') action.name = action.name(action.query)
            state.tag = action
            setStore({ name: 'tag', content: state.tag })
            if (state.tagList.some(ele => ele.fullPath == action.fullPath)) return
            state.tagList.push(action)
            setStore({ name: 'tagList', content: state.tagList })
    },
    DEL_TAG: (state, action) => {
      state.tagList = state.tagList.filter(item => {
        return item.fullPath !== action.fullPath;
      });
      setStore({ name: 'tagList', content: state.tagList });
                return item.fullPath !== action.fullPath
            })
            setStore({ name: 'tagList', content: state.tagList })
    },
    DEL_ALL_TAG: (state, tagList = []) => {
      state.tagList = tagList;
      setStore({ name: 'tagList', content: state.tagList });
            state.tagList = tagList
            setStore({ name: 'tagList', content: state.tagList })
    },
    DEL_TAG_OTHER: state => {
      state.tagList = state.tagList.filter(item => {
        return [state.tag.fullPath, website.fistPage.path].includes(item.fullPath);
      });
      setStore({ name: 'tagList', content: state.tagList });
                return [state.tag.fullPath, website.fistPage.path].includes(item.fullPath)
            })
            setStore({ name: 'tagList', content: state.tagList })
    },
  },
};
export default navs;
}
export default navs
src/store/modules/user.js
@@ -1,14 +1,14 @@
import { ELocalStorageKey } from '@/utils/http/enums';
import { ELocalStorageKey } from '@/utils/http/enums'
import {
  setToken,
  setRefreshToken,
  removeToken,
  removeRefreshToken,
  getRefreshToken,
} from '@/utils/auth';
import { setStore, getStore } from '@/utils/store';
import { validatenull } from '@/utils/validate';
import { deepClone } from '@/utils/util';
} from '@/utils/auth'
import { setStore, getStore } from '@/utils/store'
import { validatenull } from '@/utils/validate'
import { deepClone } from '@/utils/util'
import {
  loginByUsername,
  loginBySocial,
@@ -19,12 +19,12 @@
  refreshToken,
  getButtons,
  registerUser,
} from '@/api/user';
import { getRoutes, getTopMenu } from '@/api/system/menu';
import { formatPath } from '@/router/avue-router';
import { ElMessage } from 'element-plus';
import { encrypt } from '@/utils/sm2';
import md5 from 'js-md5';
} from '@/api/user'
import { getRoutes, getTopMenu } from '@/api/system/menu'
import { formatPath } from '@/router/avue-router'
import { ElMessage } from 'element-plus'
import { encrypt } from '@/utils/sm2'
import md5 from 'js-md5'
const userInfoData = getStore({ name: 'userInfo' }) || {}
const user = {
@@ -56,78 +56,78 @@
          userInfo.code
        )
          .then(res => {
            const data = res.data;
                        const data = res.data
            if (data.error_description) {
              ElMessage({
                message: data.error_description,
                type: 'error',
              });
                            })
            } else {
              commit('SET_TOKEN', data.access_token);
              commit('SET_REFRESH_TOKEN', data.refresh_token);
              commit('SET_TENANT_ID', data.tenant_id);
              commit('SET_USER_INFO', data);
              commit('DEL_ALL_TAG');
              commit('CLEAR_LOCK');
                            commit('SET_TOKEN', data.access_token)
                            commit('SET_REFRESH_TOKEN', data.refresh_token)
                            commit('SET_TENANT_ID', data.tenant_id)
                            commit('SET_USER_INFO', data)
                            commit('DEL_ALL_TAG')
                            commit('CLEAR_LOCK')
            }
            resolve();
                        resolve()
          })
          .catch(err => {
            reject(err);
          });
      });
                        reject(err)
                    })
            })
    },
    //根据第三方信息登录
    LoginBySocial({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginBySocial(userInfo.tenantId, userInfo.source, userInfo.code, userInfo.state)
          .then(res => {
            const data = res.data;
                        const data = res.data
            if (data.error_description) {
              ElMessage({
                message: data.error_description,
                type: 'error',
              });
                            })
            } else {
              commit('SET_TOKEN', data.access_token);
              commit('SET_REFRESH_TOKEN', data.refresh_token);
              commit('SET_USER_INFO', data);
              commit('SET_TENANT_ID', data.tenant_id);
              commit('DEL_ALL_TAG');
              commit('CLEAR_LOCK');
                            commit('SET_TOKEN', data.access_token)
                            commit('SET_REFRESH_TOKEN', data.refresh_token)
                            commit('SET_USER_INFO', data)
                            commit('SET_TENANT_ID', data.tenant_id)
                            commit('DEL_ALL_TAG')
                            commit('CLEAR_LOCK')
            }
            resolve();
                        resolve()
          })
          .catch(err => {
            reject(err);
          });
      });
                        reject(err)
                    })
            })
    },
    //根据单点信息登录
    LoginBySso({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        loginBySso(userInfo.state, userInfo.code)
          .then(res => {
            const data = res.data;
                        const data = res.data
            if (data.error_description) {
              ElMessage({
                message: data.error_description,
                type: 'error',
              });
                            })
            } else {
              commit('SET_TOKEN', data.access_token);
              commit('SET_REFRESH_TOKEN', data.refresh_token);
              commit('SET_USER_INFO', data);
              commit('SET_TENANT_ID', data.tenant_id);
              commit('DEL_ALL_TAG');
              commit('CLEAR_LOCK');
                            commit('SET_TOKEN', data.access_token)
                            commit('SET_REFRESH_TOKEN', data.refresh_token)
                            commit('SET_USER_INFO', data)
                            commit('SET_TENANT_ID', data.tenant_id)
                            commit('DEL_ALL_TAG')
                            commit('CLEAR_LOCK')
            }
            resolve();
                        resolve()
          })
          .catch(err => {
            reject(err);
          });
      });
                        reject(err)
                    })
            })
    },
    //根据手机信息登录
    LoginByPhone({ commit }, userInfo) {
@@ -139,26 +139,26 @@
          userInfo.codeValue
        )
          .then(res => {
            const data = res.data;
                        const data = res.data
            if (data.error_description) {
              ElMessage({
                message: data.error_description,
                type: 'error',
              });
                            })
            } else {
              commit('SET_TOKEN', data.access_token);
              commit('SET_REFRESH_TOKEN', data.refresh_token);
              commit('SET_USER_INFO', data);
              commit('SET_TENANT_ID', data.tenant_id);
              commit('DEL_ALL_TAG');
              commit('CLEAR_LOCK');
                            commit('SET_TOKEN', data.access_token)
                            commit('SET_REFRESH_TOKEN', data.refresh_token)
                            commit('SET_USER_INFO', data)
                            commit('SET_TENANT_ID', data.tenant_id)
                            commit('DEL_ALL_TAG')
                            commit('CLEAR_LOCK')
            }
            resolve();
                        resolve()
          })
          .catch(err => {
            reject(err);
          });
      });
                        reject(err)
                    })
            })
    },
    //用户注册
    RegisterUser({ commit }, userInfo = {}) {
@@ -171,37 +171,37 @@
          userInfo.phone,
          userInfo.email
        ).then(res => {
          const data = res.data;
                    const data = res.data
          if (data.error_description) {
            ElMessage({
              message: data.error_description,
              type: 'error',
            });
            reject(data.error_description);
                        })
                        reject(data.error_description)
          } else {
            commit('SET_TOKEN', data.access_token);
            commit('SET_REFRESH_TOKEN', data.refresh_token);
            commit('SET_USER_INFO', data);
            commit('SET_TENANT_ID', data.tenant_id);
            commit('DEL_ALL_TAG');
            commit('CLEAR_LOCK');
                        commit('SET_TOKEN', data.access_token)
                        commit('SET_REFRESH_TOKEN', data.refresh_token)
                        commit('SET_USER_INFO', data)
                        commit('SET_TENANT_ID', data.tenant_id)
                        commit('DEL_ALL_TAG')
                        commit('CLEAR_LOCK')
          }
          resolve();
        });
      });
                    resolve()
                })
            })
    },
    GetUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo()
          .then(res => {
            const data = res.data.data;
            commit('SET_ROLES', data.roles);
            resolve(data);
                        const data = res.data.data
                        commit('SET_ROLES', data.roles)
                        resolve(data)
          })
          .catch(err => {
            reject(err);
          });
      });
                        reject(err)
                    })
            })
    },
    //刷新token
    RefreshToken({ state, commit }, userInfo) {
@@ -213,82 +213,82 @@
          !validatenull(userInfo) ? userInfo.roleId : state.userInfo.role_id
        )
          .then(res => {
            const data = res.data;
            commit('SET_TOKEN', data.access_token);
            commit('SET_REFRESH_TOKEN', data.refresh_token);
            commit('SET_USER_INFO', data);
            resolve();
                        const data = res.data
                        commit('SET_TOKEN', data.access_token)
                        commit('SET_REFRESH_TOKEN', data.refresh_token)
                        commit('SET_USER_INFO', data)
                        resolve()
          })
          .catch(error => {
            reject(error);
          });
      });
                        reject(error)
                    })
            })
    },
    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        logout()
          .then(() => {
            commit('SET_TOKEN', '');
            commit('SET_MENU_ALL_NULL', []);
            commit('SET_MENU', []);
            commit('SET_ROLES', []);
            commit('DEL_ALL_TAG', []);
            commit('CLEAR_LOCK');
            removeToken();
            removeRefreshToken();
            removeToken();
            resolve();
                        commit('SET_TOKEN', '')
                        commit('SET_MENU_ALL_NULL', [])
                        commit('SET_MENU', [])
                        commit('SET_ROLES', [])
                        commit('DEL_ALL_TAG', [])
                        commit('CLEAR_LOCK')
                        removeToken()
                        removeRefreshToken()
                        removeToken()
                        resolve()
          })
          .catch(error => {
            reject(error);
          });
      });
                        reject(error)
                    })
            })
    },
    //注销session
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '');
        commit('SET_MENU_ALL_NULL', []);
        commit('SET_MENU', []);
        commit('SET_ROLES', []);
        commit('DEL_ALL_TAG', []);
        commit('CLEAR_LOCK');
        removeToken();
        removeRefreshToken();
        removeToken();
        resolve();
      });
                commit('SET_TOKEN', '')
                commit('SET_MENU_ALL_NULL', [])
                commit('SET_MENU', [])
                commit('SET_ROLES', [])
                commit('DEL_ALL_TAG', [])
                commit('CLEAR_LOCK')
                removeToken()
                removeRefreshToken()
                removeToken()
                resolve()
            })
    },
    GetTopMenu() {
      return new Promise(resolve => {
        getTopMenu().then(res => {
          const data = res.data.data || [];
          resolve(data);
        });
      });
                    const data = res.data.data || []
                    resolve(data)
                })
            })
    },
    GetMenu({ commit, dispatch }, tenantId) {
      return new Promise(resolve => {
        getRoutes(tenantId).then(res => {
          const data = res.data.data;
          let menu = deepClone(data);
          menu.forEach(ele => formatPath(ele, true));
          commit('SET_MENU', menu);
          commit('SET_MENU_ALL', menu);
          dispatch('GetButtons');
          resolve(menu);
        });
      });
                    const data = res.data.data
                    let menu = deepClone(data)
                    menu.forEach(ele => formatPath(ele, true))
                    commit('SET_MENU', menu)
                    commit('SET_MENU_ALL', menu)
                    dispatch('GetButtons')
                    resolve(menu)
                })
            })
    },
    GetButtons({ commit }) {
      return new Promise(resolve => {
        getButtons().then(res => {
          const data = res.data.data;
          commit('SET_PERMISSION', data);
          resolve();
        });
      });
                    const data = res.data.data
                    commit('SET_PERMISSION', data)
                    resolve()
                })
            })
    },
  },
  mutations: {
@@ -296,106 +296,106 @@
      state.selectedAreaCode = code
    },
    SET_TOKEN: (state, token) => {
      setToken(token);
      state.token = token;
      setStore({ name: 'token', content: state.token });
            setToken(token)
            state.token = token
            setStore({ name: 'token', content: state.token })
      console.log('顶顶顶111',token)
      window.localStorage.setItem(ELocalStorageKey.Token, token);
            window.localStorage.setItem(ELocalStorageKey.Token, token)
    },
    SET_REFRESH_TOKEN: (state, refreshToken) => {
      setRefreshToken(refreshToken);
      state.refreshToken = refreshToken;
      setStore({ name: 'refreshToken', content: state.refreshToken });
            setRefreshToken(refreshToken)
            state.refreshToken = refreshToken
            setStore({ name: 'refreshToken', content: state.refreshToken })
    },
    SET_MENU_ID(state, menuId) {
      state.menuId = menuId;
            state.menuId = menuId
    },
    SET_TENANT_ID: (state, tenantId) => {
      state.tenantId = tenantId;
      setStore({ name: 'tenantId', content: state.tenantId });
            state.tenantId = tenantId
            setStore({ name: 'tenantId', content: state.tenantId })
    },
    SET_USER_INFO: (state, userInfo) => {
      if (validatenull(userInfo.user_id) && validatenull(userInfo.account)) {
        state.userInfo = { user_name: 'unauth', role_name: 'unauth', authority: 'unauth' };
                state.userInfo = { user_name: 'unauth', role_name: 'unauth', authority: 'unauth' }
      } else {
        if (validatenull(userInfo.avatar)) {
          userInfo.avatar = '/img/bg/img-logo.png';
                    userInfo.avatar = '/img/bg/img-logo.png'
        }
        if (!validatenull(userInfo.role_name)) {
          userInfo.roleName = userInfo.role_name;
          userInfo.authority = userInfo.role_name;
                    userInfo.roleName = userInfo.role_name
                    userInfo.authority = userInfo.role_name
        }
        if (!validatenull(userInfo.user_id)) {
          userInfo.userId = userInfo.user_id;
                    userInfo.userId = userInfo.user_id
        }
        if (!validatenull(userInfo.user_name)) {
          userInfo.userName = userInfo.user_name;
                    userInfo.userName = userInfo.user_name
        }
        if (!validatenull(userInfo.tenant_id)) {
          userInfo.tenantId = userInfo.tenant_id;
                    userInfo.tenantId = userInfo.tenant_id
        }
        if (!validatenull(userInfo.dept_id)) {
          userInfo.deptId = userInfo.dept_id;
                    userInfo.deptId = userInfo.dept_id
        }
        if (!validatenull(userInfo.role_id)) {
          userInfo.roleId = userInfo.role_id;
                    userInfo.roleId = userInfo.role_id
        }
        if (!validatenull(userInfo.oauth_id)) {
          userInfo.oauthId = userInfo.oauth_id;
                    userInfo.oauthId = userInfo.oauth_id
        }
        userInfo.selectedAreaCode = userInfo?.detail?.areaCode || '';
        state.userInfo = userInfo;
                userInfo.selectedAreaCode = userInfo?.detail?.areaCode || ''
                state.userInfo = userInfo
      }
      setStore({ name: 'userInfo', content: state.userInfo });
            setStore({ name: 'userInfo', content: state.userInfo })
    },
    SET_MENU_ALL: (state, menuAll) => {
      let menu = state.menuAll;
            let menu = state.menuAll
      menuAll.forEach(ele => {
        let index = menu.findIndex(item => item.path === ele.path);
                let index = menu.findIndex(item => item.path === ele.path)
        if (index === -1) {
          menu.push(ele);
                    menu.push(ele)
        } else {
          menu[index] = ele;
                    menu[index] = ele
        }
      });
      state.menuAll = menu;
      setStore({ name: 'menuAll', content: state.menuAll });
            })
            state.menuAll = menu
            setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENU_ALL_NULL: state => {
      state.menuAll = [];
      setStore({ name: 'menuAll', content: state.menuAll });
            state.menuAll = []
            setStore({ name: 'menuAll', content: state.menuAll })
    },
    SET_MENU: (state, menu) => {
      state.menu = menu;
      setStore({ name: 'menu', content: state.menu });
            state.menu = menu
            setStore({ name: 'menu', content: state.menu })
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
            state.roles = roles
    },
    SET_PERMISSION: (state, permission) => {
      let result = [];
            let result = []
      function getCode(list) {
        list.forEach(ele => {
          if (typeof ele === 'object') {
            const children = ele.children;
            const code = ele.code;
                        const children = ele.children
                        const code = ele.code
            if (children && children.length > 0) {
              getCode(children);
                            getCode(children)
            } else {
              result.push(code);
                            result.push(code)
            }
          }
        });
                })
      }
      getCode(permission);
      state.permission = {};
            getCode(permission)
            state.permission = {}
      result.forEach(ele => {
        state.permission[ele] = true;
      });
      setStore({ name: 'permission', content: state.permission, type: 'session' });
                state.permission[ele] = true
            })
            setStore({ name: 'permission', content: state.permission, type: 'session' })
    },
  },
};
export default user;
}
export default user
src/utils/auth.js
@@ -1,32 +1,32 @@
import Cookies from 'js-cookie';
import Cookies from 'js-cookie'
const TokenKey = 'saber3-access-token';
const RefreshTokenKey = 'saber3-refresh-token';
const SessionId = 'JSESSIONID';
const UserId = 'b-user-id';
const TokenKey = 'saber3-access-token'
const RefreshTokenKey = 'saber3-refresh-token'
const SessionId = 'JSESSIONID'
const UserId = 'b-user-id'
export function getToken() {
  return Cookies.get(TokenKey);
    return Cookies.get(TokenKey)
}
export function setToken(token) {
  return Cookies.set(TokenKey, token);
    return Cookies.set(TokenKey, token)
}
export function getRefreshToken() {
  return Cookies.get(RefreshTokenKey);
    return Cookies.get(RefreshTokenKey)
}
export function setRefreshToken(token) {
  return Cookies.set(RefreshTokenKey, token);
    return Cookies.set(RefreshTokenKey, token)
}
export function removeToken() {
  Cookies.remove(SessionId);
  Cookies.remove(UserId);
  return Cookies.remove(TokenKey);
    Cookies.remove(SessionId)
    Cookies.remove(UserId)
    return Cookies.remove(TokenKey)
}
export function removeRefreshToken() {
  return Cookies.remove(RefreshTokenKey);
    return Cookies.remove(RefreshTokenKey)
}
src/utils/cesium-tsa.js
@@ -1,48 +1,46 @@
import * as Cesium from 'cesium';
import AmapMercatorTilingScheme from './cesium/AmapMercatorTilingScheme/index';
import store from '@/store';
import { Terrain } from 'cesium';
import * as Cesium from 'cesium'
import AmapMercatorTilingScheme from './cesium/AmapMercatorTilingScheme/index'
import store from '@/store'
import { Terrain } from 'cesium'
// vite env
const { VITE_APP_BASE } = import.meta.env;
const { VITE_APP_BASE } = import.meta.env
window.CESIUM_BASE_URL = `${VITE_APP_BASE}cesiumPu`;
window.CESIUM_BASE_URL = `${VITE_APP_BASE}cesiumPu`
// 定义全局的viewer变量防止重复生成
let viewer = null;
let globalBaseMapLayers = [];
let viewer = null
let globalBaseMapLayers = []
window.globalCesium = Cesium;
window.$viewer = null;
window.globalCesium = Cesium
window.$viewer = null
let customEntityDataSources = {};
let customEntityDataSources = {}
let customMapLayer = {};
let customMapLayer = {}
let handlerEvents = {
  handler: null,
};
}
export default function cesiumOperation() {
  const TDT_Token = 'c6eea7dad4fa1e2d1e32ec0e7c9735db';
    const TDT_Token = 'c6eea7dad4fa1e2d1e32ec0e7c9735db'
  // 天地图地图
  const TDT_IMG_C =
    'https://{s}.tianditu.gov.cn/img_c/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=' +
    TDT_Token;
        TDT_Token
  // 天地图注记
  const TDT_ZJ =
    'https://{s}.tianditu.gov.cn/cia_c/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=cia&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=' +
    TDT_Token;
        TDT_Token
  // 标准地图注记
  const TID_STAND =
    'https://{s}.tianditu.gov.cn/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0' +
    '&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}' +
    '&style=default&format=tiles&tk=' +
    TDT_Token;
        TDT_Token
  // 天地图图层变量
  const imageryProvider_tdt = new Cesium.WebMapTileServiceImageryProvider({
    url: TDT_IMG_C,
@@ -74,7 +72,7 @@
      '19',
    ],
    maximumLevel: 17,
  });
    })
  // 标准地图图层变量
  const imageryProvider_stand = new Cesium.UrlTemplateImageryProvider({
    url: 'https://t{s}.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=e45274b0235bb913eceb393aabbf9c9c',
@@ -83,14 +81,14 @@
    // show: true,
    maximumLevel: 18,
    credit: 'stand_tc',
  });
    })
  // 标准地图图层注解
  const imageryProvider_standZh = new Cesium.UrlTemplateImageryProvider({
    url: 'https://t{s}.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=e45274b0235bb913eceb393aabbf9c9c',
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    maximumLevel: 18,
    credit: 'stand_zj',
  });
    })
  // 天地图中文注记加载
  const annotation = new Cesium.WebMapTileServiceImageryProvider({
    url: TDT_ZJ,
@@ -122,7 +120,7 @@
      '19',
    ],
    maximumLevel: 50,
  });
    })
  // 高德地图图层变量
  //高德矢量地图数据图层,自带注记
@@ -136,7 +134,7 @@
    maximumLevel: 18,
    tilingScheme: new AmapMercatorTilingScheme(),
    credit: 'amap_SL',
  });
    })
  //高德影像地图数据图层,自带注记
  const imageryProvider_ammap = new Cesium.UrlTemplateImageryProvider({
@@ -149,23 +147,23 @@
    maximumLevel: 18,
    tilingScheme: new AmapMercatorTilingScheme(),
    credit: 'amap_stand',
  });
    })
  // 高德影像地图数据图层,注记
  const imageryProvider_ammapBz = new Cesium.UrlTemplateImageryProvider({
    url: 'https://webst02.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scale=1&style=8',
    tilingScheme: new AmapMercatorTilingScheme(),
    minimumLevel: 3,
  });
    })
  Cesium.Ion.defaultAccessToken =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMzg4MDk5YS05MWEzLTQ3NTYtOTYzNS04Yzk4MjU2MjI5N2YiLCJpZCI6MjE3OTM4LCJpYXQiOjE3MTY3NzIzOTR9.q1rzR7SRtIulQKTtJuv5HPUbp1av5E9RaOe-6voPDGc';
        'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkMzg4MDk5YS05MWEzLTQ3NTYtOTYzNS04Yzk4MjU2MjI5N2YiLCJpZCI6MjE3OTM4LCJpYXQiOjE3MTY3NzIzOTR9.q1rzR7SRtIulQKTtJuv5HPUbp1av5E9RaOe-6voPDGc'
  const _init = async id => {
    const cesiumToken =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkYTZlNGNlYS01NTU1LTQ1MGEtYmNlZS0yNTE2NDk5YWM2MjEiLCJpZCI6MTc5Njk2LCJpYXQiOjE3MDA1NDcwMjV9.qcl4AH2731cfFd0-I1ZLUINPXqvglLkDFD-UGR2zU5M';
    Cesium.Ion.defaultAccessToken = cesiumToken;
    Cesium.Camera.DEFAULT_VIEW_FACTOR = -0.45;
            'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkYTZlNGNlYS01NTU1LTQ1MGEtYmNlZS0yNTE2NDk5YWM2MjEiLCJpZCI6MTc5Njk2LCJpYXQiOjE3MDA1NDcwMjV9.qcl4AH2731cfFd0-I1ZLUINPXqvglLkDFD-UGR2zU5M'
        Cesium.Ion.defaultAccessToken = cesiumToken
        Cesium.Camera.DEFAULT_VIEW_FACTOR = -0.45
    // 西南东北,默认显示中国
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(66, 4, 135, 53.55);
        Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(66, 4, 135, 53.55)
    viewer = new Cesium.Viewer(id, {
      terrain: Terrain.fromWorldTerrain(),
      infoBox: false, // 禁用沙箱,解决控制台报错
@@ -179,19 +177,19 @@
      selectionIndicator: false, // 是否显示选择指示器
      baseLayer: false,
      fullscreenButton: false,
    });
        })
    // viewer.scene.globe.depthTestAgainstTerrain = true;
    viewer.imageryLayers.removeAll();
        viewer.imageryLayers.removeAll()
    globalBaseMapLayers = [];
        globalBaseMapLayers = []
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
      Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    ); // 禁用双击
    viewer.scene.screenSpaceCameraController.minimumZoomDistance = 100;
    viewer.scene.screenSpaceCameraController.maximumZoomDistance = 4500000;
        ) // 禁用双击
        viewer.scene.screenSpaceCameraController.minimumZoomDistance = 100
        viewer.scene.screenSpaceCameraController.maximumZoomDistance = 4500000
    // viewer.scene.camera.setView({
    //   destination: Cesium.Cartesian3.fromDegrees(115.856725497,28.624514734, 8000)
    // });
@@ -207,18 +205,17 @@
    //   requestVertexNormals: true,
    // })
    window.$viewer = viewer;
    loadLAYER();
  };
        window.$viewer = viewer
        loadLAYER()
    }
  const loadLAYER = () => {
    let mapLayers = [];
        let mapLayers = []
    globalBaseMapLayers.length &&
      globalBaseMapLayers.forEach(item => {
        if (item.mapLayer) item.mapLayer.show = false;
      });
                if (item.mapLayer) item.mapLayer.show = false
            })
    // 高德影像地图数据图层
    if (store.state.common.mapSetting.mode === 3) {
@@ -227,14 +224,14 @@
          { key: 'imageryProvider_ammap', layer: imageryProvider_ammap },
          { key: 'imageryProvider_ammapBz', layer: imageryProvider_ammapBz },
        ]
      );
            )
    }
    // 高德地图矢量图层加载
    if (store.state.common.mapSetting.mode === 2) {
      mapLayers.push({
        key: 'imageryProvider_ammapSL',
        layer: imageryProvider_ammapSL,
      });
            })
    }
    // 标准地图加载
@@ -244,7 +241,7 @@
          { key: 'imageryProvider_standZh', layer: imageryProvider_standZh },
          { key: 'imageryProvider_stand', layer: imageryProvider_stand },
        ]
      );
            )
    }
    // 路线图加载
@@ -252,7 +249,7 @@
      store.state.common.mapSetting.roadLine === true &&
      store.state.common.mapSetting.mode === 1
    ) {
      mapLayers.push({ key: 'annotation', layer: annotation });
            mapLayers.push({ key: 'annotation', layer: annotation })
    }
    // 天地图图层加载
@@ -260,40 +257,40 @@
      mapLayers.push({
        key: 'imageryProvider_tdt',
        layer: imageryProvider_tdt,
      });
            })
    }
    // 创建一个Set来快速查找array2中的id
    let keyBaseMap = new Set(globalBaseMapLayers.map(item => item.key));
    let keyMapLayers = new Set(mapLayers.map(item => item.key));
        let keyBaseMap = new Set(globalBaseMapLayers.map(item => item.key))
        let keyMapLayers = new Set(mapLayers.map(item => item.key))
    let keyExistBaseMap = mapLayers.filter(item => !keyBaseMap.has(item.key));
        let keyExistBaseMap = mapLayers.filter(item => !keyBaseMap.has(item.key))
    let keyNoExistBaseMap = globalBaseMapLayers.filter(item => keyMapLayers.has(item.key));
        let keyNoExistBaseMap = globalBaseMapLayers.filter(item => keyMapLayers.has(item.key))
    keyExistBaseMap.length &&
      keyExistBaseMap.forEach(item => {
        let curLayer = {
          key: item.key,
          mapLayer: viewer?.imageryLayers.addImageryProvider(item.layer),
        };
                }
        if (curLayer.mapLayer) curLayer.mapLayer.show = true;
                if (curLayer.mapLayer) curLayer.mapLayer.show = true
        viewer?.imageryLayers.lowerToBottom(curLayer.mapLayer);
                viewer?.imageryLayers.lowerToBottom(curLayer.mapLayer)
        globalBaseMapLayers.push(curLayer);
      });
                globalBaseMapLayers.push(curLayer)
            })
    keyNoExistBaseMap.length &&
      keyNoExistBaseMap.forEach(item => {
        if (item.mapLayer) item.mapLayer.show = true;
                if (item.mapLayer) item.mapLayer.show = true
        viewer?.imageryLayers.lowerToBottom(item.mapLayer);
      });
                viewer?.imageryLayers.lowerToBottom(item.mapLayer)
            })
    // 2D/3D切换
    switchModel(store.state.common.mapSetting.visual);
  };
        switchModel(store.state.common.mapSetting.visual)
    }
  const addCustomLayers = (layerName, options) => {
    if (options.type == 'arcgis') {
@@ -326,9 +323,9 @@
          '18',
          '19',
        ],
      });
            })
      customMapLayer[layerName] = viewer?.imageryLayers.addImageryProvider(imageryProvider);
            customMapLayer[layerName] = viewer?.imageryLayers.addImageryProvider(imageryProvider)
      // const layerProvider = new Cesium.ArcGisMapServerImageryProvider({
      //   url: options.src,
@@ -336,86 +333,84 @@
      // })
      // customMapLayer[layerName] = viewer?.imageryLayers.addImageryProvider(layerProvider)
    }
  };
    }
  const removeCustomLayers = (layerName = '') => {
    if (layerName) {
      if (customMapLayer[layerName]) {
        viewer?.imageryLayers.remove(customMapLayer[layerName]);
                viewer?.imageryLayers.remove(customMapLayer[layerName])
        delete customMapLayer[layerName];
                delete customMapLayer[layerName]
      }
    } else {
      for (let k in customMapLayer) {
        viewer?.imageryLayers.remove(customMapLayer[k]);
                viewer?.imageryLayers.remove(customMapLayer[k])
      }
      customMapLayer = {};
            customMapLayer = {}
    }
  };
    }
  // 切换不同背景图层
  const patternMap = () => {
    const imageryLayers = viewer?.scene.imageryLayers;
        const imageryLayers = viewer?.scene.imageryLayers
    // 切换为标准图层
    if (store.state.common.mapSetting.mode === 0) {
      const tdtImg_c = imageryLayers?._layers.find(v => v.imageryProvider._layer === 'tdtImg_c');
      const tdtZwImg_c = imageryLayers?._layers.find(
        v => v.imageryProvider._layer === 'tdtZwImg_c'
      );
      viewer?.imageryLayers.remove(tdtImg_c);
      viewer?.imageryLayers.remove(tdtZwImg_c);
            const tdtImg_c = imageryLayers?._layers.find(v => v.imageryProvider._layer === 'tdtImg_c')
            const tdtZwImg_c = imageryLayers?._layers.find(v => v.imageryProvider._layer === 'tdtZwImg_c')
            viewer?.imageryLayers.remove(tdtImg_c)
            viewer?.imageryLayers.remove(tdtZwImg_c)
    } else {
      const tdtStand_c = imageryLayers?._layers.find(
        v => v.imageryProvider.credit?.html === 'stand_tc'
      );
            )
      const tdtStand_zj = imageryLayers?._layers.find(
        v => v.imageryProvider.credit?.html === 'stand_zj'
      );
      viewer?.imageryLayers.remove(tdtStand_c);
      viewer?.imageryLayers.remove(tdtStand_zj);
            )
            viewer?.imageryLayers.remove(tdtStand_c)
            viewer?.imageryLayers.remove(tdtStand_zj)
    }
    loadLAYER();
  };
        loadLAYER()
    }
  // 生成或删除路网图层
  const roadPattern = flag => {
    if (store.state.common.mapSetting.mode === 0) return;
    const imageryLayers = viewer?.scene.imageryLayers;
    const tdtZwImg_c = imageryLayers?._layers.find(v => v.imageryProvider._layer === 'tdtZwImg_c');
        if (store.state.common.mapSetting.mode === 0) return
        const imageryLayers = viewer?.scene.imageryLayers
        const tdtZwImg_c = imageryLayers?._layers.find(v => v.imageryProvider._layer === 'tdtZwImg_c')
    if (!flag) {
      viewer?.imageryLayers.remove(tdtZwImg_c);
            viewer?.imageryLayers.remove(tdtZwImg_c)
    } else {
      viewer?.imageryLayers.addImageryProvider(annotation);
            viewer?.imageryLayers.addImageryProvider(annotation)
    }
  };
    }
  // 二维三维切换
  // 切换为二三维模式
  const switchModel = type => {
    switch (type) {
      case '2D':
        viewer?.scene.morphTo2D(0);
                viewer?.scene.morphTo2D(0)
        // viewer?.scene.camera.setView({
        //   orientation: {
        //     pitch: Cesium.Math.toRadians(-60),
        //     heading: Cesium.Math.toRadians(0),
        //   },
        // });
        break;
                break
      case '3D':
        viewer?.scene.morphTo3D(0);
                viewer?.scene.morphTo3D(0)
        // viewer?.scene.camera.setView({
        //   orientation: {
        //     pitch: Cesium.Math.toRadians(-90),
        //     heading: Cesium.Math.toRadians(0),
        //   },
        // });
        break;
                break
      default:
        break;
                break
    }
  };
    }
  /**
   * @description: 地图暗黑模式切换
@@ -430,302 +425,302 @@
      gamma: 1,
      hue: 0,
      saturation: 1,
    };
        }
    !isDark && Object.assign(options, defaultOptions);
        !isDark && Object.assign(options, defaultOptions)
    const baseLayer = viewer.imageryLayers.get(0);
    baseLayer.brightness = options.brightness || 0;
    baseLayer.contrast = options.contrast || 0;
    baseLayer.gamma = options.gamma || 2;
    baseLayer.hue = options.hue || 0;
    baseLayer.saturation = options.saturation || 0;
        const baseLayer = viewer.imageryLayers.get(0)
        baseLayer.brightness = options.brightness || 0
        baseLayer.contrast = options.contrast || 0
        baseLayer.gamma = options.gamma || 2
        baseLayer.hue = options.hue || 0
        baseLayer.saturation = options.saturation || 0
    const baseFragShader = viewer.scene.globe._surfaceShaderSet.baseFragmentShaderSource.sources;
        const baseFragShader = viewer.scene.globe._surfaceShaderSet.baseFragmentShaderSource.sources
    for (let i = 0; i < baseFragShader.length; i++) {
      const strS = 'color = czm_saturation(color, textureSaturation);\n#endif\n';
      let strT = 'color = czm_saturation(color, textureSaturation);\n#endif\n';
            const strS = 'color = czm_saturation(color, textureSaturation);\n#endif\n'
            let strT = 'color = czm_saturation(color, textureSaturation);\n#endif\n'
      if (options.invertColor) {
        strT += `
        color.r = 1.0 - color.r;
        color.g = 1.0 - color.g;
        color.b = 1.0 - color.b;
        `;
        `
      }
      if (options.filterRGB.length > 0) {
        strT += `
        color.r = color.r * ${options.filterRGB[0]}.0/255.0;
        color.g = color.g * ${options.filterRGB[1]}.0/255.0;
        color.b = color.b * ${options.filterRGB[2]}.0/255.0;
        `;
        `
      }
      if (!isDark) {
        //恢复默认
        baseFragShader[i] = baseFragShader[i].replace(strT, strS);
                baseFragShader[i] = baseFragShader[i].replace(strT, strS)
      } else {
        // 替换为暗黑模式
        baseFragShader[i] = baseFragShader[i].replace(strS, strT);
                baseFragShader[i] = baseFragShader[i].replace(strS, strT)
      }
    }
  };
    }
  const switchDarkModel = () => {
    const isDark = store.state.common.mapSetting.isDark;
        const isDark = store.state.common.mapSetting.isDark
    darkMap(viewer, isDark, {
      //反色
      invertColor: true,
      //滤色值  [176, 224, 230]
      filterRGB: [60, 145, 172],
    });
  };
        })
    }
  //移除DataSource中所有实体
  const removeAllDataSource = () => {
    viewer?.dataSources.removeAll();
  };
        viewer?.dataSources.removeAll()
    }
  // 清除所有标记点
  const removeAllPoint = () => {
    if (viewer) {
      viewer?.entities?.removeAll();
            viewer?.entities?.removeAll()
      // viewer?.scene?.primitives?.removeAll();
    }
  };
    }
  // 通过点ID删除
  const removeById = id => {
    viewer?.entities.removeById(id);
    const pointEntity = viewer?.entities.getById(id);
        viewer?.entities.removeById(id)
        const pointEntity = viewer?.entities.getById(id)
    if (pointEntity && pointEntity !== undefined) {
      viewer?.entities.remove(pointEntity);
            viewer?.entities.remove(pointEntity)
    }
  };
    }
  // 通过点ID获取实体
  const getEntityById = id => {
    const pointEntity = viewer?.entities.getById(id);
    return pointEntity;
  };
        const pointEntity = viewer?.entities.getById(id)
        return pointEntity
    }
  // 添加标记点
  const addPoint = pointOption => {
    if (!pointOption.longitude && !pointOption.latitude) return;
        if (!pointOption.longitude && !pointOption.latitude) return
    const position = Cesium.Cartesian3.fromDegrees(
      pointOption.longitude,
      pointOption.latitude,
      pointOption?.altitude || 0
    );
        )
    viewer?.entities.add({
      position,
      billboard: pointOption.billboard,
      point: pointOption.point,
      label: pointOption.label,
      id: pointOption.id,
    });
  };
        })
    }
  const addPolyline = pointOption => {
    return viewer?.entities.add({
      polyline: pointOption.polyline,
      id: pointOption.id,
    });
  };
        })
    }
  // 更新图片实体位置
  function updateEntityPosition(longitude, latitude, id, params) {
    const entity = getEntityById(id);
    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude);
    const heading = Cesium.Math.toRadians(-params.heading);
        const entity = getEntityById(id)
        const position = Cesium.Cartesian3.fromDegrees(longitude, latitude)
        const heading = Cesium.Math.toRadians(-params.heading)
    if (Cesium.defined(entity)) {
      entity.position = position;
      entity.billboard.rotation = heading;
            entity.position = position
            entity.billboard.rotation = heading
    }
  }
  // 飞行 flyto
  const flyTo = (pointOption, time = 4, height = 3000, orientation = {}) => {
    if (!pointOption.longitude && !pointOption.latitude) return;
        if (!pointOption.longitude && !pointOption.latitude) return
    const destination = Cesium.Cartesian3.fromDegrees(
      pointOption.longitude,
      pointOption.latitude,
      height
    );
    const duration = time;
        )
        const duration = time
    viewer?.camera.flyTo({
      destination,
      duration,
      orientation,
    });
  };
        })
    }
  // 鼠标点击事件
  const addLeftClickEvent = (sid, cb, eventKey = 'handler') => {
    if (handlerEvents.handler) removeLeftClickEvent();
    if (handlerEvents[eventKey]) removeLeftClickEvent(eventKey);
        if (handlerEvents.handler) removeLeftClickEvent()
        if (handlerEvents[eventKey]) removeLeftClickEvent(eventKey)
    handlerEvents[eventKey] = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
        handlerEvents[eventKey] = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    handlerEvents[eventKey].setInputAction(function (click) {
      const pick = viewer?.scene.pick(click.position);
            const pick = viewer?.scene.pick(click.position)
      if (pick && pick.primitive && pick.primitive?.customParams?.type == '3DTileset') {
        return cb(click, pick, viewer, handlerEvents[eventKey]);
                return cb(click, pick, viewer, handlerEvents[eventKey])
      }
      if (pick && pick.id && (pick.id._id === sid || pick.id._id.includes(sid))) {
        cb(click, pick, viewer, handlerEvents[eventKey]);
                cb(click, pick, viewer, handlerEvents[eventKey])
      }
      if (sid === null) {
        cb(click, pick, viewer, handlerEvents[eventKey]);
                cb(click, pick, viewer, handlerEvents[eventKey])
      }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  };
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }
  // 移除鼠标点击事件
  const removeLeftClickEvent = (eventKey = 'handler') => {
    if (handlerEvents[eventKey] == null) return;
    handlerEvents[eventKey].removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
        if (handlerEvents[eventKey] == null) return
        handlerEvents[eventKey].removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
    handlerEvents[eventKey] = null;
  };
        handlerEvents[eventKey] = null
    }
  // 鼠标左键按下事件
  let leftDownClickHandler = { handler: null };
    let leftDownClickHandler = { handler: null }
  const addLeftDownClickEvent = (sid, cb, eventKey = 'handler') => {
    if (leftDownClickHandler.handler) removeLeftDownClickEvent();
    if (leftDownClickHandler[eventKey]) removeLeftDownClickEvent(eventKey);
        if (leftDownClickHandler.handler) removeLeftDownClickEvent()
        if (leftDownClickHandler[eventKey]) removeLeftDownClickEvent(eventKey)
    leftDownClickHandler[eventKey] = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
        leftDownClickHandler[eventKey] = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    leftDownClickHandler[eventKey].setInputAction(function (click) {
      const pick = viewer?.scene.pick(click.position);
      cb(click, pick, viewer);
    }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
  };
            const pick = viewer?.scene.pick(click.position)
            cb(click, pick, viewer)
        }, Cesium.ScreenSpaceEventType.LEFT_DOWN)
    }
  // 移除鼠标左键按下事件
  const removeLeftDownClickEvent = (eventKey = 'handler') => {
    if (leftDownClickHandler[eventKey] == null) return;
    leftDownClickHandler[eventKey].removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN);
        if (leftDownClickHandler[eventKey] == null) return
        leftDownClickHandler[eventKey].removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN)
    leftDownClickHandler[eventKey] = null;
  };
        leftDownClickHandler[eventKey] = null
    }
  // 鼠标右击事件
  let leftUpClickHandler = { handler: null };
    let leftUpClickHandler = { handler: null }
  const addLeftUpClickEvent = (sid, cb, eventKey = 'handler') => {
    if (leftUpClickHandler.handler) removeLeftUpClickEvent();
    if (leftUpClickHandler[eventKey]) removeLeftUpClickEvent(eventKey);
        if (leftUpClickHandler.handler) removeLeftUpClickEvent()
        if (leftUpClickHandler[eventKey]) removeLeftUpClickEvent(eventKey)
    leftUpClickHandler[eventKey] = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
        leftUpClickHandler[eventKey] = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    leftUpClickHandler[eventKey].setInputAction(function (click) {
      const pick = viewer?.scene.pick(click.position);
      cb(click, pick, viewer);
    }, Cesium.ScreenSpaceEventType.LEFT_UP);
  };
            const pick = viewer?.scene.pick(click.position)
            cb(click, pick, viewer)
        }, Cesium.ScreenSpaceEventType.LEFT_UP)
    }
  // 移除鼠标右键事件
  const removeLeftUpClickEvent = (eventKey = 'handler') => {
    if (leftUpClickHandler[eventKey] == null) return;
    leftUpClickHandler[eventKey].removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP);
        if (leftUpClickHandler[eventKey] == null) return
        leftUpClickHandler[eventKey].removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP)
    leftUpClickHandler[eventKey] = null;
  };
        leftUpClickHandler[eventKey] = null
    }
  // 鼠标右击事件
  let rightClickHandler;
    let rightClickHandler
  const addRightClickEvent = (sid, cb) => {
    if (rightClickHandler) removeRightClickEvent();
        if (rightClickHandler) removeRightClickEvent()
    rightClickHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
        rightClickHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    rightClickHandler.setInputAction(function (click) {
      const pick = viewer?.scene.pick(click.position);
      cb(click, pick, viewer);
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
  };
            const pick = viewer?.scene.pick(click.position)
            cb(click, pick, viewer)
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    }
  // 移除鼠标右键事件
  const removeRightClickEvent = () => {
    if (!rightClickHandler) return;
    rightClickHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
        if (!rightClickHandler) return
        rightClickHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    rightClickHandler = null;
  };
        rightClickHandler = null
    }
  // 鼠标移动事件
  let LeftMounseHandler;
    let LeftMounseHandler
  const addLeftmounseEvent = (sid, cb) => {
    if (LeftMounseHandler) removeLeftmounseEvent();
    LeftMounseHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
        if (LeftMounseHandler) removeLeftmounseEvent()
        LeftMounseHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    LeftMounseHandler.setInputAction(function (event) {
      const cartesian3 = viewer?.scene.globe.pick(
        viewer?.camera.getPickRay(event.startPosition),
        viewer?.scene
      );
      cb(cartesian3, viewer);
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  };
            )
            cb(cartesian3, viewer)
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    }
  // 移除鼠标移动事件
  const removeLeftmounseEvent = () => {
    if (LeftMounseHandler == null) return;
    LeftMounseHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        if (LeftMounseHandler == null) return
        LeftMounseHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    LeftMounseHandler = null;
  };
        LeftMounseHandler = null
    }
  let MounseHandler;
    let MounseHandler
  const addMounseHandler = (sid, cb) => {
    if (MounseHandler == null) removeMounseEvent();
        if (MounseHandler == null) removeMounseEvent()
    MounseHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
        MounseHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    MounseHandler.setInputAction(function (movement) {
      let mouseInfo = _getMouseInfo(movement.endPosition);
            let mouseInfo = _getMouseInfo(movement.endPosition)
      cb(mouseInfo, viewer);
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  };
            cb(mouseInfo, viewer)
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    }
  const _getMouseInfo = position => {
    let scene = viewer.scene;
    let target = scene.pick(position);
    let cartesian = undefined;
    let surfaceCartesian = undefined;
    let wgs84Position = undefined;
    let wgs84SurfacePosition = undefined;
        let scene = viewer.scene
        let target = scene.pick(position)
        let cartesian = undefined
        let surfaceCartesian = undefined
        let wgs84Position = undefined
        let wgs84SurfacePosition = undefined
    if (scene.pickPositionSupported) {
      cartesian = scene.pickPosition(position);
            cartesian = scene.pickPosition(position)
    }
    if (cartesian) {
      let c = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian);
            let c = Cesium.Ellipsoid.WGS84.cartesianToCartographic(cartesian)
      if (c) {
        wgs84Position = {
          lng: Cesium.Math.toDegrees(c.longitude),
          lat: Cesium.Math.toDegrees(c.latitude),
          alt: c.height,
        };
                }
      }
    }
    if (
      scene.mode === Cesium.SceneMode.SCENE3D &&
      !(viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider)
    ) {
      let ray = scene.camera.getPickRay(position);
      surfaceCartesian = scene.globe.pick(ray, scene);
            let ray = scene.camera.getPickRay(position)
            surfaceCartesian = scene.globe.pick(ray, scene)
    } else {
      surfaceCartesian = scene.camera.pickEllipsoid(position, Cesium.Ellipsoid.WGS84);
            surfaceCartesian = scene.camera.pickEllipsoid(position, Cesium.Ellipsoid.WGS84)
    }
    if (surfaceCartesian) {
      let c = Cesium.Ellipsoid.WGS84.cartesianToCartographic(surfaceCartesian);
            let c = Cesium.Ellipsoid.WGS84.cartesianToCartographic(surfaceCartesian)
      if (c) {
        wgs84SurfacePosition = {
          lng: Cesium.Math.toDegrees(c.longitude),
          lat: Cesium.Math.toDegrees(c.latitude),
          alt: c.height,
        };
                }
      }
    }
@@ -736,82 +731,82 @@
      wgs84Position: wgs84Position,
      surfacePosition: surfaceCartesian,
      wgs84SurfacePosition: wgs84SurfacePosition,
    };
  };
        }
    }
  // 移除鼠标移动事件
  const removeMounseEvent = () => {
    if (MounseHandler == null) return;
    MounseHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        if (MounseHandler == null) return
        MounseHandler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
    MounseHandler = null;
  };
        MounseHandler = null
    }
  // 视角变化时间
  let mapViewHandler = null;
    let mapViewHandler = null
  const addCameraMoveEvent = cb => {
    if (mapViewHandler) removeCameraMoveEvent();
        if (mapViewHandler) removeCameraMoveEvent()
    mapViewHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        mapViewHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
    mapViewHandler.setInputAction(event => {
      cb(event);
    }, Cesium.ScreenSpaceEventType.WHEEL);
  };
            cb(event)
        }, Cesium.ScreenSpaceEventType.WHEEL)
    }
  const removeCameraMoveEvent = () => {
    if (mapViewHandler == null) return;
    mapViewHandler.removeInputAction(Cesium.ScreenSpaceEventType.WHEEL);
    mapViewHandler = null;
  };
        if (mapViewHandler == null) return
        mapViewHandler.removeInputAction(Cesium.ScreenSpaceEventType.WHEEL)
        mapViewHandler = null
    }
  // 添加entity
  const addCustomEntityDataSource = (sourceName, entities) => {
    if (!customEntityDataSources[sourceName]) {
      customEntityDataSources[sourceName] = new Cesium.CustomDataSource();
      window.$viewer?.dataSources.add(customEntityDataSources[sourceName]);
            customEntityDataSources[sourceName] = new Cesium.CustomDataSource()
            window.$viewer?.dataSources.add(customEntityDataSources[sourceName])
    }
    let entity = customEntityDataSources[sourceName].entities.add(entities);
        let entity = customEntityDataSources[sourceName].entities.add(entities)
    return entity;
  };
        return entity
    }
  const clearCustomEntityDataSource = sourceName => {
    if (customEntityDataSources[sourceName]) {
      customEntityDataSources[sourceName]?.entities.removeAll();
            customEntityDataSources[sourceName]?.entities.removeAll()
    }
  };
    }
  const removeAllCustomEntityDataSource = sourceName => {
    if (customEntityDataSources[sourceName]) {
      customEntityDataSources[sourceName]?.entities.removeAll();
      window.$viewer.dataSources.remove(customEntityDataSources[sourceName]);
      delete customEntityDataSources[sourceName];
            customEntityDataSources[sourceName]?.entities.removeAll()
            window.$viewer.dataSources.remove(customEntityDataSources[sourceName])
            delete customEntityDataSources[sourceName]
    }
  };
    }
  // 添加entity
  const addCustomImageryProviderDataSource = imageryLayers => {
    return viewer?.imageryLayers.addImageryProvider(imageryLayers);
  };
        return viewer?.imageryLayers.addImageryProvider(imageryLayers)
    }
  const showCustomImageryProviderDataSource = (imageryLayers, show) => {
    if (imageryLayers) {
      imageryLayers.show = show;
            imageryLayers.show = show
    }
  };
    }
  const removeAllCustomImageryProviderDataSource = imageryLayers => {
    if (imageryLayers) {
      viewer?.imageryLayers.remove(imageryLayers);
            viewer?.imageryLayers.remove(imageryLayers)
    }
  };
    }
  // 添加范围的圆
  const addEllipse = ({ longitude, latitude, dist = 7000 }) => {
    if (!longitude && !latitude) return;
        if (!longitude && !latitude) return
    // 定义起点位置
    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude);
        const position = Cesium.Cartesian3.fromDegrees(longitude, latitude)
    // 画圆
    viewer?.entities.add({
@@ -824,14 +819,14 @@
        outline: true,
        material: Cesium.Color.CORNFLOWERBLUE.withAlpha(0.3),
      },
    });
        })
    // 添加距离虚线
    // addDistLine({ longitude, latitude, dist });
  };
    }
  const addDistLine = ({ longitude, latitude, dist = 7 }) => {
    // 定义起点位置
    const startPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude);
        const startPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude)
    // 计算目标位置(7公里处)
    const offsetCartesian = Cesium.Cartesian3.fromDegrees(
      longitude,
@@ -839,7 +834,7 @@
        Cesium.Math.toDegrees(
          dist / (Cesium.Ellipsoid.WGS84.maximumRadius * Math.cos(Cesium.Math.toRadians(latitude)))
        ) // 7公里的偏移
    );
        )
    // 将目标位置转换为经纬度
    // const offsetCartographic = Cesium.Cartographic.fromCartesian(offsetCartesian);
    // const offsetLongitude = Cesium.Math.toDegrees(offsetCartographic.longitude);
@@ -855,15 +850,15 @@
          color: Cesium.Color.CORNFLOWERBLUE,
        }),
      },
    });
  };
        })
    }
  // 添加圆
  const addCircle = option => {
    if (!option.longitude && !option.latitude) return;
        if (!option.longitude && !option.latitude) return
    // 定义起点位置
    const { longitude, latitude } = option;
    const position = Cesium.Cartesian3.fromDegrees(longitude, latitude);
        const { longitude, latitude } = option
        const position = Cesium.Cartesian3.fromDegrees(longitude, latitude)
    viewer.entities.add({
      position,
      id: option.id,
@@ -876,8 +871,8 @@
        outlineColor: Cesium.Color.fromCssColorString(option.color),
        outlineWidth: 3,
      },
    });
  };
        })
    }
  //
  /**
@@ -886,14 +881,14 @@
   * @return {*} void 0
   */
  const addPolygon = option => {
    if (option.positions.length === 0) return;
        if (option.positions.length === 0) return
    let zIndex = {};
        let zIndex = {}
    if (option.zIndex) {
      zIndex = {
        zIndex: option.zIndex,
      };
            }
    }
    // 定义起点位置
@@ -908,49 +903,48 @@
        outlineWidth: 3,
      },
      ...zIndex,
    });
  };
        })
    }
  // Cesium矢量切片是否加载完成
  const isLoadingCompleted = () => {
    return new Promise((resolve, reject) => {
      const helper = new Cesium.EventHelper();
            const helper = new Cesium.EventHelper()
      helper.add(viewer?.scene.globe.tileLoadProgressEvent, function (e) {
        if (e === 0) {
          resolve(true);
                    resolve(true)
        }
      });
    });
  };
            })
        })
    }
  // 获取屏幕四个角经纬度
  const getScreenCorner = () => {
    const camera = viewer.scene.camera;
    const canvas = viewer.canvas;
        const camera = viewer.scene.camera
        const canvas = viewer.canvas
    // 获取屏幕左下角和右上角的世界坐标
    const leftBottom = new Cesium.Cartesian2(0, canvas.clientHeight);
    const rightTop = new Cesium.Cartesian2(canvas.clientWidth, 0);
        const leftBottom = new Cesium.Cartesian2(0, canvas.clientHeight)
        const rightTop = new Cesium.Cartesian2(canvas.clientWidth, 0)
    // 将屏幕坐标转为世界坐标
    const leftBottomWorld = camera.pickEllipsoid(leftBottom, viewer.scene.globe.ellipsoid);
    const rightTopWorld = camera.pickEllipsoid(rightTop, viewer.scene.globe.ellipsoid);
        const leftBottomWorld = camera.pickEllipsoid(leftBottom, viewer.scene.globe.ellipsoid)
        const rightTopWorld = camera.pickEllipsoid(rightTop, viewer.scene.globe.ellipsoid)
    // 将世界坐标转为经纬度
    const leftBottomCartographic =
      viewer.scene.globe.ellipsoid.cartesianToCartographic(leftBottomWorld);
    const rightTopCartographic =
      viewer.scene.globe.ellipsoid.cartesianToCartographic(rightTopWorld);
            viewer.scene.globe.ellipsoid.cartesianToCartographic(leftBottomWorld)
        const rightTopCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(rightTopWorld)
    // 获取经纬度
    const leftBottomLonLat = [
      Cesium.Math.toDegrees(leftBottomCartographic.longitude),
      Cesium.Math.toDegrees(leftBottomCartographic.latitude),
    ];
        ]
    const rightTopLonLat = [
      Cesium.Math.toDegrees(rightTopCartographic.longitude),
      Cesium.Math.toDegrees(rightTopCartographic.latitude),
    ];
        ]
    // 返回四个角的经纬度
    return {
@@ -958,86 +952,86 @@
      rb: [rightTopLonLat[0], leftBottomLonLat[1]], // 右下角
      rt: rightTopLonLat,
      lt: [leftBottomLonLat[0], rightTopLonLat[1]], // 左上角
    };
  };
        }
    }
  // 加载3D建筑模型
  let tileset = null;
    let tileset = null
  function setBuilding3dModel() {
    try {
      const resource = Cesium.IonResource.fromAssetId(96188);
            const resource = Cesium.IonResource.fromAssetId(96188)
      tileset = new Cesium.Cesium3DTileset({
        url: resource,
      });
            })
      tileset.customParams = {
        type: '3DTileset',
      };
            }
      viewer.scene.primitives.add(tileset);
            viewer.scene.primitives.add(tileset)
    } catch (error) {
      console.log(`Error loading tileset: ${error}`);
            console.log(`Error loading tileset: ${error}`)
    }
  }
  function removeBuilding3dModel() {
    if (tileset) {
      viewer.scene.primitives.remove(tileset);
            viewer.scene.primitives.remove(tileset)
    }
  }
  const viewerDestory = () => {
    viewer && viewer.destroy();
    viewer = null;
        viewer && viewer.destroy()
        viewer = null
    window.$viewer = null
  };
    }
  let tilesetArr = [];
    let tilesetArr = []
  const add3Dtileset = () => {
    let url = '/3Dtile/kjds/tileset.json';
        let url = '/3Dtile/kjds/tileset.json'
    let tileset = new Cesium.Cesium3DTileset({
      url: url,
    });
        })
    tileset.customParams = {
      type: '3DTileset',
    };
        }
    tilesetArr.push(tileset);
        tilesetArr.push(tileset)
    tilesetArr.forEach(i => viewer?.scene.primitives.add(i));
  };
        tilesetArr.forEach(i => viewer?.scene.primitives.add(i))
    }
  const remove3Dtileset = () => {
    if (tilesetArr.length > 0) {
      tilesetArr.forEach(i => viewer.scene.primitives.remove(i));
            tilesetArr.forEach(i => viewer.scene.primitives.remove(i))
    }
    tilesetArr = [];
  };
        tilesetArr = []
    }
  let pointEditHandler;
    let pointEditHandler
  // 航点航线编辑相关事件
  const pointInitEvent = (lefet_down, mouse_move, left_up) => {
    if (!pointEditHandler) {
      pointEditHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas);
            pointEditHandler = new Cesium.ScreenSpaceEventHandler(viewer?.scene.canvas)
    }
    const events = {
      lefet_down,
      mouse_move,
      left_up,
    };
        }
    pointEditBindEvent(events);
    pointEditBindEvent(events, Cesium.KeyboardEventModifier.CTRL);
    pointEditBindEvent(events, Cesium.KeyboardEventModifier.ALT);
    pointEditBindEvent(events, Cesium.KeyboardEventModifier.SHIFT);
    pointEditBindEvent(events, Cesium.KeyboardEventModifier.META);
  };
        pointEditBindEvent(events)
        pointEditBindEvent(events, Cesium.KeyboardEventModifier.CTRL)
        pointEditBindEvent(events, Cesium.KeyboardEventModifier.ALT)
        pointEditBindEvent(events, Cesium.KeyboardEventModifier.SHIFT)
        pointEditBindEvent(events, Cesium.KeyboardEventModifier.META)
    }
  const pointEditBindEvent = (events, e) => {
    if (pointEditHandler) {
@@ -1045,31 +1039,31 @@
        events.lefet_down(e),
        Cesium.ScreenSpaceEventType.LEFT_DOWN,
        e
      );
            )
      pointEditHandler.setInputAction(
        events.mouse_move(e),
        Cesium.ScreenSpaceEventType.MOUSE_MOVE,
        e
      );
      pointEditHandler.setInputAction(events.left_up(e), Cesium.ScreenSpaceEventType.LEFT_UP, e);
            )
            pointEditHandler.setInputAction(events.left_up(e), Cesium.ScreenSpaceEventType.LEFT_UP, e)
    }
  };
    }
  const pointUnInitEvent = () => {
    pointEditUnBindEvent();
    pointEditUnBindEvent(Cesium.KeyboardEventModifier.CTRL);
    pointEditUnBindEvent(Cesium.KeyboardEventModifier.ALT);
    pointEditUnBindEvent(Cesium.KeyboardEventModifier.SHIFT);
    pointEditUnBindEvent(Cesium.KeyboardEventModifier.META);
        pointEditUnBindEvent()
        pointEditUnBindEvent(Cesium.KeyboardEventModifier.CTRL)
        pointEditUnBindEvent(Cesium.KeyboardEventModifier.ALT)
        pointEditUnBindEvent(Cesium.KeyboardEventModifier.SHIFT)
        pointEditUnBindEvent(Cesium.KeyboardEventModifier.META)
    pointEditHandler = null;
  };
        pointEditHandler = null
    }
  const pointEditUnBindEvent = e => {
    pointEditHandler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN, e);
    pointEditHandler?.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE, e);
    pointEditHandler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP, e);
  };
        pointEditHandler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN, e)
        pointEditHandler?.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE, e)
        pointEditHandler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP, e)
    }
  return {
    _init,
@@ -1133,5 +1127,5 @@
    // 航线规划---航点航线
    pointInitEvent,
    pointUnInitEvent,
  };
    }
}
src/utils/cesium/AmapMercatorTilingScheme/CoordTransform.js
@@ -1,8 +1,8 @@
// 定义一些常量
const BD_FACTOR = (3.14159265358979324 * 3000.0) / 180.0;
const PI = 3.1415926535897932384626;
const RADIUS = 6378245.0;
const EE = 0.00669342162296594323;
const BD_FACTOR = (3.14159265358979324 * 3000.0) / 180.0
const PI = 3.1415926535897932384626
const RADIUS = 6378245.0
const EE = 0.00669342162296594323
class CoordTransform {
    /**
@@ -12,13 +12,13 @@
     * @returns {number[]}
     */
    static BD09ToGCJ02(lng, lat) {
        let x = +lng - 0.0065;
        let y = +lat - 0.006;
        let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * BD_FACTOR);
        let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * BD_FACTOR);
        let gg_lng = z * Math.cos(theta);
        let gg_lat = z * Math.sin(theta);
        return [gg_lng, gg_lat];
        let x = +lng - 0.0065
        let y = +lat - 0.006
        let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * BD_FACTOR)
        let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * BD_FACTOR)
        let gg_lng = z * Math.cos(theta)
        let gg_lat = z * Math.sin(theta)
        return [gg_lng, gg_lat]
    }
    /**
@@ -29,15 +29,13 @@
     * @constructor
     */
    static GCJ02ToBD09(lng, lat) {
        lat = +lat;
        lng = +lng;
        let z =
            Math.sqrt(lng * lng + lat * lat) +
            0.00002 * Math.sin(lat * BD_FACTOR);
        let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * BD_FACTOR);
        let bd_lng = z * Math.cos(theta) + 0.0065;
        let bd_lat = z * Math.sin(theta) + 0.006;
        return [bd_lng, bd_lat];
        lat = +lat
        lng = +lng
        let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * BD_FACTOR)
        let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * BD_FACTOR)
        let bd_lng = z * Math.cos(theta) + 0.0065
        let bd_lat = z * Math.sin(theta) + 0.006
        return [bd_lng, bd_lat]
    }
    /**
@@ -47,13 +45,13 @@
     * @returns {number[]}
     */
    static WGS84ToGCJ02(lng, lat) {
        lat = +lat;
        lng = +lng;
        lat = +lat
        lng = +lng
        if (this.out_of_china(lng, lat)) {
            return [lng, lat];
            return [lng, lat]
        } else {
            let d = this.delta(lng, lat);
            return [lng + d[0], lat + d[1]];
            let d = this.delta(lng, lat)
            return [lng + d[0], lat + d[1]]
        }
    }
@@ -65,15 +63,15 @@
     * @constructor
     */
    static GCJ02ToWGS84(lng, lat) {
        lat = +lat;
        lng = +lng;
        lat = +lat
        lng = +lng
        if (this.out_of_china(lng, lat)) {
            return [lng, lat];
            return [lng, lat]
        } else {
            let d = this.delta(lng, lat);
            let mgLng = lng + d[0];
            let mgLat = lat + d[1];
            return [lng * 2 - mgLng, lat * 2 - mgLat];
            let d = this.delta(lng, lat)
            let mgLng = lng + d[0]
            let mgLat = lat + d[1]
            return [lng * 2 - mgLng, lat * 2 - mgLat]
        }
    }
@@ -84,16 +82,15 @@
     * @returns {number[]}
     */
    static delta(lng, lat) {
        let dLng = this.transformLng(lng - 105, lat - 35);
        let dLat = this.transformLat(lng - 105, lat - 35);
        const radLat = (lat / 180) * PI;
        let magic = Math.sin(radLat);
        magic = 1 - EE * magic * magic;
        const sqrtMagic = Math.sqrt(magic);
        dLng = (dLng * 180) / ((RADIUS / sqrtMagic) * Math.cos(radLat) * PI);
        dLat =
            (dLat * 180) / (((RADIUS * (1 - EE)) / (magic * sqrtMagic)) * PI);
        return [dLng, dLat];
        let dLng = this.transformLng(lng - 105, lat - 35)
        let dLat = this.transformLat(lng - 105, lat - 35)
        const radLat = (lat / 180) * PI
        let magic = Math.sin(radLat)
        magic = 1 - EE * magic * magic
        const sqrtMagic = Math.sqrt(magic)
        dLng = (dLng * 180) / ((RADIUS / sqrtMagic) * Math.cos(radLat) * PI)
        dLat = (dLat * 180) / (((RADIUS * (1 - EE)) / (magic * sqrtMagic)) * PI)
        return [dLng, dLat]
    }
    /**
@@ -103,30 +100,14 @@
     * @returns {number}
     */
    static transformLng(lng, lat) {
        lat = +lat;
        lng = +lng;
        lat = +lat
        lng = +lng
        let ret =
            300.0 +
            lng +
            2.0 * lat +
            0.1 * lng * lng +
            0.1 * lng * lat +
            0.1 * Math.sqrt(Math.abs(lng));
        ret +=
            ((20.0 * Math.sin(6.0 * lng * PI) +
                20.0 * Math.sin(2.0 * lng * PI)) *
                2.0) /
            3.0;
        ret +=
            ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) *
                2.0) /
            3.0;
        ret +=
            ((150.0 * Math.sin((lng / 12.0) * PI) +
                300.0 * Math.sin((lng / 30.0) * PI)) *
                2.0) /
            3.0;
        return ret;
            300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
        ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0
        ret += ((20.0 * Math.sin(lng * PI) + 40.0 * Math.sin((lng / 3.0) * PI)) * 2.0) / 3.0
        ret += ((150.0 * Math.sin((lng / 12.0) * PI) + 300.0 * Math.sin((lng / 30.0) * PI)) * 2.0) / 3.0
        return ret
    }
    /**
@@ -136,30 +117,19 @@
     * @returns {number}
     */
    static transformLat(lng, lat) {
        lat = +lat;
        lng = +lng;
        lat = +lat
        lng = +lng
        let ret =
            -100.0 +
            2.0 * lng +
            3.0 * lat +
            0.2 * lat * lat +
            0.1 * lng * lat +
            0.2 * Math.sqrt(Math.abs(lng));
        ret +=
            ((20.0 * Math.sin(6.0 * lng * PI) +
                20.0 * Math.sin(2.0 * lng * PI)) *
                2.0) /
            3.0;
        ret +=
            ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) *
                2.0) /
            3.0;
        ret +=
            ((160.0 * Math.sin((lat / 12.0) * PI) +
                320 * Math.sin((lat * PI) / 30.0)) *
                2.0) /
            3.0;
        return ret;
            0.2 * Math.sqrt(Math.abs(lng))
        ret += ((20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0) / 3.0
        ret += ((20.0 * Math.sin(lat * PI) + 40.0 * Math.sin((lat / 3.0) * PI)) * 2.0) / 3.0
        ret += ((160.0 * Math.sin((lat / 12.0) * PI) + 320 * Math.sin((lat * PI) / 30.0)) * 2.0) / 3.0
        return ret
    }
    /**
@@ -169,10 +139,10 @@
     * @returns {boolean}
     */
    static out_of_china(lng, lat) {
        lat = +lat;
        lng = +lng;
        return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
        lat = +lat
        lng = +lng
        return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55)
    }
}
export default CoordTransform;
export default CoordTransform
src/utils/cesium/AmapMercatorTilingScheme/index.js
@@ -13,41 +13,35 @@
    Math,
    Cartographic,
    Cartesian2,
} from 'cesium';
import CoordTransform from './CoordTransform';
} from 'cesium'
import CoordTransform from './CoordTransform'
class AmapMercatorTilingScheme extends WebMercatorTilingScheme {
    constructor() {
        super();
        super()
        let projection = new WebMercatorProjection();
        let projection = new WebMercatorProjection()
        this._projection.project = function (cartographic, result) {
            result = CoordTransform.WGS84ToGCJ02(
                Math.toDegrees(cartographic.longitude),
                Math.toDegrees(cartographic.latitude),
            );
                Math.toDegrees(cartographic.latitude)
            )
            result = projection.project(
                new Cartographic(
                    Math.toRadians(result[0]),
                    Math.toRadians(result[1]),
                ),
            );
            return new Cartesian2(result.x, result.y);
        };
                new Cartographic(Math.toRadians(result[0]), Math.toRadians(result[1]))
            )
            return new Cartesian2(result.x, result.y)
        }
        this._projection.unproject = function (cartesian, result) {
            let cartographic = projection.unproject(cartesian);
            let cartographic = projection.unproject(cartesian)
            result = CoordTransform.GCJ02ToWGS84(
                Math.toDegrees(cartographic.longitude),
                Math.toDegrees(cartographic.latitude),
            );
            return new Cartographic(
                Math.toRadians(result[0]),
                Math.toRadians(result[1]),
            );
        };
                Math.toDegrees(cartographic.latitude)
            )
            return new Cartographic(Math.toRadians(result[0]), Math.toRadians(result[1]))
        }
    }
}
export default AmapMercatorTilingScheme;
export default AmapMercatorTilingScheme
src/utils/cesium/ImageTrailMaterial.js
@@ -1,48 +1,45 @@
import * as Cesium from 'cesium';
import * as Cesium from 'cesium'
/**
 * 定义Cesium材质对象
 */
class ImageTrailMaterial {
    constructor(options = {}) {
        this._definitionChanged = new Cesium.Event();
        this._color = void 0;
        this._colorSubscription = void 0;
        this._speed = void 0;
        this._speedSubscription = void 0;
        this._image = void 0;
        this._imageSubscription = void 0;
        this._repeat = void 0;
        this._repeatSubscription = void 0;
        this.color = options.color || Cesium.Color.fromBytes(0, 0, 255, 255);
        this.speed = options.speed || 1;
        this.image = options.image;
        this.repeat = new Cesium.Cartesian2(
            options.repeat?.x || 1,
            options.repeat?.y || 1,
        );
        this._definitionChanged = new Cesium.Event()
        this._color = void 0
        this._colorSubscription = void 0
        this._speed = void 0
        this._speedSubscription = void 0
        this._image = void 0
        this._imageSubscription = void 0
        this._repeat = void 0
        this._repeatSubscription = void 0
        this.color = options.color || Cesium.Color.fromBytes(0, 0, 255, 255)
        this.speed = options.speed || 1
        this.image = options.image
        this.repeat = new Cesium.Cartesian2(options.repeat?.x || 1, options.repeat?.y || 1)
    }
    get isConstant() {
        return false;
        return false
    }
    get definitionChanged() {
        return this._definitionChanged;
        return this._definitionChanged
    }
    getType() {
        return Cesium.Material.ImageTrailMaterialType;
        return Cesium.Material.ImageTrailMaterialType
    }
    getValue(time, result) {
        if (!result) {
            result = {};
            result = {}
        }
        result.color = Cesium.Property.getValueOrUndefined(this._color, time);
        result.image = Cesium.Property.getValueOrUndefined(this._image, time);
        result.repeat = Cesium.Property.getValueOrUndefined(this._repeat, time);
        result.speed = this._speed;
        return result;
        result.color = Cesium.Property.getValueOrUndefined(this._color, time)
        result.image = Cesium.Property.getValueOrUndefined(this._image, time)
        result.repeat = Cesium.Property.getValueOrUndefined(this._repeat, time)
        result.speed = this._speed
        return result
    }
    equals(other) {
@@ -53,7 +50,7 @@
                Cesium.Property.equals(this._image, other._image) &&
                Cesium.Property.equals(this._repeat, other._repeat) &&
                Cesium.Property.equals(this._speed, other._speed))
        );
        )
    }
}
@@ -62,13 +59,11 @@
    speed: Cesium.createPropertyDescriptor('speed'),
    image: Cesium.createPropertyDescriptor('image'),
    repeat: Cesium.createPropertyDescriptor('repeat'),
});
})
//材质类型
Cesium.Material.ImageTrailMaterialType = 'PolylineImageTrail';
Cesium.Material.ImageTrailMaterialType = 'PolylineImageTrail'
//添加材质到缓冲区中
Cesium.Material._materialCache.addMaterial(
    Cesium.Material.ImageTrailMaterialType,
    {
Cesium.Material._materialCache.addMaterial(Cesium.Material.ImageTrailMaterialType, {
        fabric: {
            type: Cesium.Material.ImageTrailMaterialType,
            //uniform变量
@@ -97,11 +92,10 @@
                    `,
        },
        translucent: function () {
            return true;
        return true
        },
    },
);
export default ImageTrailMaterial;
})
export default ImageTrailMaterial
//之前的航线材质编写
// source: `
src/utils/cesium/common.js
@@ -6,126 +6,91 @@
 * @FilePath: /bigScreen/src/utils/cesium/common.js
 * @Description:
 */
import * as Cesium from 'cesium';
import JsZip from 'jszip';
import _ from 'lodash';
import axios from 'axios';
import { analyzeKmzFile, XMLToJSON } from './kmz';
import { getCenterPoint, getLnglatDist, getShortestDistance } from './mapUtil';
import * as Cesium from 'cesium'
import JsZip from 'jszip'
import _ from 'lodash'
import axios from 'axios'
import { analyzeKmzFile, XMLToJSON } from './kmz'
import { getCenterPoint, getLnglatDist, getShortestDistance } from './mapUtil'
// 图斑航线计算
export const polygonRoutePlanning = (polygonList, startPostion) => {
    // 起始点位
    const { longitude, latitude } = startPostion;
    const { longitude, latitude } = startPostion
    // 计算中心点
    const polygonCenterArr = polygonList.map((polygon) => {
        const newPolygon = [
            ...new Set(polygon.map((lnglat) => lnglat.join(','))),
        ];
    const polygonCenterArr = polygonList.map(polygon => {
        const newPolygon = [...new Set(polygon.map(lnglat => lnglat.join(',')))]
        return {
            center: getCenterPoint(polygon),
            polygon: newPolygon.map((item) => item.split(',')),
        };
    });
            polygon: newPolygon.map(item => item.split(',')),
        }
    })
    // 机场到中心点的距离排序
    const airportDistanceArr = polygonCenterArr.sort((prev, next) => {
        const prevDistance = getLnglatDist(
            longitude,
            latitude,
            prev.center.lng,
            prev.center.lat,
        );
        const nextDistance = getLnglatDist(
            longitude,
            latitude,
            next.center.lng,
            next.center.lat,
        );
        return prevDistance - nextDistance;
    });
        const prevDistance = getLnglatDist(longitude, latitude, prev.center.lng, prev.center.lat)
        const nextDistance = getLnglatDist(longitude, latitude, next.center.lng, next.center.lat)
        return prevDistance - nextDistance
    })
    const sortPolygon = [];
    const sortPolygon = []
    function getFirstPolygon(arr, start) {
        const { slongitude, slatitude } = start;
        const { slongitude, slatitude } = start
        // 机场到中心点的距离排序
        const airportDistanceArr = arr.sort((prev, next) => {
            const prevDistance = getLnglatDist(
                slongitude,
                slatitude,
                prev.center.lng,
                prev.center.lat,
            );
            const nextDistance = getLnglatDist(
                slongitude,
                slatitude,
                next.center.lng,
                next.center.lat,
            );
            return prevDistance - nextDistance;
        });
        const polygon = _.cloneDeep(airportDistanceArr[0]);
        if (polygon === void 0) return;
        sortPolygon.push(polygon);
        airportDistanceArr.splice(0, 1);
            const prevDistance = getLnglatDist(slongitude, slatitude, prev.center.lng, prev.center.lat)
            const nextDistance = getLnglatDist(slongitude, slatitude, next.center.lng, next.center.lat)
            return prevDistance - nextDistance
        })
        const polygon = _.cloneDeep(airportDistanceArr[0])
        if (polygon === void 0) return
        sortPolygon.push(polygon)
        airportDistanceArr.splice(0, 1)
        if (airportDistanceArr.length > 0) {
            getFirstPolygon(airportDistanceArr, {
                slongitude: polygon.center.lng,
                slatitude: polygon.center.lat,
            });
            })
        }
    }
    getFirstPolygon(polygonCenterArr, {
        slongitude: longitude,
        slatitude: latitude,
    });
    })
    // 计算图斑内点位飞行顺序
    let result = [[longitude, latitude]];
    let result = [[longitude, latitude]]
    sortPolygon.forEach((item, index) => {
        const { polygon } = item;
        const { polygon } = item
        // 取出当前图斑之前最后一个点
        const prevPolygon = result[result.length - 1];
        const [slng, slat] = prevPolygon;
        const nextPolygon = airportDistanceArr[index + 1];
        const prevPolygon = result[result.length - 1]
        const [slng, slat] = prevPolygon
        const nextPolygon = airportDistanceArr[index + 1]
        // 求出距离上一个点最近的点,作为第一个点
        const sequence = polygon.sort((prev, next) => {
            const [prevLng, prevLat] = prev;
            const [nextLng, nextLat] = next;
            const prevDistance = getLnglatDist(slng, slat, prevLng, prevLat);
            const nextDistance = getLnglatDist(slng, slat, nextLng, nextLat);
            return prevDistance - nextDistance;
        });
            const [prevLng, prevLat] = prev
            const [nextLng, nextLat] = next
            const prevDistance = getLnglatDist(slng, slat, prevLng, prevLat)
            const nextDistance = getLnglatDist(slng, slat, nextLng, nextLat)
            return prevDistance - nextDistance
        })
        // 第一个点位
        const firstLnglat = [...sequence[0]];
        const firstLnglat = [...sequence[0]]
        // 去除第一个点位
        const cloneSequence = _.cloneDeep(sequence);
        cloneSequence.splice(0, 1);
        const cloneSequence = _.cloneDeep(sequence)
        cloneSequence.splice(0, 1)
        if (nextPolygon) {
            // 获取两个经纬度组两个最近的点位
            const { index: lnglatIndex } = getShortestDistance(
                cloneSequence,
                nextPolygon.polygon,
            );
            const lastLnglat = _.cloneDeep(cloneSequence[lnglatIndex[0]]);
            const { index: lnglatIndex } = getShortestDistance(cloneSequence, nextPolygon.polygon)
            const lastLnglat = _.cloneDeep(cloneSequence[lnglatIndex[0]])
            // 删除飞行的最后一个点
            cloneSequence.splice(lnglatIndex[0], 1);
            cloneSequence.splice(lnglatIndex[0], 1)
            const centerLnglatList = cloneSequence.sort((prev, next) => {
                const [prevLng, prevLat] = prev;
                const [nextLng, nextLat] = next;
                const prevDistance = getLnglatDist(
                    longitude,
                    latitude,
                    prevLng,
                    prevLat,
                );
                const nextDistance = getLnglatDist(
                    longitude,
                    latitude,
                    nextLng,
                    nextLat,
                );
                return prevDistance - nextDistance;
            });
            result = [...result, firstLnglat, ...centerLnglatList, lastLnglat];
                const [prevLng, prevLat] = prev
                const [nextLng, nextLat] = next
                const prevDistance = getLnglatDist(longitude, latitude, prevLng, prevLat)
                const nextDistance = getLnglatDist(longitude, latitude, nextLng, nextLat)
                return prevDistance - nextDistance
            })
            result = [...result, firstLnglat, ...centerLnglatList, lastLnglat]
        } else {
            // const last = polygon.sort((prev, next) => {
            //   const [prevLng, prevLat] = prev;
@@ -134,61 +99,61 @@
            //   const nextDistance = getLnglatDist(longitude, latitude, nextLng, nextLat);
            //   return prevDistance - nextDistance;
            // });
            result = [...result, ...sequence];
            result = [...result, ...sequence]
            // result = [...result, ...last]
        }
    });
    return result;
};
    })
    return result
}
export const getWaylineFilePoints = async (fileUrl) => {
    const fileRes = await analyzeKmzFile(fileUrl);
    const waylineContent = await fileRes['fileInfoObj']?.['wpmz/waylines.wpml'];
    const xml = XMLToJSON(waylineContent);
    const placemarkArr = xml?.Document?.Folder.Placemark;
    const points = placemarkArr.map((placemark) => {
        const lnglat = placemark.Point.coordinates?.['#text'].split(',');
export const getWaylineFilePoints = async fileUrl => {
    const fileRes = await analyzeKmzFile(fileUrl)
    const waylineContent = await fileRes['fileInfoObj']?.['wpmz/waylines.wpml']
    const xml = XMLToJSON(waylineContent)
    const placemarkArr = xml?.Document?.Folder.Placemark
    const points = placemarkArr.map(placemark => {
        const lnglat = placemark.Point.coordinates?.['#text'].split(',')
        return {
            longitude: lnglat[0],
            latitude: lnglat[1],
        };
    });
    return points;
};
        }
    })
    return points
}
// 传入方向,计算移动点位经纬度
export function movePosition(lon, lat, heading, direction) {
    // 计算朝向角度的弧度值(Cesium 是基于地理坐标系,heading=0 指向正北)
    const headingRad = Cesium.Math.toRadians(heading);
    const moveStep = 0.00005; // 移动步长
    let newLon = lon;
    let newLat = lat;
    const headingRad = Cesium.Math.toRadians(heading)
    const moveStep = 0.00005 // 移动步长
    let newLon = lon
    let newLat = lat
    switch (direction) {
        case "W": // 向前(heading 方向)
            newLon += moveStep * Math.sin(headingRad);
            newLat += moveStep * Math.cos(headingRad);
            break;
        case 'W': // 向前(heading 方向)
            newLon += moveStep * Math.sin(headingRad)
            newLat += moveStep * Math.cos(headingRad)
            break
        case "S": // 向后(反方向)
            newLon -= moveStep * Math.sin(headingRad);
            newLat -= moveStep * Math.cos(headingRad);
            break;
        case 'S': // 向后(反方向)
            newLon -= moveStep * Math.sin(headingRad)
            newLat -= moveStep * Math.cos(headingRad)
            break
        case "D": // 向右(heading + 90°)
            newLon += moveStep * Math.cos(headingRad);
            newLat -= moveStep * Math.sin(headingRad);
            break;
        case 'D': // 向右(heading + 90°)
            newLon += moveStep * Math.cos(headingRad)
            newLat -= moveStep * Math.sin(headingRad)
            break
        case "A": // 向左(heading - 90°)
            newLon -= moveStep * Math.cos(headingRad);
            newLat += moveStep * Math.sin(headingRad);
            break;
        case 'A': // 向左(heading - 90°)
            newLon -= moveStep * Math.cos(headingRad)
            newLat += moveStep * Math.sin(headingRad)
            break
        default:
            console.warn("无效方向");
            return null;
            console.warn('无效方向')
            return null
    }
    return { longitude: newLon, latitude: newLat };
    return { longitude: newLon, latitude: newLat }
}
src/utils/cesium/compressImage.js
@@ -7,49 +7,49 @@
 * @return {*}
 */
function compressImage(src, quality, maxWidth, callback) {
    const img = new Image();
    img.setAttribute('crossOrigin', 'Anonymous');
    const img = new Image()
    img.setAttribute('crossOrigin', 'Anonymous')
    img.onload = function () {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        let width = img.width;
        let height = img.height;
        const canvas = document.createElement('canvas')
        const ctx = canvas.getContext('2d')
        let width = img.width
        let height = img.height
        if (width > maxWidth) {
            height *= maxWidth / width;
            width = maxWidth;
            height *= maxWidth / width
            width = maxWidth
        }
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);
        canvas.width = width
        canvas.height = height
        ctx.drawImage(img, 0, 0, width, height)
        const newData = canvas.toDataURL('image/jpeg', quality);
        const newData = canvas.toDataURL('image/jpeg', quality)
        // 使用atob()将base64转换为二进制字符串
        const binaryString = window.atob(newData.split(',')[1]);
        const mimeString = newData.split(',')[0].split(':')[1].split(';')[0];
        const binaryString = window.atob(newData.split(',')[1])
        const mimeString = newData.split(',')[0].split(':')[1].split(';')[0]
        // 创建Blob对象
        const array = [];
        const array = []
        for (let i = 0; i < binaryString.length; i++) {
            array.push(binaryString.charCodeAt(i));
            array.push(binaryString.charCodeAt(i))
        }
        const blob = new Blob([new Uint8Array(array)], { type: mimeString });
        const blob = new Blob([new Uint8Array(array)], { type: mimeString })
        callback(blob);
    };
    img.src = src;
        callback(blob)
    }
    img.src = src
    return src;
    return src
}
export default function imageCompress(src, quality, maxWidth) {
    // 使用例子
    return compressImage(src, quality, maxWidth, function (blob) {
        // 创建一个新的图片URL
        const imageUrl = URL.createObjectURL(blob);
        const imageUrl = URL.createObjectURL(blob)
        // 可以在这里使用imageUrl,比如设置为img元素的src
        // document.getElementById('your-image-element').src = imageUrl;
        // 当不需要这个URL的时候,释放它
        URL.revokeObjectURL(imageUrl);
    });
        URL.revokeObjectURL(imageUrl)
    })
}
src/utils/cesium/compressImage2.js
@@ -12,35 +12,35 @@
    maxWidth,
    maxHeight,
    outputFormat = 'image/jpeg',
    quality = 0.7,
    quality = 0.7
) {
    return new Promise((resolve, reject) => {
        const image = new Image();
        image.setAttribute('crossOrigin', 'Anonymous');
        image.src = src;
        const image = new Image()
        image.setAttribute('crossOrigin', 'Anonymous')
        image.src = src
        image.onload = () => {
            let width = image.width;
            let height = image.height;
            let width = image.width
            let height = image.height
            if (width > maxWidth) {
                height *= maxWidth / width;
                width = maxWidth;
                height *= maxWidth / width
                width = maxWidth
            }
            if (height > maxHeight) {
                width *= maxHeight / height;
                height = maxHeight;
                width *= maxHeight / height
                height = maxHeight
            }
            const canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            const ctx = canvas.getContext('2d');
            ctx.drawImage(image, 0, 0, width, height);
            const canvas = document.createElement('canvas')
            canvas.width = width
            canvas.height = height
            const ctx = canvas.getContext('2d')
            ctx.drawImage(image, 0, 0, width, height)
            const newDataUrl = canvas.toDataURL(outputFormat, quality);
            resolve(newDataUrl);
        };
        image.onerror = reject;
    });
            const newDataUrl = canvas.toDataURL(outputFormat, quality)
            resolve(newDataUrl)
        }
        image.onerror = reject
    })
}
src/utils/cesium/frustum/CreateFrustum.js
@@ -1,59 +1,59 @@
// * 创建视锥
import * as Cesium from 'cesium';
import * as Cesium from 'cesium'
/* eslint-disable new-cap */
/* eslint-disable no-undef */
export default class CreateFrustum {
  constructor(viewer, options) {
    this.position = options.position;
    this.viewer = viewer;
    this.fov = options.fov || 0;
    this.near = options.near || 0;
    this.far = options.far || 0;
    this.heading = options.heading || 0;
    this.pitch = options.pitch || 0;
    this.roll = options.roll || 0;
    this.width = options.width;
    this.height = options.height;
    this.add();
        this.position = options.position
        this.viewer = viewer
        this.fov = options.fov || 0
        this.near = options.near || 0
        this.far = options.far || 0
        this.heading = options.heading || 0
        this.pitch = options.pitch || 0
        this.roll = options.roll || 0
        this.width = options.width
        this.height = options.height
        this.add()
  }
  UpdateWidth(value) {
    this.width = value;
    this.add();
        this.width = value
        this.add()
  }
  UpdateHeight(value) {
    this.height = value;
    this.add();
        this.height = value
        this.add()
  }
  UpdateFov(value) {
    this.fov = value;
    this.add();
        this.fov = value
        this.add()
  }
  UpdateNear(value) {
    this.near = value;
    this.add();
        this.near = value
        this.add()
  }
  UpdateFar(value) {
    this.far = value;
    this.add();
        this.far = value
        this.add()
  }
  UpdateHeading(value) {
    this.heading = value;
    this.add();
        this.heading = value
        this.add()
  }
  UpdatePitch(value) {
    this.pitch = value;
    this.add();
        this.pitch = value
        this.add()
  }
  UpdateRoll(value) {
    this.roll = value;
    this.add();
        this.roll = value
        this.add()
  }
  UpdataPosition(position) {
    if (!position) return;
    this.position = position;
    this.add();
        if (!position) return
        this.position = position
        this.add()
  }
  // 更新视锥体的姿态
@@ -61,55 +61,55 @@
    this.position = Cesium.Cartesian3.fromDegrees(
      position.longitude,
      position.latitude,
      position.altitude,
    );
            position.altitude
        )
    this.orientation = Cesium.Transforms.headingPitchRollQuaternion(
      this.position,
      new Cesium.HeadingPitchRoll.fromDegrees(
        headingPitchRoll.heading,
        headingPitchRoll.pitch,
        headingPitchRoll.roll,
      ),
    );
    this.add();
                headingPitchRoll.roll
            )
        )
        this.add()
  }
  // 创建视锥体和轮廓线
  add() {
    this.clear();
    this.addFrustum();
    this.addOutline();
    this.addCenterline();
        this.clear()
        this.addFrustum()
        this.addOutline()
        this.addCenterline()
  }
  // 清除视锥体和轮廓线
  clear() {
    this.clearFrustum();
    this.clearOutline();
    this.clearCenterline();
        this.clearFrustum()
        this.clearOutline()
        this.clearCenterline()
  }
  // 清除视锥体
  clearFrustum() {
    if (this.frustumPrimitive) {
      this.viewer.scene.primitives.remove(this.frustumPrimitive);
      this.frustumPrimitive = null;
            this.viewer.scene.primitives.remove(this.frustumPrimitive)
            this.frustumPrimitive = null
    }
  }
  // 清除轮廓线
  clearOutline() {
    if (this.outlinePrimitive) {
      this.viewer.scene.primitives.remove(this.outlinePrimitive);
      this.outlinePrimitive = null;
            this.viewer.scene.primitives.remove(this.outlinePrimitive)
            this.outlinePrimitive = null
    }
  }
  clearCenterline() {
    if (this.centerDataSource) {
      this.centerDataSource.entities.removeAll();
      this.viewer.dataSources.remove(this.centerDataSource);
      this.centerDataSource = null;
            this.centerDataSource.entities.removeAll()
            this.viewer.dataSources.remove(this.centerDataSource)
            this.centerDataSource = null
    }
  }
@@ -124,33 +124,29 @@
      near: this.near,
      // 远面距视点的距离
      far: this.far,
    });
        })
    const position = Cesium.Cartesian3.fromDegrees(
      this.position.longitude,
      this.position.latitude,
      this.position.altitude,
    );
            this.position.altitude
        )
    const geometry = new Cesium.FrustumGeometry({
      frustum: frustum,
      origin: position,
      orientation: Cesium.Transforms.headingPitchRollQuaternion(
        position,
        new Cesium.HeadingPitchRoll.fromDegrees(
          this.heading,
          this.pitch,
          this.roll,
        ),
                new Cesium.HeadingPitchRoll.fromDegrees(this.heading, this.pitch, this.roll)
      ),
      vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
    });
        })
    const instance = new Cesium.GeometryInstance({
      geometry: geometry,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.fromBytes(0, 213, 144, 20),
                    Cesium.Color.fromBytes(0, 213, 144, 20)
        ),
      },
    });
        })
    const primitive = new Cesium.Primitive({
      geometryInstances: instance,
      appearance: new Cesium.PerInstanceColorAppearance({
@@ -158,8 +154,8 @@
        flat: true,
      }),
      asynchronous: false,
    });
    this.frustumPrimitive = this.viewer.scene.primitives.add(primitive);
        })
        this.frustumPrimitive = this.viewer.scene.primitives.add(primitive)
  }
  // 创建轮廓线
@@ -175,33 +171,29 @@
      near: this.near,
      // 远面距视点的距离
      far: this.far,
    });
        })
    const position = Cesium.Cartesian3.fromDegrees(
      this.position.longitude,
      this.position.latitude,
      this.position.altitude,
    );
            this.position.altitude
        )
    const geometry = new Cesium.FrustumOutlineGeometry({
      frustum: frustum,
      origin: position,
      orientation: Cesium.Transforms.headingPitchRollQuaternion(
        position,
        new Cesium.HeadingPitchRoll.fromDegrees(
          this.heading,
          this.pitch,
          this.roll,
        ),
                new Cesium.HeadingPitchRoll.fromDegrees(this.heading, this.pitch, this.roll)
      ),
      vertexFormat: Cesium.VertexFormat.POSITION_ONLY,
    });
        })
    const instance = new Cesium.GeometryInstance({
      geometry: geometry,
      attributes: {
        color: Cesium.ColorGeometryInstanceAttribute.fromColor(
          Cesium.Color.fromBytes(0, 213, 144, 255),
                    Cesium.Color.fromBytes(0, 213, 144, 255)
        ),
      },
    });
        })
    const primitive = new Cesium.Primitive({
      geometryInstances: instance,
      appearance: new Cesium.PerInstanceColorAppearance({
@@ -209,52 +201,40 @@
        flat: true,
      }),
      asynchronous: false,
    });
    this.outlinePrimitive = this.viewer.scene.primitives.add(primitive);
        })
        this.outlinePrimitive = this.viewer.scene.primitives.add(primitive)
  }
  addCenterline() {
    this.centerDataSource = new Cesium.CustomDataSource();
    this.viewer.dataSources.add(this.centerDataSource);
        this.centerDataSource = new Cesium.CustomDataSource()
        this.viewer.dataSources.add(this.centerDataSource)
    const position = Cesium.Cartesian3.fromDegrees(
      this.position.longitude,
      this.position.latitude,
      this.position.altitude,
    );
            this.position.altitude
        )
    let matrix = Cesium.Matrix3.fromQuaternion(
      Cesium.Transforms.headingPitchRollQuaternion(
        position,
        new Cesium.HeadingPitchRoll.fromDegrees(
          this.heading,
          this.pitch,
          this.roll,
                new Cesium.HeadingPitchRoll.fromDegrees(this.heading, this.pitch, this.roll)
        ),
      ),
      new Cesium.Matrix3(),
    );
            new Cesium.Matrix3()
        )
    let right1 = Cesium.Matrix3.getColumn(matrix, 0, new Cesium.Cartesian3());
    let up1 = Cesium.Matrix3.getColumn(matrix, 1, new Cesium.Cartesian3());
    let direction = Cesium.Matrix3.getColumn(
      matrix,
      2,
      new Cesium.Cartesian3(),
    );
        let right1 = Cesium.Matrix3.getColumn(matrix, 0, new Cesium.Cartesian3())
        let up1 = Cesium.Matrix3.getColumn(matrix, 1, new Cesium.Cartesian3())
        let direction = Cesium.Matrix3.getColumn(matrix, 2, new Cesium.Cartesian3())
    // const direction = new Cartesian3(-0.10668226241650887, 0.8103322335050215, -0.5761775474872814)
    let frontDirect = Cesium.Cartesian3.multiplyByScalar(
      direction,
      this.far,
      new Cesium.Cartesian3(),
    );
    let bottomCenter = Cesium.Cartesian3.add(
      position,
      frontDirect,
      new Cesium.Cartesian3(),
    );
            new Cesium.Cartesian3()
        )
        let bottomCenter = Cesium.Cartesian3.add(position, frontDirect, new Cesium.Cartesian3())
    // 创建Entity来显示中心线
    this.centerDataSource.entities.add({
@@ -270,6 +250,6 @@
          gapWidth: 1.0,
        }),
      },
    });
        })
  }
}
src/utils/cesium/kmz.js
@@ -1,91 +1,82 @@
import axios from 'axios';
import JsZip from 'jszip';
import axios from 'axios'
import JsZip from 'jszip'
const noWmpl = ['Folder', 'Placemark', 'Point', 'coordinates'];
const noWmpl = ['Folder', 'Placemark', 'Point', 'coordinates']
/**
 * @description: 读取kmz文件解析出kml文件
 * @param {string} filePath 文件地址
 * @return {*}
 */
export const analyzeKmzFile = (filePath) => {
export const analyzeKmzFile = filePath => {
  return (
    axios({
      url: filePath,
      method: 'get',
      responseType: 'arraybuffer',
      authorization: false
            authorization: false,
    })
      // .get(filePath, { responseType: 'arraybuffer' },)
      .then((fileRes) => fileRes.data)
      .then((kmzData) => JsZip.loadAsync(kmzData)) // 解压kmz文件
      .then((zipFile) => {
        const files = {};
        Object.keys(zipFile.files).forEach((key) => {
          files[key] = zipFile.files[key].async('text');
        });
            .then(fileRes => fileRes.data)
            .then(kmzData => JsZip.loadAsync(kmzData)) // 解压kmz文件
            .then(zipFile => {
                const files = {}
                Object.keys(zipFile.files).forEach(key => {
                    files[key] = zipFile.files[key].async('text')
                })
        return {
          zip: zipFile,
          fileInfoObj: files,
        };
                }
      })
  );
};
    )
}
export const getKmlParams = (source, isWpml, params) => {
  let regx = null;
    let regx = null
  if (isWpml) {
    if (params.mode) {
      regx = new RegExp(
        `<wpml:${params.name}>${params.findRegx}<\\/wpml:${params.name}>`,
        params.mode,
      );
                params.mode
            )
    } else {
      regx = new RegExp(
        `<wpml:${params.name}>${params.findRegx}<\\/wpml:${params.name}>`,
      );
            regx = new RegExp(`<wpml:${params.name}>${params.findRegx}<\\/wpml:${params.name}>`)
    }
  } else {
    if (params.mode) {
      regx = new RegExp(
        `<${params.name}>${params.findRegx}<\\/${params.name}>`,
        params.mode,
      );
            regx = new RegExp(`<${params.name}>${params.findRegx}<\\/${params.name}>`, params.mode)
    } else {
      regx = new RegExp(
        `<${params.name}>${params.findRegx}<\\/${params.name}>`,
      );
            regx = new RegExp(`<${params.name}>${params.findRegx}<\\/${params.name}>`)
    }
  }
  return source?.match(regx);
};
    return source?.match(regx)
}
export const generateKmlFormat = (settingParmas) => {
  let paramGroup = '';
  Object.keys(settingParmas).forEach((key) => {
    if (
      Object.prototype.toString.call(settingParmas[key]) === '[object Object]'
    ) {
      let parmaStr = '';
      Object.keys(settingParmas[key]).forEach((v) => {
export const generateKmlFormat = settingParmas => {
    let paramGroup = ''
    Object.keys(settingParmas).forEach(key => {
        if (Object.prototype.toString.call(settingParmas[key]) === '[object Object]') {
            let parmaStr = ''
            Object.keys(settingParmas[key]).forEach(v => {
        const xml = noWmpl.includes(key)
          ? `<${v}>${settingParmas[key][v]}</${v}>`
          : `<wpml:${v}>${settingParmas[key][v]}</wpml:${v}>`;
        parmaStr += xml;
      });
                    : `<wpml:${v}>${settingParmas[key][v]}</wpml:${v}>`
                parmaStr += xml
            })
      const xml = noWmpl.includes(key)
        ? `<${key}>${parmaStr}</${key}>`
        : `<wpml:${key}>${parmaStr}</wpml:${key}>`;
      paramGroup += xml;
                : `<wpml:${key}>${parmaStr}</wpml:${key}>`
            paramGroup += xml
    } else {
      const xml = noWmpl.includes(key)
        ? `<${key}>${settingParmas[key]}</${key}>`
        : `<wpml:${key}>${settingParmas[key]}</wpml:${key}>`;
      paramGroup += xml;
                : `<wpml:${key}>${settingParmas[key]}</wpml:${key}>`
            paramGroup += xml
    }
  });
  return paramGroup;
};
    })
    return paramGroup
}
/**
 * @description: JSON转XML
@@ -94,98 +85,98 @@
 * @return {*} string
 */
export const JSONToXML = (obj, rootName, isEnd) => {
  let xml = '';
    let xml = ''
  const buildXml = (obj, rootName) => {
    let xml = '';
        let xml = ''
    if (Array.isArray(obj)) {
      obj.forEach((item) => {
        const str = !noWmpl.includes(rootName) && isEnd ? 'wpml:' : '';
        xml += `<${str}${rootName}>${buildXml(item)}</${str}${rootName}>`;
      });
            obj.forEach(item => {
                const str = !noWmpl.includes(rootName) && isEnd ? 'wpml:' : ''
                xml += `<${str}${rootName}>${buildXml(item)}</${str}${rootName}>`
            })
    } else if (typeof obj === 'object') {
      Object.keys(obj).forEach((key) => {
            Object.keys(obj).forEach(key => {
        if (key === '#text') {
          xml += obj[key];
                    xml += obj[key]
        } else {
          const str = !noWmpl.includes(key) && isEnd ? 'wpml:' : '';
                    const str = !noWmpl.includes(key) && isEnd ? 'wpml:' : ''
          if (key === 'Placemark') {
            xml += `${buildXml(obj[key], key)}`;
                        xml += `${buildXml(obj[key], key)}`
          } else if (key === 'action') {
            if (Array.isArray(obj[key])) {
              xml += `${buildXml(obj[key], key)}`;
                            xml += `${buildXml(obj[key], key)}`
            } else {
              xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`;
                            xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`
            }
          } else {
            xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`;
                        xml += `<${str}${key}>${buildXml(obj[key], key)}</${str}${key}>`
          }
        }
      });
            })
    } else {
      xml += obj;
            xml += obj
    }
    return xml;
  };
        return xml
    }
  const header = isEnd ? '<?xml version="1.0" encoding="UTF-8"?>' : '';
    const header = isEnd ? '<?xml version="1.0" encoding="UTF-8"?>' : ''
  xml += `${header}
  <kml xmlns="http://www.opengis.net/kml/2.2" xmlns:wpml="http://www.dji.com/wpmz/1.0.5">
    <Document>
      ${buildXml(obj, rootName)}
    </Document>
  </kml>`;
  return xml;
};
export const getTagNameFromXml = (xmlString) => {
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
  const element = xmlDoc.documentElement;
  if (element && element.tagName) {
    return element.tagName; // 返回的是类似 "WPML:USEGLOBALHEADINGPARAM" 的全大写形式
  </kml>`
    return xml
  }
  return null;
};
export const getTagNameFromXml = xmlString => {
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(xmlString, 'text/xml')
    const element = xmlDoc.documentElement
    if (element && element.tagName) {
        return element.tagName // 返回的是类似 "WPML:USEGLOBALHEADINGPARAM" 的全大写形式
    }
    return null
}
// 将xml转为json
const deepParse = (xml) => {
  let obj = {};
const deepParse = xml => {
    let obj = {}
  // 如果是文档节点,遍历其子节点
  if (xml.nodeType === 1) {
    // element node
    // 处理子节点
    if (xml.childNodes.length > 0) {
      for (let i = 0; i < xml.childNodes.length; i++) {
        const item = xml.childNodes[i];
        const nodeName = item.nodeName.replace('wpml:', '');
                const item = xml.childNodes[i]
                const nodeName = item.nodeName.replace('wpml:', '')
        // 检查是否是文本节点
        if (item.nodeType === 3) {
          // text node
          // 处理文本节点的内容
          if (item.nodeValue.trim() !== '') {
            obj[nodeName] = item.nodeValue.trim();
                        obj[nodeName] = item.nodeValue.trim()
          }
        } else if (item.nodeType === 1) {
          // element node
          // 递归调用处理子节点
          if (obj[nodeName] === undefined) {
            const nodeValue = deepParse(item);
                        const nodeValue = deepParse(item)
            if (nodeValue[nodeName] === undefined) {
              obj[nodeName] = nodeValue;
                            obj[nodeName] = nodeValue
            } else {
              obj[nodeName] = nodeValue[nodeName];
                            obj[nodeName] = nodeValue[nodeName]
            }
          } else {
            if (!obj[nodeName].push) {
              const old = obj[nodeName];
              obj[nodeName] = [];
              obj[nodeName].push(old);
                            const old = obj[nodeName]
                            obj[nodeName] = []
                            obj[nodeName].push(old)
            }
            const nodeValue = deepParse(item);
                        const nodeValue = deepParse(item)
            if (nodeValue[nodeName] === undefined) {
              obj[nodeName].push(nodeValue);
                            obj[nodeName].push(nodeValue)
            }
          }
        }
@@ -194,25 +185,25 @@
  } else if (xml.nodeType === 3) {
    // text node
    // 处理文本节点的内容
    obj = xml.nodeValue.trim();
        obj = xml.nodeValue.trim()
  }
  return obj;
};
    return obj
}
/**
 * @description: XML转JSON
 * @param {string} xmlStr xml字符串
 * @return {*} string
 */
export const XMLToJSON = (xmlStr) => {
  const parser = new DOMParser();
  const xmlDoc = parser.parseFromString(xmlStr, 'text/xml');
  const xmlObj = deepParse(xmlDoc.documentElement);
export const XMLToJSON = xmlStr => {
    const parser = new DOMParser()
    const xmlDoc = parser.parseFromString(xmlStr, 'text/xml')
    const xmlObj = deepParse(xmlDoc.documentElement)
  if (Reflect.has(xmlObj, 'Document')) {
    return xmlObj;
        return xmlObj
  } else {
    return {
      Document: xmlObj,
    };
  }
};
    }
}
src/utils/cesium/mapUtil.js
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import * as turf from '@turf/turf';
import * as Cesium from 'cesium'
import * as turf from '@turf/turf'
export const getLngLatDistance = (lat1, lng1, lat2, lng2) => {
  const radLat1 = (lat1 * Math.PI) / 180.0
@@ -11,8 +11,8 @@
    Math.asin(
      Math.sqrt(
        Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2),
      ),
                    Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)
            )
    )
  s = s * 6378.137 // EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000
@@ -20,7 +20,7 @@
}
// 获取限polyline长度
export const getPolylineLength = (entity) => {
export const getPolylineLength = entity => {
  let length = 0
  // 获取Polyline的所有顶点位置
@@ -88,11 +88,7 @@
  // const distance = new Cesium.EllipsoidGeodesic(startCartesianPosition, endCartesianPosition, ellipsoid)
  // return distance
  const { longitude, latitude, height } = end
  const cartographic = Cesium.Cartographic.fromDegrees(
    longitude,
    latitude,
    height,
  )
    const cartographic = Cesium.Cartographic.fromDegrees(longitude, latitude, height)
  const cartesianPosition = ellipsoid.cartographicToCartesian(cartographic)
  const haeHeight = ellipsoid.cartesianToCartographic(cartesianPosition).height
  return haeHeight
@@ -102,10 +98,7 @@
export const cartesian3Convert = (cartesian3Position, viewer) => {
  // 转换为经纬度
  const ellipsoid = viewer.scene.globe.ellipsoid
  const cartographicPosition = Cesium.Cartographic.fromCartesian(
    cartesian3Position,
    ellipsoid,
  )
    const cartographicPosition = Cesium.Cartographic.fromCartesian(cartesian3Position, ellipsoid)
  const longitude = Cesium.Math.toDegrees(cartographicPosition.longitude)
  const latitude = Cesium.Math.toDegrees(cartographicPosition.latitude)
  const height = cartographicPosition.height
@@ -124,10 +117,7 @@
// Cesium Cartesian2 转正常经纬度
export const cartesian2Convert = (position, viewer) => {
  const ellipsoid = viewer.scene.globe.ellipsoid
  const c3Position = viewer.scene.globe.pick(
    viewer.camera.getPickRay(position),
    viewer.scene,
  )
    const c3Position = viewer.scene.globe.pick(viewer.camera.getPickRay(position), viewer.scene)
  const c2Postion = ellipsoid.cartesianToCartographic(c3Position)
  const longitude = Cesium.Math.toDegrees(c2Postion.longitude)
  const latitude = Cesium.Math.toDegrees(c2Postion.latitude)
@@ -136,11 +126,7 @@
// 根据经纬度获取距离
export const getLnglatDist = (lng1, lat1, lng2, lat2) => {
  const start = new Cesium.Cartesian3.fromDegrees(
    Number(lng1),
    Number(lat1),
    0,
  )
    const start = new Cesium.Cartesian3.fromDegrees(Number(lng1), Number(lat1), 0)
  const end = new Cesium.Cartesian3.fromDegrees(Number(lng2), Number(lat2), 0)
  return Cesium.Cartesian3.distance(start, end)
}
@@ -150,8 +136,8 @@
 * @param coordinateList {Array<Array<Object>>} [[{lat, lng}]]
 * @return { Object } {lat lng}
 */
export const getCenterPoint = (coordinateList) => {
  coordinateList = coordinateList.map((item) => {
export const getCenterPoint = coordinateList => {
    coordinateList = coordinateList.map(item => {
    const [lng, lat] = item
    return [{ lat, lng }]
  })
@@ -217,9 +203,7 @@
    const cartographic = Cesium.Cartographic.fromDegrees(longitude, latitude)
    // 获取地形数据的Promise
    const promise = Cesium.sampleTerrainMostDetailed(terrainProvider, [
      cartographic,
    ])
        const promise = Cesium.sampleTerrainMostDetailed(terrainProvider, [cartographic])
    // 使用 Cesium.when 处理 Promise
    promise
@@ -255,17 +239,14 @@
    const terrainProvider = viewer?.terrainProvider
    // 创建 Cartographic 对象
    const cartographics = data.map((item) => {
        const cartographics = data.map(item => {
      const [lng, lat] = item?.['Point']?.['coordinates']?.['#text'].split(',')
      return Cesium.Cartographic.fromDegrees(Number(lng), Number(lat))
    })
    // 获取地形数据的Promise
    const promise = Cesium.sampleTerrainMostDetailed(
      terrainProvider,
      cartographics,
    )
        const promise = Cesium.sampleTerrainMostDetailed(terrainProvider, cartographics)
    // 使用 Cesium.when 处理 Promise
    promise
@@ -275,7 +256,8 @@
          const longitude = Cesium.Math.toDegrees(item.longitude)
          const latitude = Cesium.Math.toDegrees(item.latitude)
          let FinalHeight = Number(data[index]?.['ellipsoidHeight']?.['#text']) + Number(item.height)
                    let FinalHeight =
                        Number(data[index]?.['ellipsoidHeight']?.['#text']) + Number(item.height)
          if (droneHeight) {
            FinalHeight = Number(data[index]?.['ellipsoidHeight']?.['#text']) + droneHeight
@@ -316,20 +298,15 @@
    const cesiumSamplePoints = []
    for (let i = 0; i < turfSamplePoints.features.length; i++) {
      const coord = turfSamplePoints.features[i].geometry.coordinates
      cesiumSamplePoints.push(
        Cesium.Cartographic.fromDegrees(coord[0], coord[1]),
      )
            cesiumSamplePoints.push(Cesium.Cartographic.fromDegrees(coord[0], coord[1]))
    }
    // 获取地形数据的Promise
    const promise = Cesium.sampleTerrainMostDetailed(
      terrainProvider,
      cesiumSamplePoints,
    )
        const promise = Cesium.sampleTerrainMostDetailed(terrainProvider, cesiumSamplePoints)
    promise
      .then(function (updatedPositions) {
        const newPosition = updatedPositions.map((item) => Number(item.height))
                const newPosition = updatedPositions.map(item => Number(item.height))
        resolve(Math.max(...newPosition))
      })
@@ -340,10 +317,10 @@
}
// 展示当前的高度
export const getWaylineShowHeight = (positions) => {
export const getWaylineShowHeight = positions => {
  const { lng, lat } = getCenterPoint(positions)
  let maxDist = 0
  positions.forEach((item) => {
    positions.forEach(item => {
    const [lng1, lat1] = item
    let pointsDist = getLnglatDist(lng1, lat1, lng, lat)
    if (pointsDist > maxDist) {
@@ -358,7 +335,7 @@
}
// 获取当前面是否有交叉点
export const isIntersection = (coordinates) => {
export const isIntersection = coordinates => {
  const polyDikuai = turf.polygon([coordinates])
  const result = turf.kinks(polyDikuai)
  const resultFeatures = result.features
src/utils/cesium/use-kmz-tsa.js
@@ -1,7 +1,7 @@
import _ from 'lodash';
import JSZIP from 'jszip';
import { JSONToXML } from './kmz';
import { getDateFromTimestamp } from '@/utils/date';
import _ from 'lodash'
import JSZIP from 'jszip'
import { JSONToXML } from './kmz'
import { getDateFromTimestamp } from '@/utils/date'
export default function kmzFile() {
  // 云台信息
@@ -12,20 +12,20 @@
    67: '1',
    80: '0',
    81: '1',
  };
    }
  // 创建图斑航线
  const create = async (waylineBasicInfo, lnglats, spotList) => {
    try {
      const date = new Date();
      const username = window.localStorage.getItem('bs_username');
      const updateTime = date.getTime();
      const fileName = '图斑航线规划_' + date.getTime();
            const date = new Date()
            const username = window.localStorage.getItem('bs_username')
            const updateTime = date.getTime()
            const fileName = '图斑航线规划_' + date.getTime()
      // 无人机机型、云台型号、航线高度
      const { droneEnumValue, payloadEnumValue, height } = waylineBasicInfo;
      const defaultHeight = height || 100;
            const { droneEnumValue, payloadEnumValue, height } = waylineBasicInfo
            const defaultHeight = height || 100
      // 起始点位 (参考点位-具体以机场为准)
      const startPoint = lnglats[0];
      const takeOffPoint = [startPoint[1], startPoint[0], 0].join(',');
            const startPoint = lnglats[0]
            const takeOffPoint = [startPoint[1], startPoint[0], 0].join(',')
      // template.xml对象模版
      const fileTemplate = {
        author: { '#text': username },
@@ -113,27 +113,25 @@
          //   imageFormat: { '#text': 'wide,zoom' },
          // },
        },
      };
            }
      // 航点创建
      const polygonNo = {
        no: '',
        index: 0,
      };
            }
      lnglats.forEach((lnglat, index) => {
        const obj = spotList.find((spot) =>
          spot.dkfw.find((item) => _.isEqual(item, lnglat)),
        );
        let fileSuffix = '';
                const obj = spotList.find(spot => spot.dkfw.find(item => _.isEqual(item, lnglat)))
                let fileSuffix = ''
        if (obj) {
          if (polygonNo.no === obj.dkbh) {
            polygonNo.index++;
                        polygonNo.index++
          } else {
            polygonNo.no = obj.dkbh;
            polygonNo.index = 1;
                        polygonNo.no = obj.dkbh
                        polygonNo.index = 1
          }
          fileSuffix = `图斑航线拍摄(${obj.dkbh}-${polygonNo.index})`;
                    fileSuffix = `图斑航线拍摄(${obj.dkbh}-${polygonNo.index})`
        } else {
          fileSuffix = '图斑航线拍摄(起点)';
                    fileSuffix = '图斑航线拍摄(起点)'
        }
        const placemark = {
          Point: {
@@ -191,40 +189,36 @@
              },
            },
          },
        };
        fileTemplate.Folder.Placemark.push(placemark);
      });
      const fileWaylines = waylinesContext(fileTemplate);
                }
                fileTemplate.Folder.Placemark.push(placemark)
            })
            const fileWaylines = waylinesContext(fileTemplate)
      return {
        fileName,
        template: fileTemplate,
        waylines: fileWaylines,
      };
    } catch (error) {
      console.log(error);
      return false;
    }
  };
        } catch (error) {
            console.log(error)
            return false
        }
    }
  // 创建正常航线
  const createNoramlWaylines = (waylineBasicInfo, lnglats) => {
    try {
      const date = new Date();
      const username = window.localStorage.getItem('bs_username');
      const updateTime = date.getTime();
      const { year, month, day, hours, minutes } =
        getDateFromTimestamp(updateTime);
      const fileName = '新建航线_' + year + month + day + hours + minutes;
            const date = new Date()
            const username = window.localStorage.getItem('bs_username')
            const updateTime = date.getTime()
            const { year, month, day, hours, minutes } = getDateFromTimestamp(updateTime)
            const fileName = '新建航线_' + year + month + day + hours + minutes
      // 无人机机型、云台型号、航线高度
      const { droneEnumValue, payloadEnumValue, height, waylineName } =
        waylineBasicInfo;
      const defaultHeight = height || 100;
            const { droneEnumValue, payloadEnumValue, height, waylineName } = waylineBasicInfo
            const defaultHeight = height || 100
      // 起始点位 (参考点位-具体以机场为准)
      const startPoint = lnglats[0];
      const takeOffPoint = [startPoint.latitude, startPoint.longitude, 0].join(
        ',',
      );
            const startPoint = lnglats[0]
            const takeOffPoint = [startPoint.latitude, startPoint.longitude, 0].join(',')
      // template.xml对象模版
      const fileTemplate = {
        author: { '#text': username },
@@ -317,7 +311,7 @@
            imageFormat: { '#text': 'wide,zoom' },
          },
        },
      };
            }
      lnglats.forEach((lnglat, index) => {
        const placemark = {
          Point: {
@@ -357,7 +351,7 @@
          useGlobalHeadingParam: { '#text': 1 },
          useGlobalTurnParam: { '#text': 1 },
          useStraightLine: { '#text': 1 },
        };
                }
        if (lnglat?.actions) {
          const actionGroup = {
            actionGroupId: { '#text': index },
@@ -374,13 +368,13 @@
            //   actionActuatorFuncParam: {},
            // }],
            action: [],
          };
                    }
          lnglat?.actions.forEach((action, index) => {
            const singleAction = {
              actionId: { '#text': index },
              actionActuatorFunc: { '#text': '' },
              actionActuatorFuncParam: {},
            };
                        }
            // actionGroup.action['actionActuatorFunc'] = { '#text': action.key }
            // action.params.forEach(p => {
            //   if (p.value || p.value !== '') {
@@ -389,69 +383,66 @@
            // })
            singleAction['actionActuatorFunc'] = {
              '#text': action.key,
            };
            action.params.forEach((p) => {
                        }
                        action.params.forEach(p => {
              if (p.value || p.value !== '') {
                singleAction['actionActuatorFuncParam'][p.key] = {
                  '#text': p.value,
                };
              }
            });
                            }
                        })
            if (lnglat?.actions.length > 1) {
              actionGroup.action.push(singleAction);
                            actionGroup.action.push(singleAction)
            } else {
              actionGroup.action = singleAction;
                            actionGroup.action = singleAction
            }
          });
          placemark.actionGroup = actionGroup;
                    })
                    placemark.actionGroup = actionGroup
        }
        fileTemplate.Folder.Placemark.push(placemark);
      });
      const fileWaylines = waylinesContext(fileTemplate);
                fileTemplate.Folder.Placemark.push(placemark)
            })
            const fileWaylines = waylinesContext(fileTemplate)
      return {
        fileName: waylineName || fileName,
        template: fileTemplate,
        waylines: fileWaylines,
      };
    } catch (error) {
      console.log(error);
      return error;
    }
  };
        } catch (error) {
            console.log(error)
            return error
        }
    }
  // 创建面状航线
  const createPlanarWayline = (waylineBasicInfo, lnglats) => {};
    const createPlanarWayline = (waylineBasicInfo, lnglats) => {}
  // 创建点状航线
  const createPointWayLines = (
    waylineBasicInfo,
    points,
    settingInfo,
    dockPosition,
  ) => {
    const createPointWayLines = (waylineBasicInfo, points, settingInfo, dockPosition) => {
    try {
      const { droneEnumValue, payloadEnumValue, waylineName } =
        waylineBasicInfo;
            const { droneEnumValue, payloadEnumValue, waylineName } = waylineBasicInfo
      const { imageFormat, heightMode, globalHeight, autoFlightSpeed,gimbalPitchMode,
        waypointTurnMode,waypointHeadingMode,finishAction,globalTransitionalSpeed  } =
        settingInfo;
            const {
                imageFormat,
                heightMode,
                globalHeight,
                autoFlightSpeed,
                gimbalPitchMode,
                waypointTurnMode,
                waypointHeadingMode,
                finishAction,
                globalTransitionalSpeed,
            } = settingInfo
      const date = new Date();
      const username = window.localStorage.getItem('bs_username');
      const updateTime = date.getTime();
      const { year, month, day, hours, minutes } =
        getDateFromTimestamp(updateTime);
      const fileName = '新建航线_' + year + month + day + hours + minutes;
            const date = new Date()
            const username = window.localStorage.getItem('bs_username')
            const updateTime = date.getTime()
            const { year, month, day, hours, minutes } = getDateFromTimestamp(updateTime)
            const fileName = '新建航线_' + year + month + day + hours + minutes
      // 无人机机型、云台型号、航线高度
      const defaultHeight = 100;
            const defaultHeight = 100
      // 起始点位 (参考点位-具体以机场为准)
      const takeOffPoint = [
        dockPosition.latitude,
        dockPosition.longitude,
        0,
      ].join(',');
            const takeOffPoint = [dockPosition.latitude, dockPosition.longitude, 0].join(',')
      // template.xml对象模版
      const fileTemplate = {
@@ -545,10 +536,10 @@
            imageFormat: imageFormat,
          },
        },
      };
            }
      points.length &&
        points.forEach((detail, ind) => {
          const { Point, index, height, ellipsoidHeight, actionGroup,waypointSpeed } = detail;
                    const { Point, index, height, ellipsoidHeight, actionGroup, waypointSpeed } = detail
          const placemark = {
            Point,
@@ -562,7 +553,9 @@
            waypointSpeed: { '#text': waypointSpeed ||  10 },
            // 沿航线方向 - 可使用当前默认值
            waypointHeadingParam: {
              waypointHeadingMode: { '#text': waypointHeadingMode || 'followWayline' },
                            waypointHeadingMode: {
                                '#text': waypointHeadingMode || 'followWayline',
                            },
              waypointHeadingAngle: { '#text': 0 },
              waypointPoiPoint: {
                '#text': '0.000000,0.000000,0.000000',
@@ -583,39 +576,39 @@
            useGlobalHeadingParam: { '#text': 1 },
            useGlobalTurnParam: { '#text': 1 },
            useStraightLine: { '#text': 1 },
          };
                    }
          if (actionGroup) {
            placemark.actionGroup = actionGroup;
                        placemark.actionGroup = actionGroup
          }
          fileTemplate.Folder.Placemark.push(placemark);
        });
                    fileTemplate.Folder.Placemark.push(placemark)
                })
      const fileWaylines = waylinesContext(fileTemplate);
            const fileWaylines = waylinesContext(fileTemplate)
      return {
        fileName: waylineName || fileName,
        template: fileTemplate,
        waylines: fileWaylines,
      };
    } catch (error) {
      console.log(error);
      return error;
    }
  };
        } catch (error) {
            console.log(error)
            return error
        }
    }
  const save = async (fileInfo) => {
    const JsZip = new JSZIP();
    const { fileName, template, waylines } = fileInfo;
    const templateXml = JSONToXML(template, '', true);
    const waylinesWpml = JSONToXML(waylines, '', true);
    JsZip.file('wpmz/template.kml', templateXml);
    JsZip.file('wpmz/waylines.wpml', waylinesWpml);
    const fileBlob = await JsZip.generateAsync({ type: 'blob' });
    const save = async fileInfo => {
        const JsZip = new JSZIP()
        const { fileName, template, waylines } = fileInfo
        const templateXml = JSONToXML(template, '', true)
        const waylinesWpml = JSONToXML(waylines, '', true)
        JsZip.file('wpmz/template.kml', templateXml)
        JsZip.file('wpmz/waylines.wpml', waylinesWpml)
        const fileBlob = await JsZip.generateAsync({ type: 'blob' })
    // saveAs(kmzFile, `${fileName}.kmz`)
    return fileBlob;
  };
        return fileBlob
    }
  const waylinesContext = (templateJson) => {
    const waylinesContext = templateJson => {
    const waylinesObj = {
      // 标准模版
      missionConfig: {
@@ -642,38 +635,35 @@
        */
        Placemark: null,
      },
    };
    Object.keys(waylinesObj).forEach((key) => {
      if (
        Object.prototype.toString.call(waylinesObj[key]) === '[object Object]'
      ) {
        Object.keys(waylinesObj[key]).forEach((item) => {
          waylinesObj[key][item] = templateJson[key][item];
        }
        Object.keys(waylinesObj).forEach(key => {
            if (Object.prototype.toString.call(waylinesObj[key]) === '[object Object]') {
                Object.keys(waylinesObj[key]).forEach(item => {
                    waylinesObj[key][item] = templateJson[key][item]
          if (item === 'executeHeightMode') {
            waylinesObj[key][item] =
              templateJson[key].waylineCoordinateSysParam.heightMode;
                        waylinesObj[key][item] = templateJson[key].waylineCoordinateSysParam.heightMode
          }
          if (item === 'waylineId') {
            waylinesObj[key][item] = templateJson[key].templateId;
                        waylinesObj[key][item] = templateJson[key].templateId
          }
          if (item === 'Placemark') {
            const placemarks = _.cloneDeep(templateJson[key][item]);
            placemarks.forEach((placemark) => {
                        const placemarks = _.cloneDeep(templateJson[key][item])
                        placemarks.forEach(placemark => {
              placemark.executeHeight = {
                '#text': placemark.ellipsoidHeight?.['#text'] || '',
              };
              delete placemark.ellipsoidHeight;
              delete placemark.height;
            });
            waylinesObj[key][item] = placemarks;
          }
        });
                            delete placemark.ellipsoidHeight
                            delete placemark.height
                        })
                        waylinesObj[key][item] = placemarks
                    }
                })
      } else {
        waylinesObj[key] = templateJson[key];
                waylinesObj[key] = templateJson[key]
      }
    });
    return waylinesObj;
  };
        })
        return waylinesObj
    }
  return {
    create,
@@ -681,5 +671,5 @@
    createPlanarWayline,
    createPointWayLines,
    save,
  };
    }
}
src/utils/crypto.js
@@ -1,21 +1,21 @@
import CryptoJS from 'crypto-js';
import CryptoJS from 'crypto-js'
export default class crypto {
  /**
   * token加密key 使用@org.springblade.test.CryptoKeyGenerator获取,需和后端配置保持一致
   * @type {string}
   */
  static cryptoKey = '请配置cryptoKey';
    static cryptoKey = '请配置cryptoKey'
  /**
   * 报文加密key 使用@org.springblade.test.CryptoKeyGenerator获取,需和后端配置保持一致
   * @type {string}
   */
  static aesKey = '请配置aesKey';
    static aesKey = '请配置aesKey'
  /**
   * 报文加密key 使用@org.springblade.test.CryptoKeyGenerator获取,需和后端配置保持一致
   * @type {string}
   */
  static desKey = '请配置desKey';
    static desKey = '请配置desKey'
  /**
   * aes 加密方法
@@ -23,7 +23,7 @@
   * @returns {*}
   */
  static encrypt(data) {
    return this.encryptAES(data, this.aesKey);
        return this.encryptAES(data, this.aesKey)
  }
  /**
@@ -32,53 +32,53 @@
   * @returns {*}
   */
  static decrypt(data) {
    return this.decryptAES(data, this.aesKey);
        return this.decryptAES(data, this.aesKey)
  }
  /**
   * aes 加密方法,同java:AesUtil.encryptToBase64(text, aesKey);
   */
  static encryptAES(data, key) {
    const dataBytes = CryptoJS.enc.Utf8.parse(data);
    const keyBytes = CryptoJS.enc.Utf8.parse(key);
        const dataBytes = CryptoJS.enc.Utf8.parse(data)
        const keyBytes = CryptoJS.enc.Utf8.parse(key)
    const encrypted = CryptoJS.AES.encrypt(dataBytes, keyBytes, {
      iv: keyBytes,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
        })
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext)
  }
  /**
   * aes 解密方法,同java:AesUtil.decryptFormBase64ToString(encrypt, aesKey);
   */
  static decryptAES(data, key) {
    const keyBytes = CryptoJS.enc.Utf8.parse(key);
        const keyBytes = CryptoJS.enc.Utf8.parse(key)
    const decrypted = CryptoJS.AES.decrypt(data, keyBytes, {
      iv: keyBytes,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7,
    });
    return CryptoJS.enc.Utf8.stringify(decrypted);
        })
        return CryptoJS.enc.Utf8.stringify(decrypted)
  }
  /**
   * des 加密方法,同java:DesUtil.encryptToBase64(text, desKey)
   */
  static encryptDES(data, key) {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
        const keyHex = CryptoJS.enc.Utf8.parse(key)
    const encrypted = CryptoJS.DES.encrypt(data, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return encrypted.toString();
        })
        return encrypted.toString()
  }
  /**
   * des 解密方法,同java:DesUtil.decryptFormBase64(encryptBase64, desKey);
   */
  static decryptDES(data, key) {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
        const keyHex = CryptoJS.enc.Utf8.parse(key)
    const decrypted = CryptoJS.DES.decrypt(
      {
        ciphertext: CryptoJS.enc.Base64.parse(data),
@@ -88,7 +88,7 @@
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7,
      }
    );
    return decrypted.toString(CryptoJS.enc.Utf8);
        )
        return decrypted.toString(CryptoJS.enc.Utf8)
  }
}
src/utils/date.js
@@ -1,16 +1,16 @@
export const calcDate = (date1, date2) => {
  let date3 = date2 - date1;
    let date3 = date2 - date1
  let days = Math.floor(date3 / (24 * 3600 * 1000));
    let days = Math.floor(date3 / (24 * 3600 * 1000))
  let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  let hours = Math.floor(leave1 / (3600 * 1000));
    let leave1 = date3 % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    let hours = Math.floor(leave1 / (3600 * 1000))
  let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  let minutes = Math.floor(leave2 / (60 * 1000));
    let leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    let minutes = Math.floor(leave2 / (60 * 1000))
  let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  let seconds = Math.round(date3 / 1000);
    let leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    let seconds = Math.round(date3 / 1000)
  return {
    leave1,
    leave2,
@@ -19,14 +19,14 @@
    hours: hours,
    minutes: minutes,
    seconds: seconds,
  };
};
    }
}
/**
 * 日期格式化
 */
export function dateFormat(date, format) {
  format = format || 'yyyy-MM-dd hh:mm:ss';
    format = format || 'yyyy-MM-dd hh:mm:ss'
  if (date !== 'Invalid Date') {
    let o = {
      'M+': date.getMonth() + 1, //month
@@ -36,23 +36,23 @@
      's+': date.getSeconds(), //second
      'q+': Math.floor((date.getMonth() + 3) / 3), //quarter
      S: date.getMilliseconds(), //millisecond
    };
        }
    if (/(y+)/.test(format))
      format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
            format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (let k in o)
      if (new RegExp('(' + k + ')').test(format))
        format = format.replace(
          RegExp.$1,
          RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length)
        );
    return format;
                )
        return format
  }
  return '';
    return ''
}
/**
 * 当前时间戳
 */
export function dateNow() {
  return dateFormat(new Date(), 'yyyyMMddhhmmss');
    return dateFormat(new Date(), 'yyyyMMddhhmmss')
}
src/utils/flow.js
@@ -4,7 +4,7 @@
 * @returns {string}
 */
export function flowCategory(category) {
  return `flow_${category}`;
    return `flow_${category}`
}
/**
@@ -14,7 +14,7 @@
 */
export function flowRoute(routes, key) {
  const data = routes.filter(d => {
    return d.routeKey === key;
  });
  return data.length === 0 ? [] : data[0].routeValue;
        return d.routeKey === key
    })
    return data.length === 0 ? [] : data[0].routeValue
}
src/utils/formatter.js
@@ -1,4 +1,4 @@
import {validatenull} from "@/utils/validate";
import { validatenull } from '@/utils/validate'
/**
 * 格式化工具类
@@ -8,32 +8,35 @@
    try {
      // 为空则返回空
      if (validatenull(str)) {
        return '';
                return ''
      }
      // 解析并格式化JSON字符串
      str = JSON.stringify(JSON.parse(str), null, 2);
            str = JSON.stringify(JSON.parse(str), null, 2)
      // 使用HTML实体进行替换(不改变&符号)
      str = str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
            str = str.replace(/</g, '&lt;').replace(/>/g, '&gt;')
      // 返回格式化的字符串,并添加样式类
      return str.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        let cls = 'number';
            return str.replace(
                /("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
                function (match) {
                    let cls = 'number'
        if (/^"/.test(match)) {
          if (/:$/.test(match)) {
            cls = 'key';
                            cls = 'key'
          } else {
            cls = 'string';
                            cls = 'string'
          }
        } else if (/true|false/.test(match)) {
          cls = 'boolean';
                        cls = 'boolean'
        } else if (/null/.test(match)) {
          cls = 'null';
                        cls = 'null'
        }
        return match;
      });
                    return match
                }
            )
    } catch (e) {
      return str;
            return str
    }
  }
}
src/utils/func.js
@@ -8,7 +8,7 @@
   * @returns {boolean}
   */
  static notEmpty(val) {
    return !this.isEmpty(val);
        return !this.isEmpty(val)
  }
  /**
@@ -17,7 +17,7 @@
   * @returns {boolean}
   */
  static isUndefined(val) {
    return val === null || typeof val === 'undefined';
        return val === null || typeof val === 'undefined'
  }
  /**
@@ -31,9 +31,9 @@
      typeof val === 'undefined' ||
      (typeof val === 'string' && val === '' && val !== 'undefined')
    ) {
      return true;
            return true
    }
    return false;
        return false
  }
  /**
@@ -44,10 +44,10 @@
   */
  static toInt(val, defaultValue) {
    if (this.isEmpty(val)) {
      return defaultValue === undefined ? -1 : defaultValue;
            return defaultValue === undefined ? -1 : defaultValue
    }
    const num = parseInt(val, 0);
    return Number.isNaN(num) ? (defaultValue === undefined ? -1 : defaultValue) : num;
        const num = parseInt(val, 0)
        return Number.isNaN(num) ? (defaultValue === undefined ? -1 : defaultValue) : num
  }
  /**
@@ -56,10 +56,10 @@
   */
  static toNumber(val) {
    if (this.isEmpty(val)) {
      return '';
            return ''
    }
    const num = parseFloat(val);
    return Number.isNaN(num) ? val : num;
        const num = parseFloat(val)
        return Number.isNaN(num) ? val : num
  }
  /**
@@ -68,11 +68,11 @@
   * @returns {FormData}
   */
  static toFormData(obj) {
    const data = new FormData();
        const data = new FormData()
    Object.keys(obj).forEach(key => {
      data.append(key, Array.isArray(obj[key]) ? obj[key].join(',') : obj[key]);
    });
    return data;
            data.append(key, Array.isArray(obj[key]) ? obj[key].join(',') : obj[key])
        })
        return data
  }
  /**
@@ -82,7 +82,7 @@
   * @returns {null}
   */
  static format(date, format = 'YYYY-MM-DD HH:mm:ss') {
    return date ? date.format(format) : null;
        return date ? date.format(format) : null
  }
  /**
@@ -91,7 +91,7 @@
   * @returns {string}
   */
  static formatDateTime(timestamp) {
    return this.formatDate(new Date(timestamp));
        return this.formatDate(new Date(timestamp))
  }
  /**
@@ -100,16 +100,16 @@
   * @returns {string}
   */
  static formatDate(date) {
    const pad = num => (num < 10 ? '0' + num : num);
        const pad = num => (num < 10 ? '0' + num : num)
    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1); // 月份从0开始,所以+1
    const day = pad(date.getDate());
    const hour = pad(date.getHours());
    const minute = pad(date.getMinutes());
    const second = pad(date.getSeconds());
        const year = date.getFullYear()
        const month = pad(date.getMonth() + 1) // 月份从0开始,所以+1
        const day = pad(date.getDate())
        const hour = pad(date.getHours())
        const minute = pad(date.getMinutes())
        const second = pad(date.getSeconds())
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  }
  /**
@@ -118,9 +118,9 @@
   * @returns {string}
   */
  static toLocalISOString(datetime) {
    let timezoneOffset = datetime.getTimezoneOffset() * 60000; // 获取当前时区与UTC的时间差(以毫秒为单位)
    let localDatetime = new Date(datetime - timezoneOffset); // 调整时间,得到当前时区时间
    return localDatetime.toISOString();
        let timezoneOffset = datetime.getTimezoneOffset() * 60000 // 获取当前时区与UTC的时间差(以毫秒为单位)
        let localDatetime = new Date(datetime - timezoneOffset) // 调整时间,得到当前时区时间
        return localDatetime.toISOString()
  }
  /**
@@ -129,7 +129,7 @@
   * @returns {string}
   */
  static join(arr) {
    return Array.isArray(arr) ? arr.join(',') : arr;
        return Array.isArray(arr) ? arr.join(',') : arr
  }
  /**
@@ -138,7 +138,7 @@
   * @returns {string}
   */
  static split(str) {
    return str ? String(str).split(',') : '';
        return str ? String(str).split(',') : ''
  }
  /**
@@ -148,9 +148,9 @@
   */
  static toStr(str) {
    if (typeof str === 'undefined' || str === null) {
      return '';
            return ''
    }
    return str;
        return str
  }
  /**
@@ -159,7 +159,7 @@
   * @returns {boolean}
   */
  static isArrayAndNotEmpty(param) {
    return Array.isArray(param) && param.length > 0;
        return Array.isArray(param) && param.length > 0
  }
  /**
@@ -168,11 +168,11 @@
   * @returns {*|string}
   */
  static formatUrl(url) {
    if (!url) return url;
        if (!url) return url
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url;
            return url
    } else {
      return `http://${url}`;
            return `http://${url}`
    }
  }
@@ -182,8 +182,8 @@
   * @returns {string}
   */
  static bytesToKB(bytes) {
    const kb = bytes / 1024;
    return kb.toFixed(2);
        const kb = bytes / 1024
        return kb.toFixed(2)
  }
  /**
@@ -193,9 +193,9 @@
   */
  static jsonArrayToKeyValue(jsonArray) {
    if (this.isEmpty(jsonArray)) {
      return '';
            return ''
    }
    return jsonArray.map(item => `${item.enumKey}:${item.enumValue}`).join(';');
        return jsonArray.map(item => `${item.enumKey}:${item.enumValue}`).join(';')
  }
  /**
@@ -205,16 +205,16 @@
   */
  static keyValueToJsonArray(keyValue) {
    if (this.isEmpty(keyValue)) {
      return [];
            return []
    }
    return keyValue.split(';').map((kv, index) => {
      const [key, value] = kv.split(':');
            const [key, value] = kv.split(':')
      return {
        id: index,
        enumKey: key,
        enumValue: value,
      };
    });
            }
        })
  }
  /**
@@ -226,9 +226,9 @@
  static contains(str, val) {
    // 检查str是否为字符串且不为空
    if (typeof str === 'string' && str.length > 0) {
      return str.includes(val);
            return str.includes(val)
    }
    return false;
        return false
  }
  /**
@@ -239,9 +239,9 @@
   */
  static truncateString(str, len = 20) {
    if (str.length > len) {
      return str.slice(0, len) + '...';
            return str.slice(0, len) + '...'
    }
    return str;
        return str
  }
  /**
@@ -250,7 +250,7 @@
   * @returns {*}
   */
  static camelCaseString(str) {
    return str.replace(/_([a-z])/g, g => g[1].toUpperCase());
        return str.replace(/_([a-z])/g, g => g[1].toUpperCase())
  }
  /**
@@ -259,15 +259,15 @@
   * @returns {string}
   */
  static strGenerate(length) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    const maxLength = 256;
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
        const maxLength = 256
    if (length > maxLength) {
      throw new Error(`长度最大值不能超过 ${maxLength}`);
            throw new Error(`长度最大值不能超过 ${maxLength}`)
    }
    return Array.from({ length }, () =>
      characters.charAt(Math.floor(Math.random() * characters.length))
    ).join('');
        ).join('')
  }
  /**
@@ -277,9 +277,9 @@
  static generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (Math.random() * 16) | 0,
        v = c === 'x' ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    });
                v = c === 'x' ? r : (r & 0x3) | 0x8
            return v.toString(16)
        })
  }
  /**
@@ -292,7 +292,7 @@
      Object.entries(obj).filter(
        ([, value]) => value !== '' && value !== null && value !== undefined
      )
    );
        )
  }
  /**
@@ -302,9 +302,9 @@
   */
  static getUserTenantId(userInfo) {
    if (userInfo && userInfo.tenant_id) {
      return userInfo.tenant_id;
            return userInfo.tenant_id
    } else if (userInfo && userInfo.tenantId) {
      return userInfo.tenantId;
            return userInfo.tenantId
    }
  }
}
src/utils/http/config.js
@@ -18,7 +18,10 @@
  // livestreaming
  // RTMP  Note: This IP is the address of the streaming server. If you want to see livestream on web page, you need to convert the RTMP stream to WebRTC stream.
  // rtmpURL: 'rtmp://www.yb.zhbhd.top:30005/uav/', // Example: 'rtmp://192.168.1.1/live/'
  rtmpURL: import.meta.env.VITE_APP_ENV === 'production'?'rtmp://101.132.85.201/live/':'rtmp://139.196.74.78/live/',
    rtmpURL:
        import.meta.env.VITE_APP_ENV === 'production'
            ? 'rtmp://101.132.85.201/live/'
            : 'rtmp://139.196.74.78/live/',
  rtmpURL2: 'rtmp://www.ainfo.top:735/uav/', // Example: 'rtmp://192.168.1.1/live/'
  // GB28181 Note:If you don't know what these parameters mean, you can go to Pilot2 and select the GB28181 page in the cloud platform. Where the parameters same as these parameters.
  // gbServerIp: '171.34.76.175',
@@ -49,4 +52,4 @@
  // You can apply on the AMap website.
  amapKey: '5221d3ca929a7bf59c301be186c03791',
  amapSearchKey: '6c3ea75b215f0c0efcbcfdf13273991b',
};
}
src/utils/http/enums.js
@@ -11,4 +11,4 @@
  Device: 'bs_device',
  GatewayOnline: 'bs_gateway_online',
  UserInfo: 'bs_user_info',
};
}
src/utils/module.js
@@ -1,39 +1,39 @@
let flowInstance = null;
let formInstance = null;
let formDesignInstance = null;
let flowInstance = null
let formInstance = null
let formDesignInstance = null
export function loadFlowModule(app) {
  if (!flowInstance) {
    flowInstance = import('@saber/nf-design-base-elp')
      .then(module => {
        app.use(module.default);
        return module;
                app.use(module.default)
                return module
      })
      .catch(error => console.error('failed to load module:', error));
            .catch(error => console.error('failed to load module:', error))
  }
  return flowInstance;
    return flowInstance
}
export function loadFormModule(app) {
  if (!formInstance) {
    formInstance = import('@saber/nf-form-elp')
      .then(module => {
        app.use(module.default);
        return module;
                app.use(module.default)
                return module
      })
      .catch(error => console.error('failed to load module:', error));
            .catch(error => console.error('failed to load module:', error))
  }
  return formInstance;
    return formInstance
}
export function loadFormDesignModule(app) {
  if (!formDesignInstance) {
    formDesignInstance = import('@saber/nf-form-design-elp')
      .then(module => {
        app.use(module.default);
        return module;
                app.use(module.default)
                return module
      })
      .catch(error => console.error('failed to load module:', error));
            .catch(error => console.error('failed to load module:', error))
  }
  return formDesignInstance;
    return formDesignInstance
}
src/utils/rem.js
@@ -8,6 +8,5 @@
}
export const pxToRem = width => {
    return width * 0.1 + 'rem';
};
    return width * 0.1 + 'rem'
}
src/utils/sensitive.js
@@ -6,8 +6,8 @@
   * @returns {Object} 敏感数据管理器实例
   */
  create(config = {}) {
    const sensitiveFields = config.fields || [];
    let initialMaskedData = {};
        const sensitiveFields = config.fields || []
        let initialMaskedData = {}
    return {
      /**
@@ -15,12 +15,12 @@
       * @param {Object} data 包含脱敏数据的对象
       */
      saveInitialData(data) {
        initialMaskedData = {};
                initialMaskedData = {}
        sensitiveFields.forEach(field => {
          if (data[field]) {
            initialMaskedData[field] = data[field];
                        initialMaskedData[field] = data[field]
          }
        });
                })
      },
      /**
@@ -29,16 +29,16 @@
       * @returns {Object} 过滤后的提交数据
       */
      getSubmitData(formData) {
        const submitData = { ...formData };
                const submitData = { ...formData }
        sensitiveFields.forEach(field => {
          // 如果敏感字段的值与初始值相同,删除该字段
          if (submitData[field] === initialMaskedData[field]) {
            delete submitData[field];
                        delete submitData[field]
          }
        });
                })
        return submitData;
                return submitData
      },
      /**
@@ -46,7 +46,7 @@
       * @param {Object} newMaskedData 新的脱敏数据
       */
      updateMaskedData(newMaskedData) {
        Object.assign(initialMaskedData, newMaskedData);
                Object.assign(initialMaskedData, newMaskedData)
      },
      /**
@@ -54,7 +54,7 @@
       * @returns {boolean}
       */
      isModified(formData) {
        return sensitiveFields.some(field => formData[field] !== initialMaskedData[field]);
                return sensitiveFields.some(field => formData[field] !== initialMaskedData[field])
      },
      /**
@@ -62,7 +62,7 @@
       * @returns {Array}
       */
      getModifiedFields(formData) {
        return sensitiveFields.filter(field => formData[field] !== initialMaskedData[field]);
                return sensitiveFields.filter(field => formData[field] !== initialMaskedData[field])
      },
      /**
@@ -72,10 +72,10 @@
      reset(formData) {
        sensitiveFields.forEach(field => {
          if (initialMaskedData[field]) {
            formData[field] = initialMaskedData[field];
                        formData[field] = initialMaskedData[field]
          }
        });
                })
      },
    };
        }
  },
};
}
src/utils/sm2.js
@@ -1,5 +1,5 @@
import website from '@/config/website';
import smCrypto from 'sm-crypto';
import website from '@/config/website'
import smCrypto from 'sm-crypto'
/**
 * sm2 加密方法
@@ -8,8 +8,8 @@
 */
export function encrypt(data) {
  try {
    return smCrypto.sm2.doEncrypt(data, website.oauth2.publicKey, 0);
        return smCrypto.sm2.doEncrypt(data, website.oauth2.publicKey, 0)
  } catch {
    return '';
        return ''
  }
}
src/utils/staticData/device.js
@@ -6,7 +6,7 @@
  PAYLOAD: '1', // 负载
  RC: '2', // 遥控
  DOCK: '3', // 机场
};
}
// 设备sub_type 从0升序
export const DEVICE_SUB_TYPE = {
@@ -15,7 +15,7 @@
  TWO: 2,
  THREE: 3,
  UNKNOWN: 65535,
};
}
// DJI飞机类型
export const DRONE_TYPE = {
@@ -23,7 +23,7 @@
  M300: 60,
  Mavic3EnterpriseAdvanced: 77,
  M350: 89,
};
}
// DJI负载类型枚举值
export const PAYLOAD_TYPE = {
@@ -42,18 +42,18 @@
  M3E: 66,
  M3T: 67,
  // UNKNOWN = 65535
};
}
// RC type
export const RC_TYPE = {
  RC: 56,
  RCPlus: 119,
  RC144: 144,
};
}
// DOCK type
export const DOCK_TYPE = {
  Dock: 1,
};
}
export const DEVICE_MODEL_KEY = {
  M30: `${DOMAIN.DRONE}-${DRONE_TYPE.M30}-${DEVICE_SUB_TYPE.ZERO}`,
  M30T: `${DOMAIN.DRONE}-${DRONE_TYPE.M30}-${DEVICE_SUB_TYPE.ONE}`,
@@ -78,7 +78,7 @@
  RC: `${DOMAIN.RC}-${RC_TYPE.RC}-${DEVICE_SUB_TYPE.ZERO}`,
  RCPlus: `${DOMAIN.RC}-${RC_TYPE.RCPlus}-${DEVICE_SUB_TYPE.ZERO}`,
  Dock: `${DOMAIN.DOCK}-${DOCK_TYPE.Dock}-${DEVICE_SUB_TYPE.ZERO}`,
};
}
export const DEVICE_NAME = {
  // drone
@@ -113,12 +113,12 @@
  // dock
  [DEVICE_MODEL_KEY.Dock]: 'Dock',
};
}
export const ControlSource = {
  A: 'A',
  B: 'B',
};
}
export const RainfallEnum = {
  正常: 0,
@@ -129,14 +129,14 @@
  1: '小雨',
  2: '中雨',
  3: '大雨',
};
}
export const DroneInDockEnum = {
  舱外: 0,
  舱内: 1,
  0: '舱外',
  1: '舱内',
};
}
export const EModeText = {
  待机: 0,
@@ -175,7 +175,7 @@
  15: 'APAS',
  16: '虚拟摇杆状态',
  17: '指令飞行',
};
}
export const EModeCode = {
  Standby: 0,
@@ -193,7 +193,7 @@
  Three_Blades_Landing: 12,
  Upgrading: 13,
  Disconnected: 14,
};
}
export const EGear = {
  A: 0,
@@ -216,7 +216,7 @@
  7: 'M',
  8: 'G',
  9: 'T',
};
}
export const EDeviceType = {
  M30: '0-67-0',
@@ -241,8 +241,8 @@
  M3E_Camera: '1-66-0',
  M3T_Camera: '0-67-1',
  M3D_Camera: '1-80-0',
  M3TD_Camera: '1-81-0'
};
    M3TD_Camera: '1-81-0',
}
export const EDockModeText = {
  已断开连接: -1,
@@ -257,7 +257,7 @@
  2: '远程调试',
  3: '固件升级中',
  4: '设备工作中',
};
}
export const EDockModeCode = {
  Disconnected: '-1',
@@ -272,4 +272,4 @@
  2: 'Remote_Debugging',
  3: 'Upgrading',
  4: 'Working',
};
}
src/utils/staticData/enums.js
@@ -1,4 +1,4 @@
export const ERouterName = {};
export const ERouterName = {}
export const ELocalStorageKey = {
  Username: 'username',
@@ -12,7 +12,7 @@
  Device: 'device',
  GatewayOnline: 'gateway_online',
  UserInfo: 'user_info',
};
}
export const EBizCode = {
  GatewayOsd: 'gateway_osd',
@@ -61,7 +61,7 @@
  TakeoffToPointProgress: 'takeoff_to_point_progress', // 一键起飞
  JoystickInvalidNotify: 'joystick_invalid_notify', // 设备端退出drc模式
  DrcStatusNotify: 'drc_status_notify', // 飞行控制模式状态
};
}
export const EBizCodeMessage = {
  [EBizCode.DeviceOnline]: '设备在线',
@@ -93,13 +93,13 @@
  [EBizCode.TakeoffToPointProgress]: '一键起飞',
  [EBizCode.DrcStatusNotify]: '飞行控制模式状态',
  [EBizCode.JoystickInvalidNotify]: '设备端退出drc模式',
};
}
export const EDeviceTypeName = {
  Aircraft: 0,
  Gateway: 2,
  Dock: 3,
};
}
export const EHmsLevel = {
  NOTICE: 0,
@@ -108,4 +108,4 @@
  0: 'NOTICE',
  1: 'CAUTION',
  2: 'WARN',
};
}
src/utils/store.js
@@ -1,72 +1,72 @@
import { validatenull } from 'utils/validate';
import website from '@/config/website';
import { validatenull } from 'utils/validate'
import website from '@/config/website'
const keyName = website.key + '-';
const keyName = website.key + '-'
/**
 * 存储localStorage
 */
export const setStore = (params = {}) => {
  let { name, content, type } = params;
  name = keyName + name;
    let { name, content, type } = params
    name = keyName + name
  let obj = {
    dataType: typeof content,
    content: content,
    type: type,
    datetime: new Date().getTime(),
  };
  if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
  else window.localStorage.setItem(name, JSON.stringify(obj));
};
    }
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj))
    else window.localStorage.setItem(name, JSON.stringify(obj))
}
/**
 * 获取localStorage
 */
export const getStore = (params = {}) => {
  let { name, debug } = params;
  name = keyName + name;
    let { name, debug } = params
    name = keyName + name
  let obj = {},
    content;
  obj = window.sessionStorage.getItem(name);
  if (validatenull(obj)) obj = window.localStorage.getItem(name);
  if (validatenull(obj)) return;
        content
    obj = window.sessionStorage.getItem(name)
    if (validatenull(obj)) obj = window.localStorage.getItem(name)
    if (validatenull(obj)) return
  try {
    obj = JSON.parse(obj);
        obj = JSON.parse(obj)
  } catch {
    return obj;
        return obj
  }
  if (debug) {
    return obj;
        return obj
  }
  if (obj.dataType == 'string') {
    content = obj.content;
        content = obj.content
  } else if (obj.dataType == 'number') {
    content = Number(obj.content);
        content = Number(obj.content)
  } else if (obj.dataType == 'boolean') {
    content = eval(obj.content);
        content = eval(obj.content)
  } else if (obj.dataType == 'object') {
    content = obj.content;
        content = obj.content
  }
  return content;
};
    return content
}
/**
 * 删除localStorage
 */
export const removeStore = (params = {}) => {
  let { name, type } = params;
  name = keyName + name;
    let { name, type } = params
    name = keyName + name
  if (type) {
    window.sessionStorage.removeItem(name);
        window.sessionStorage.removeItem(name)
  } else {
    window.localStorage.removeItem(name);
        window.localStorage.removeItem(name)
  }
};
}
/**
 * 获取全部localStorage
 */
export const getAllStore = (params = {}) => {
  let list = [];
  let { type } = params;
    let list = []
    let { type } = params
  if (type) {
    for (let i = 0; i <= window.sessionStorage.length; i++) {
      list.push({
@@ -75,7 +75,7 @@
          name: window.sessionStorage.key(i),
          type: 'session',
        }),
      });
            })
    }
  } else {
    for (let i = 0; i <= window.localStorage.length; i++) {
@@ -84,20 +84,20 @@
        content: getStore({
          name: window.localStorage.key(i),
        }),
      });
            })
    }
  }
  return list;
};
    return list
}
/**
 * 清空全部localStorage
 */
export const clearStore = (params = {}) => {
  let { type } = params;
    let { type } = params
  if (type) {
    window.sessionStorage.clear();
        window.sessionStorage.clear()
  } else {
    window.localStorage.clear();
        window.localStorage.clear()
  }
};
}
src/utils/util.js
@@ -1,16 +1,16 @@
import { validatenull } from './validate';
import sha256 from 'crypto-js/sha256';
import Base64 from 'crypto-js/enc-base64';
import { validatenull } from './validate'
import sha256 from 'crypto-js/sha256'
import Base64 from 'crypto-js/enc-base64'
//表单序列化
export const serialize = data => {
  let list = [];
    let list = []
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`);
  });
  return list.join('&');
};
        list.push(`${ele}=${data[ele]}`)
    })
    return list.join('&')
}
export const getObjType = obj => {
  var toString = Object.prototype.toString;
    var toString = Object.prototype.toString
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
@@ -22,136 +22,136 @@
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};
    if (obj instanceof Element) {
        return 'element'
    }
    return map[toString.call(obj)]
}
/**
 * 对象深拷贝
 */
export const deepClone = data => {
  var type = getObjType(data);
  var obj;
    var type = getObjType(data)
    var obj
  if (type === 'array') {
    obj = [];
        obj = []
  } else if (type === 'object') {
    obj = {};
        obj = {}
  } else {
    //不再具有下一层次
    return data;
        return data
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
            obj.push(deepClone(data[i]))
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
            obj[key] = deepClone(data[key])
    }
  }
  return obj;
};
    return obj
}
/**
 * 设置灰度模式
 */
export const toggleGrayMode = status => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
        document.body.className = document.body.className + ' grayMode'
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
        document.body.className = document.body.className.replace(' grayMode', '')
  }
};
}
/**
 * 设置主题
 */
export const setTheme = name => {
  document.body.className = name;
};
    document.body.className = name
}
/**
 * 加密处理
 */
export const encryption = params => {
  let { data = {}, type, param, key } = params;
  let result = JSON.parse(JSON.stringify(data));
    let { data = {}, type, param, key } = params
    let result = JSON.parse(JSON.stringify(data))
  if (type == 'Base64') {
    param.forEach(ele => {
      result[ele] = Base64.stringify(result[ele]);
    });
            result[ele] = Base64.stringify(result[ele])
        })
  } else if (type == 'Aes') {
    param.forEach(ele => {
      result[ele] = sha256(result[ele], key);
    });
            result[ele] = sha256(result[ele], key)
        })
  }
  return result;
};
    return result
}
/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
        exitFullScreen()
  } else {
    reqFullScreen();
        reqFullScreen()
  }
};
}
/**
 * esc监听全屏
 */
export const listenfullscreen = callback => {
  function listen() {
    callback();
        callback()
  }
  document.addEventListener('fullscreenchange', function () {
    listen();
  });
        listen()
    })
  document.addEventListener('mozfullscreenchange', function () {
    listen();
  });
        listen()
    })
  document.addEventListener('webkitfullscreenchange', function () {
    listen();
  });
        listen()
    })
  document.addEventListener('msfullscreenchange', function () {
    listen();
  });
};
        listen()
    })
}
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen =
    document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen;
  return isFullscreen;
};
        document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
    return isFullscreen
}
/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
        document.documentElement.requestFullScreen()
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
        document.documentElement.webkitRequestFullScreen()
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
        document.documentElement.mozRequestFullScreen()
  }
};
}
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
        document.exitFullScreen()
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
        document.webkitCancelFullScreen()
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
        document.mozCancelFullScreen()
  }
};
}
/**
 * 递归寻找子类的父类
 */
@@ -161,16 +161,16 @@
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
                    return menu[i]
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
                        return findParent(menu[i].children[j].children, id)
          }
        }
      }
    }
  }
};
}
/**
 * 判断2个对象属性和值是否相等
 */
@@ -180,113 +180,113 @@
 */
export const loadStyle = url => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
    const link = document.createElement('link')
    link.type = 'text/css'
    link.rel = 'stylesheet'
    link.href = url
    const head = document.getElementsByTagName('head')[0]
    head.appendChild(link)
}
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
    delete obj1.close
    var o1 = obj1 instanceof Object
    var o2 = obj2 instanceof Object
  if (!o1 || !o2) {
    /*  判断不是对象  */
    return obj1 === obj2;
        return obj1 === obj2
  }
  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
        return false
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如:数组返回下表:let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }
  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
        var t1 = obj1[attr] instanceof Object
        var t2 = obj2[attr] instanceof Object
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
            return diff(obj1[attr], obj2[attr])
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
            return false
    }
  }
  return true;
};
    return true
}
/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
  let result = '';
  if (validatenull(dic)) return value;
    let result = ''
    if (validatenull(dic)) return value
  if (typeof value == 'string' || typeof value == 'number' || typeof value == 'boolean') {
    let index = 0;
    index = findArray(dic, value);
        let index = 0
        index = findArray(dic, value)
    if (index != -1) {
      result = dic[index].label;
            result = dic[index].label
    } else {
      result = value;
            result = value
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
        result = []
        let index = 0
    value.forEach(ele => {
      index = findArray(dic, ele);
            index = findArray(dic, ele)
      if (index != -1) {
        result.push(dic[index].label);
                result.push(dic[index].label)
      } else {
        result.push(value);
                result.push(value)
      }
    });
    result = result.toString();
        })
        result = result.toString()
  }
  return result;
};
    return result
}
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i].value == value) {
      return i;
            return i
    }
  }
  return -1;
};
    return -1
}
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = '';
    let random = ''
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
        .substr(0, len ? len : 4)
    if (date) random = random + Date.now()
    return random
}
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
    const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
    const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top
  const width = window.innerWidth
    ? window.innerWidth
    : document.documentElement.clientWidth
    ? document.documentElement.clientWidth
    : screen.width;
        : screen.width
  const height = window.innerHeight
    ? window.innerHeight
    : document.documentElement.clientHeight
    ? document.documentElement.clientHeight
    : screen.height;
        : screen.height
  const left = width / 2 - w / 2 + dualScreenLeft;
  const top = height / 2 - h / 2 + dualScreenTop;
    const left = width / 2 - w / 2 + dualScreenLeft
    const top = height / 2 - h / 2 + dualScreenTop
  const newWindow = window.open(
    url,
    title,
@@ -298,39 +298,39 @@
      top +
      ', left=' +
      left
  );
    )
  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus();
        newWindow.focus()
  }
};
}
export const getScreen = isCollapse => {
  if (document.body.clientWidth <= 768) {
    return !isCollapse;
        return !isCollapse
  } else {
    return isCollapse;
        return isCollapse
  }
};
}
/**
 * 获取顶部地址栏地址
 */
export const getTopUrl = () => {
  return window.location.href.split('/#/')[0];
};
    return window.location.href.split('/#/')[0]
}
/**
 * 获取url参数
 * @param name 参数名
 */
export const getQueryString = name => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
  let r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(decodeURI(r[2]));
  return null;
};
    let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    let r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(decodeURI(r[2]))
    return null
}
/**
 * 下载文件
@@ -338,29 +338,29 @@
 * @param {String} name - 文件名,eg: test.png
 */
export const downloadFileBlob = (path, name) => {
  const xhr = new XMLHttpRequest();
  xhr.open('get', path);
  xhr.responseType = 'blob';
  xhr.send();
    const xhr = new XMLHttpRequest()
    xhr.open('get', path)
    xhr.responseType = 'blob'
    xhr.send()
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
      if ('msSaveOrOpenBlob' in navigator) {
        navigator.msSaveOrOpenBlob(this.response, name);
        return;
                navigator.msSaveOrOpenBlob(this.response, name)
                return
      }
      const url = URL.createObjectURL(this.response);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = name;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
            const url = URL.createObjectURL(this.response)
            const a = document.createElement('a')
            a.style.display = 'none'
            a.href = url
            a.download = name
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            URL.revokeObjectURL(url)
    }
  };
};
    }
}
/**
 * 下载文件
@@ -368,26 +368,26 @@
 * @param {String} name - 文件名,eg: test.png
 */
export const downloadFileBase64 = (path, name) => {
  const xhr = new XMLHttpRequest();
  xhr.open('get', path);
  xhr.responseType = 'blob';
  xhr.send();
    const xhr = new XMLHttpRequest()
    xhr.open('get', path)
    xhr.responseType = 'blob'
    xhr.send()
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(this.response);
            const fileReader = new FileReader()
            fileReader.readAsDataURL(this.response)
      fileReader.onload = function () {
        const a = document.createElement('a');
        a.style.display = 'none';
        a.href = this.result;
        a.download = name;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      };
                const a = document.createElement('a')
                a.style.display = 'none'
                a.href = this.result
                a.download = name
                document.body.appendChild(a)
                a.click()
                document.body.removeChild(a)
    }
  };
};
        }
    }
}
/**
 * 下载excel
@@ -395,8 +395,8 @@
 * @param {String} filename 文件名称
 */
export const downloadXls = (fileArrayBuffer, filename) => {
  downloadFile(fileArrayBuffer, filename, 'application/vnd.ms-excel,charset=utf-8');
};
    downloadFile(fileArrayBuffer, filename, 'application/vnd.ms-excel,charset=utf-8')
}
/**
 * 下载json
@@ -404,8 +404,8 @@
 * @param {String} filename 文件名称
 */
export const downloadJson = (fileArrayBuffer, filename) => {
  downloadFile(fileArrayBuffer, filename, 'application/json,charset=utf-8');
};
    downloadFile(fileArrayBuffer, filename, 'application/json,charset=utf-8')
}
/**
 * 下载文件
@@ -414,20 +414,20 @@
 * @param mimeType 文件类型
 */
export const downloadFile = (fileArrayBuffer, filename, mimeType = 'application/octet-stream') => {
  let data = new Blob([fileArrayBuffer], { type: mimeType });
    let data = new Blob([fileArrayBuffer], { type: mimeType })
  if (typeof window.chrome !== 'undefined') {
    // Chrome
    let link = document.createElement('a');
    link.href = window.URL.createObjectURL(data);
    link.download = filename;
    link.click();
        let link = document.createElement('a')
        link.href = window.URL.createObjectURL(data)
        link.download = filename
        link.click()
  } else if (typeof window.navigator.msSaveBlob !== 'undefined') {
    // IE
    let blob = new Blob([data], { type: 'application/force-download' });
    window.navigator.msSaveBlob(blob, filename);
        let blob = new Blob([data], { type: 'application/force-download' })
        window.navigator.msSaveBlob(blob, filename)
  } else {
    // Firefox
    let file = new File([data], filename, { type: 'application/force-download' });
    window.open(URL.createObjectURL(file));
        let file = new File([data], filename, { type: 'application/force-download' })
        window.open(URL.createObjectURL(file))
  }
};
}
src/utils/validate.js
@@ -3,15 +3,15 @@
 */
export function isvalidUsername(str) {
  const valid_map = ['admin', 'editor'];
  return valid_map.indexOf(str.trim()) >= 0;
    const valid_map = ['admin', 'editor']
    return valid_map.indexOf(str.trim()) >= 0
}
/* 合法uri*/
export function validateURL(textval) {
  const urlregex =
    /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
  return urlregex.test(textval);
        /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
    return urlregex.test(textval)
}
/**
@@ -19,7 +19,7 @@
 * @param {*} s
 */
export function isEmail(s) {
  return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s);
    return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}
/**
@@ -27,7 +27,7 @@
 * @param {*} s
 */
export function isMobile(s) {
  return /^1[0-9]{10}$/.test(s);
    return /^1[0-9]{10}$/.test(s)
}
/**
@@ -35,7 +35,7 @@
 * @param {*} s
 */
export function isPhone(s) {
  return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s);
    return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}
/**
@@ -43,40 +43,40 @@
 * @param {*} s
 */
export function isURL(s) {
  return /^http[s]?:\/\/.*/.test(s);
    return /^http[s]?:\/\/.*/.test(s)
}
/* 小写字母*/
export function validateLowerCase(str) {
  const reg = /^[a-z]+$/;
  return reg.test(str);
    const reg = /^[a-z]+$/
    return reg.test(str)
}
/* 大写字母*/
export function validateUpperCase(str) {
  const reg = /^[A-Z]+$/;
  return reg.test(str);
    const reg = /^[A-Z]+$/
    return reg.test(str)
}
/* 大小写字母*/
export function validatAlphabets(str) {
  const reg = /^[A-Za-z]+$/;
  return reg.test(str);
    const reg = /^[A-Za-z]+$/
    return reg.test(str)
}
/*验证pad还是pc*/
export const vaildatePc = function () {
  const userAgentInfo = navigator.userAgent;
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
  let flag = true;
    const userAgentInfo = navigator.userAgent
    const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
    let flag = true
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
            flag = false
            break
    }
  }
  return flag;
};
    return flag
}
/**
 * validate email
@@ -85,17 +85,17 @@
 */
export function validateEmail(email) {
  const re =
    /^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(email);
        /^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    return re.test(email)
}
/**
 * 判断身份证号码
 */
export function cardid(code) {
  let list = [];
  let result = true;
  let msg = '';
    let list = []
    let result = true
    let msg = ''
  var city = {
    11: '北京',
    12: '天津',
@@ -132,108 +132,108 @@
    81: '香港',
    82: '澳门',
    91: '国外 ',
  };
    }
  if (!validatenull(code)) {
    if (code.length === 18) {
      if (!code || !/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(code)) {
        msg = '证件号码格式错误';
                msg = '证件号码格式错误'
      } else if (!city[code.substr(0, 2)]) {
        msg = '地址编码错误';
                msg = '地址编码错误'
      } else {
        //18位身份证需要验证最后一位校验位
        code = code.split('');
                code = code.split('')
        //∑(ai×Wi)(mod 11)
        //加权因子
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        //校验位
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x'];
        var sum = 0;
        var ai = 0;
        var wi = 0;
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2, 'x']
                var sum = 0
                var ai = 0
                var wi = 0
        for (var i = 0; i < 17; i++) {
          ai = code[i];
          wi = factor[i];
          sum += ai * wi;
                    ai = code[i]
                    wi = factor[i]
                    sum += ai * wi
        }
        if (parity[sum % 11] !== code[17]) {
          msg = '证件号码校验位错误';
                    msg = '证件号码校验位错误'
        } else {
          result = false;
                    result = false
        }
      }
    } else {
      msg = '证件号码长度不为18位';
            msg = '证件号码长度不为18位'
    }
  } else {
    msg = '证件号码不能为空';
        msg = '证件号码不能为空'
  }
  list.push(result);
  list.push(msg);
  return list;
    list.push(result)
    list.push(msg)
    return list
}
/**
 * 判断手机号码是否正确
 */
export function isvalidatemobile(phone) {
  let list = [];
  let result = true;
  let msg = '';
  var isPhone = /^0\d{2,3}-?\d{7,8}$/;
    let list = []
    let result = true
    let msg = ''
    var isPhone = /^0\d{2,3}-?\d{7,8}$/
  //增加134 减少|1349[0-9]{7},增加181,增加145,增加17[678]
  if (!validatenull(phone)) {
    if (phone.length === 11) {
      if (isPhone.test(phone)) {
        msg = '手机号码格式不正确';
                msg = '手机号码格式不正确'
      } else {
        result = false;
                result = false
      }
    } else {
      msg = '手机号码长度不为11位';
            msg = '手机号码长度不为11位'
    }
  } else {
    msg = '手机号码不能为空';
        msg = '手机号码不能为空'
  }
  list.push(result);
  list.push(msg);
  return list;
    list.push(result)
    list.push(msg)
    return list
}
/**
 * 判断姓名是否正确
 */
export function validatename(name) {
  var regName = /^[\u4e00-\u9fa5]{2,4}$/;
  if (!regName.test(name)) return false;
  return true;
    var regName = /^[\u4e00-\u9fa5]{2,4}$/
    if (!regName.test(name)) return false
    return true
}
/**
 * 判断是否为整数
 */
export function validatenum(num, type) {
  let regName = /[^\d.]/g;
    let regName = /[^\d.]/g
  if (type === 1) {
    if (!regName.test(num)) return false;
        if (!regName.test(num)) return false
  } else if (type === 2) {
    regName = /[^\d]/g;
    if (!regName.test(num)) return false;
        regName = /[^\d]/g
        if (!regName.test(num)) return false
  }
  return true;
    return true
}
/**
 * 判断是否为小数
 */
export function validatenumord(num, type) {
  let regName = /[^\d.]/g;
    let regName = /[^\d.]/g
  if (type === 1) {
    if (!regName.test(num)) return false;
        if (!regName.test(num)) return false
  } else if (type === 2) {
    regName = /[^\d.]/g;
    if (!regName.test(num)) return false;
        regName = /[^\d.]/g
        if (!regName.test(num)) return false
  }
  return true;
    return true
}
/**
@@ -241,21 +241,21 @@
 */
export function validatenull(val) {
  if (typeof val == 'boolean') {
    return false;
        return false
  }
  if (typeof val == 'number') {
    return false;
        return false
  }
  if (val instanceof Array) {
    if (val.length === 0) return true;
        if (val.length === 0) return true
  } else if (val instanceof Object) {
    if (JSON.stringify(val) === '{}') return true;
        if (JSON.stringify(val) === '{}') return true
  } else {
    if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '')
      return true;
    return false;
            return true
        return false
  }
  return false;
    return false
}
/**
@@ -266,20 +266,20 @@
export function validatejson(val) {
  // 直接判断是否为对象(排除 null 和数组)
  if (val !== null && typeof val === 'object') {
    return true;
        return true
  }
  // 尝试解析字符串为 JSON
  if (typeof val === 'string') {
    try {
      const obj = JSON.parse(val);
            const obj = JSON.parse(val)
      // 解析后还需判断是否为对象或数组
      return obj !== null && typeof obj === 'object';
            return obj !== null && typeof obj === 'object'
    } catch (e) {
      return false;
            return false
    }
  }
  // 非对象、非数组、非字符串,或者字符串不是 JSON
  return false;
    return false
}
src/utils/websocket/connect-websocket.js
@@ -1,15 +1,15 @@
import ConnectWebSocket from '@/websocket';
import { getWebsocketUrl } from '@/websocket/util/config';
import ConnectWebSocket from '@/websocket'
import { getWebsocketUrl } from '@/websocket/util/config'
/**
 * 接收一个message函数
 * @param messageHandler
 */
export function useConnectWebSocket(messageHandler, url) {
    const webSocket = new ConnectWebSocket(url || getWebsocketUrl());
    const webSocket = new ConnectWebSocket(url || getWebsocketUrl())
    webSocket?.registerMessageHandler(messageHandler);
    webSocket?.initSocket();
    webSocket?.registerMessageHandler(messageHandler)
    webSocket?.initSocket()
    return webSocket;
    return webSocket
}
src/utils/websocket/drone-ws-control.js
@@ -1,6 +1,6 @@
// import { EventBus } from '@/eventBus/event-bus';
import { EBizCode, EBizCodeMessage } from '@/utils/staticData/enums';
import { ControlSource } from '@/utils/staticData/device';
import { EBizCode, EBizCodeMessage } from '@/utils/staticData/enums'
import { ControlSource } from '@/utils/staticData/device'
export default {
    data() {
@@ -8,33 +8,24 @@
            droneControlSource: '',
            payloadControlSource: '',
            ControlSource: ControlSource,
        };
        }
    },
    methods: {
        useDroneControlWsEvent(sn, payloadSn, funcs) {
            const _this = this;
            this.droneControlSource = this.ControlSource.A;
            this.payloadControlSource = this.ControlSource.B;
            const _this = this
            this.droneControlSource = this.ControlSource.A
            this.payloadControlSource = this.ControlSource.B
            function onControlSourceChange(data) {
                if (
                    data.type === 1 &&
                    data.sn === sn
                ) {
                    _this.droneControlSource = data.control_source;
                    _this.$store.commit(
                        'SET_DRONE_CONTROL_SOURCE',
                        _this.droneControlSource,
                    );
                if (data.type === 1 && data.sn === sn) {
                    _this.droneControlSource = data.control_source
                    _this.$store.commit('SET_DRONE_CONTROL_SOURCE', _this.droneControlSource)
                    // _this.$message.info(`飞行控制改为 ${_this.droneControlSource}`)
                    // _this._showMessage.info(`飞行控制改为 ${_this.droneControlSource}`)
                    return;
                    return
                }
                if (
                    data.type === 2 &&
                    data.sn === payloadSn
                ) {
                    _this.payloadControlSource = data.control_source;
                if (data.type === 2 && data.sn === payloadSn) {
                    _this.payloadControlSource = data.control_source
                    // _this.$message.info(`负载控制改为 ${_this.payloadControlSource}.`)
                    // _this._showMessage.info(`负载控制改为 ${_this.payloadControlSource}.`)
                }
@@ -49,7 +40,7 @@
                    //     duration: 30
                    // })
                    // _this._showMessage.warning(key + '错误码:' + error)
                    _this._showMessage.warning(key);
                    _this._showMessage.warning(key)
                } else {
                    // _this.$notify.closeAll()
                    // _this.$notify.info({
@@ -57,89 +48,71 @@
                    //     message: message,
                    //     duration: 30
                    // })
                    _this._showMessage.info(message);
                    _this._showMessage.info(message)
                }
            }
            function handleDroneControlWsEvent(payload) {
                if (!payload) {
                    return;
                    return
                }
                switch (payload.biz_code) {
                    case EBizCode.ControlSourceChange: {
                        onControlSourceChange(payload.data);
                        break;
                        onControlSourceChange(payload.data)
                        break
                    }
                    case EBizCode.FlyToPointProgress: {
                        const {
                            sn: deviceSn,
                            result,
                            message: msg,
                        } = payload.data;
                        if (deviceSn !== sn) return;
                        const { sn: deviceSn, result, message: msg } = payload.data
                        if (deviceSn !== sn) return
                        handleProgress(
                            EBizCodeMessage[EBizCode.FlyToPointProgress],
                            `设备(编码: ${deviceSn}) ${msg}`,
                            result,
                        );
                        break;
                            result
                        )
                        break
                    }
                    case EBizCode.TakeoffToPointProgress: {
                        const {
                            sn: deviceSn,
                            result,
                            message: msg,
                        } = payload.data;
                        if (deviceSn !== sn) return;
                        const { sn: deviceSn, result, message: msg } = payload.data
                        if (deviceSn !== sn) return
                        handleProgress(
                            EBizCodeMessage[EBizCode.TakeoffToPointProgress],
                            `设备(编码: ${deviceSn}) ${msg}`,
                            result,
                        );
                        break;
                            result
                        )
                        break
                    }
                    case EBizCode.JoystickInvalidNotify: {
                        const {
                            sn: deviceSn,
                            result,
                            message: msg,
                        } = payload.data;
                        if (deviceSn !== sn) return;
                        const { sn: deviceSn, result, message: msg } = payload.data
                        if (deviceSn !== sn) return
                        handleProgress(
                            EBizCodeMessage[EBizCode.JoystickInvalidNotify],
                            `设备(编码: ${deviceSn}) ${msg}`,
                            result,
                        );
                        break;
                            result
                        )
                        break
                    }
                    case EBizCode.DrcStatusNotify: {
                        const {
                            sn: deviceSn,
                            result,
                            message: msg,
                        } = payload.data;
                        break;
                        const { sn: deviceSn, result, message: msg } = payload.data
                        break
                    }
                }
            }
            return {
                handleDroneControlWsEvent,
            };
            }
        },
    },
    mounted() {
        this.$EventBus.$on(
            'droneControlWs',
            this.useDroneControlWsEvent(this.sn, this.payloadSelectInfo.value)
                .handleDroneControlWsEvent,
        );
            this.useDroneControlWsEvent(this.sn, this.payloadSelectInfo.value).handleDroneControlWsEvent
        )
    },
    beforeDestroy() {
        this.$EventBus.$off(
            'droneControlWs',
            this.useDroneControlWsEvent(this.sn, this.payloadSelectInfo.value)
                .handleDroneControlWsEvent,
        );
            this.useDroneControlWsEvent(this.sn, this.payloadSelectInfo.value).handleDroneControlWsEvent
        )
    },
};
}
src/views/Home/Footer.vue
@@ -14,24 +14,24 @@
</template>
<script setup>
import img1 from '@/assets/images/home/footer/machine-nest.png';
import activeImg1 from '@/assets/images/home/footer/machine-nest1.png';
import img2 from '@/assets/images/home/footer/event.png';
import activeImg2 from '@/assets/images/home/footer/event1.png';
import img3 from '@/assets/images/home/footer/panorama.png';
import activeImg3 from '@/assets/images/home/footer/panorama1.png';
import img4 from '@/assets/images/home/footer/3D.png';
import activeImg4 from '@/assets/images/home/footer/3D1.png';
import img5 from '@/assets/images/home/footer/orthophoto.png';
import activeImg5 from '@/assets/images/home/footer/orthophoto1.png';
import img1 from '@/assets/images/home/footer/machine-nest.png'
import activeImg1 from '@/assets/images/home/footer/machine-nest1.png'
import img2 from '@/assets/images/home/footer/event.png'
import activeImg2 from '@/assets/images/home/footer/event1.png'
import img3 from '@/assets/images/home/footer/panorama.png'
import activeImg3 from '@/assets/images/home/footer/panorama1.png'
import img4 from '@/assets/images/home/footer/3D.png'
import activeImg4 from '@/assets/images/home/footer/3D1.png'
import img5 from '@/assets/images/home/footer/orthophoto.png'
import activeImg5 from '@/assets/images/home/footer/orthophoto1.png'
import { useUavHome } from '@/views/Home/useUavHome/useUavHome';
import { useEventOperate } from '@/views/Home/useEventOperate/useEventOperate';
import { useUavHome } from '@/views/Home/useUavHome/useUavHome'
import { useEventOperate } from '@/views/Home/useEventOperate/useEventOperate'
// 机巢聚合
const { init, removeAll } = useUavHome();
const { init, removeAll } = useUavHome()
// 事件聚合
const { init: eventInit, removeAll: eventRemove } = useEventOperate();
const { init: eventInit, removeAll: eventRemove } = useEventOperate()
const list = ref([
  {
@@ -55,28 +55,28 @@
  { name: 'event3', img: img3, activeImg: activeImg3, active: false, className: 'panorama' },
  { name: 'event4', img: img4, activeImg: activeImg4, active: false, className: 'threeD' },
  { name: 'event5', img: img5, activeImg: activeImg5, active: false, className: 'orthophoto' },
]);
])
const imgClick = toItem => {
  const fromItem = list.value.find(item => item.active);
  if (fromItem.name === toItem.name) return;
  fromItem?.removeAll?.();
    const fromItem = list.value.find(item => item.active)
    if (fromItem.name === toItem.name) return
    fromItem?.removeAll?.()
  nextTick(()=>{
    toItem?.init?.();
        toItem?.init?.()
  })
  list.value = list.value.map(item => ({ ...item, active: item.name === toItem.name }));
};
    list.value = list.value.map(item => ({ ...item, active: item.name === toItem.name }))
}
// 销毁前钩子
onBeforeUnmount(() => {
  if (!window.$viewer) return;
  removeAll();
});
    if (!window.$viewer) return
    removeAll()
})
onMounted(() => {
  nextTick(() => {
    init();
  });
});
        init()
    })
})
</script>
<style scoped lang="scss">
src/views/Home/components/HomeLeft/InspectionRaskDetails.vue
@@ -10,7 +10,9 @@
      </div>
      <div class="status">
        <div v-for="item in list">
          <div :style="{ color: item.color }" class="value">{{ jobStatistics[item.field] }}</div>
                    <div :style="{ color: item.color }" class="value">
                        {{ jobStatistics[item.field] }}
                    </div>
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
@@ -21,22 +23,22 @@
</template>
<script setup>
import * as echarts from 'echarts';
import { pxToRem } from '@/utils/rem';
import CommonTitle from '@/components/CommonTitle.vue';
import CommonDateTime from '@/components/CommonDateTime.vue';
import { getJobNumBar, getJobStatistics, getTotalJobNum } from '@/api/home';
import dayjs from 'dayjs';
import * as echarts from 'echarts'
import { pxToRem } from '@/utils/rem'
import CommonTitle from '@/components/CommonTitle.vue'
import CommonDateTime from '@/components/CommonDateTime.vue'
import { getJobNumBar, getJobStatistics, getTotalJobNum } from '@/api/home'
import dayjs from 'dayjs'
const currenDate = dayjs().format('YYYY-MM-DD');
const newTime = ref([currenDate, currenDate]);
const currenDate = dayjs().format('YYYY-MM-DD')
const newTime = ref([currenDate, currenDate])
const list = ref([
  { name: '计划执行', value: 89, color: '#FFFFFF', field: 'planned_executions' },
  { name: '执行中', value: 100, color: '#FFA768', field: 'running_num' },
  { name: '待执行', value: 66, color: '#FFE17E', field: 'pending_executions' },
  { name: '已执行', value: 10, color: '#8EFFAC', field: 'executed' },
  { name: '执行失败', value: 10, color: '#FF8E8E', field: 'failed_executions' },
]);
])
const option = {
  grid: {
    top: '15%',
@@ -57,7 +59,7 @@
  },
  xAxis: {
    type: 'category',
    data: ['1',],
        data: ['1'],
    axisLine: {
      show: false, // 隐藏轴线
    },
@@ -100,13 +102,13 @@
      ]),
    },
  },
};
}
const detailsFun = () => {
  console.log('details');
};
    console.log('details')
}
let chart = null;
let chart = null
// TODAY,CURRENT_WEEK,CURRENT_MONTH,CURRENT_YEAR
const getData = (value,date_enum) => {
@@ -114,38 +116,38 @@
    date_enum,
    // start_date: newTime.value[0],
    // end_date: newTime.value[1]
  };
    }
  getJobStatistics(params).then(res => {
    jobStatistics.value = res.data?.data || {};
  });
        jobStatistics.value = res.data?.data || {}
    })
  getJobNumBar(params).then(res => {
    option.xAxis.data = res.data?.data.map(item => item.name);
    option.series.data = res.data?.data.map(item => item.value);
    chart.setOption(option);
  });
};
        option.xAxis.data = res.data?.data.map(item => item.name)
        option.series.data = res.data?.data.map(item => item.value)
        chart.setOption(option)
    })
}
const chartRef = ref(null);
const total = ref(0);
const chartRef = ref(null)
const total = ref(0)
const jobStatistics = ref({
  planned_executions: 0,
  executed: 0,
  running_num: 0,
  failed_executions: 0,
  pending_executions: 0,
});
})
onMounted(() => {
  chart = echarts.init(chartRef.value);
    chart = echarts.init(chartRef.value)
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize();
  });
        chart.resize()
    })
  getTotalJobNum().then(res => {
    total.value = res.data?.data || 0;
  });
  getData(newTime.value, 'TODAY');
});
        total.value = res.data?.data || 0
    })
    getData(newTime.value, 'TODAY')
})
</script>
<style scoped lang="scss">
@@ -164,7 +166,8 @@
  opacity: 0.85;
  .inspection-num {
    background: url('@/assets/images/home/homeLeft/inspection-num.png') no-repeat center / 100% 100%;
        background: url('@/assets/images/home/homeLeft/inspection-num.png') no-repeat center / 100%
            100%;
    width: 360px;
    height: 118px;
    position: relative;
src/views/Home/useEventOperate/useEventOperate.js
@@ -1,13 +1,13 @@
import * as Cesium from 'cesium';
import data2 from '@/assets/images/home/homeRight/data2.png';
import data1 from '@/assets/images/home/homeRight/data1.png';
import eventImg from '@/assets/images/home/useEventOperate/event.png';
import jiangxishi from '@/assets/geojson/jiangxishi.json';
import jiangxi from '@/assets/geojson/jiangxi.json';
import zg from '@/assets/geojson/zg.json';
import EventPopUpBox from './EventPopUpBox.vue';
import { render } from 'vue';
import store from '@/store';
import * as Cesium from 'cesium'
import data2 from '@/assets/images/home/homeRight/data2.png'
import data1 from '@/assets/images/home/homeRight/data1.png'
import eventImg from '@/assets/images/home/useEventOperate/event.png'
import jiangxishi from '@/assets/geojson/jiangxishi.json'
import jiangxi from '@/assets/geojson/jiangxi.json'
import zg from '@/assets/geojson/zg.json'
import EventPopUpBox from './EventPopUpBox.vue'
import { render } from 'vue'
import store from '@/store'
/**
 * 事件聚合功能
@@ -18,33 +18,33 @@
    { name: '市', value: [48651, 314863], gJson: jiangxishi },
    { name: '省', value: [314863, 1169651], gJson: jiangxi },
    { name: '国', value: [1169651, 37962800], gJson: zg },
  ];
  let viewer = null;
  let active = null;
  let handler = null;
  let positionC3 = null;
    ]
    let viewer = null
    let active = null
    let handler = null
    let positionC3 = null
  const listenerHeight = () => {
    determineScaling();
    viewer.camera.moveEnd.addEventListener(determineScaling);
  };
        determineScaling()
        viewer.camera.moveEnd.addEventListener(determineScaling)
    }
  // 确定缩放比例
  const determineScaling = () => {
    if(!viewer) return
    let height = viewer.camera.positionCartographic.height;
        let height = viewer.camera.positionCartographic.height
    // 根据高度展示对应的 gJson
    for (let item of scalingJudgment) {
      if (height > item.value[0] && height <= item.value[1]) {
        if (active !== item.name) {
          removeEntities();
          removeLabel();
          active = item.name;
          item.gJson ? aggregation(item) : splashed();
                    removeEntities()
                    removeLabel()
                    active = item.name
                    item.gJson ? aggregation(item) : splashed()
        }
        break;
                break
      }
    }
  };
    }
  //散点机巢
  function splashed() {
@@ -70,7 +70,7 @@
          width: 24,
          height: 24,
        },
      });
            })
    }
  }
@@ -79,11 +79,11 @@
    const featuresList = item.gJson.features.map(item => ({
      name: item.properties.name,
      position: item.properties.center,
    }));
        }))
    // 遍历特征并添加实体
    featuresList.forEach(feature => {
      if (!feature.position) return;
      const position = Cesium.Cartesian3.fromDegrees(feature.position[0], feature.position[1]);
            if (!feature.position) return
            const position = Cesium.Cartesian3.fromDegrees(feature.position[0], feature.position[1])
      viewer.entities.add({
        id: feature.id,
        position: position,
@@ -109,98 +109,98 @@
            name: feature.name,
          },
        },
      });
    });
            })
        })
    // 加载新的 GeoJSON 数据
    Cesium.GeoJsonDataSource.load(item.gJson).then(dataSource => {
      viewer.dataSources.add(dataSource);
      item.dataSource = dataSource; // 保存数据源以便后续删除
            viewer.dataSources.add(dataSource)
            item.dataSource = dataSource // 保存数据源以便后续删除
      // 获取数据源中的实体
      const entities = dataSource.entities.values;
            const entities = dataSource.entities.values
      entities.forEach(entity => {
        entity.polygon.material = new Cesium.ColorMaterialProperty(
          Cesium.Color.YELLOW.withAlpha(0) // 透明填充
        );
        entity.polygon.outline = new Cesium.ConstantProperty(true); // 显示边框
        entity.polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.YELLOW); // 黑色边框
      });
    });
  };
                )
                entity.polygon.outline = new Cesium.ConstantProperty(true) // 显示边框
                entity.polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.YELLOW) // 黑色边框
            })
        })
    }
  // 获取弹框box
  const getLabelDom = () => {
    const vNode = h(EventPopUpBox, { data: '参数', removeLabel });
    const tooltipContainer = document.createElement('div');
    tooltipContainer.id = 'mapPopUpBox';
    tooltipContainer.style.position = 'absolute';
    tooltipContainer.style.transform = 'translate(-50%,-110%)';
    tooltipContainer.style.pointerEvents = 'none';
    document.querySelector('.page-index').append(tooltipContainer);
    render(vNode, tooltipContainer);
    return tooltipContainer;
  };
        const vNode = h(EventPopUpBox, { data: '参数', removeLabel })
        const tooltipContainer = document.createElement('div')
        tooltipContainer.id = 'mapPopUpBox'
        tooltipContainer.style.position = 'absolute'
        tooltipContainer.style.transform = 'translate(-50%,-110%)'
        tooltipContainer.style.pointerEvents = 'none'
        document.querySelector('.page-index').append(tooltipContainer)
        render(vNode, tooltipContainer)
        return tooltipContainer
    }
  // 弹框位置刷新
  const labelBox = () => {
    store.commit('setSingleUavHome', {
      id: '123'
    });
    let dom = document.querySelector('#mapPopUpBox');
            id: '123',
        })
        let dom = document.querySelector('#mapPopUpBox')
    if (!dom) {
      dom = getLabelDom();
            dom = getLabelDom()
    }
    const screenPosition = viewer.scene.cartesianToCanvasCoordinates(positionC3);
        const screenPosition = viewer.scene.cartesianToCanvasCoordinates(positionC3)
    if (screenPosition) {
      dom.style.left = `${screenPosition.x}px`;
      dom.style.top = `${screenPosition.y}px`;
      dom.style.display = 'block';
            dom.style.left = `${screenPosition.x}px`
            dom.style.top = `${screenPosition.y}px`
            dom.style.display = 'block'
    }
  };
    }
  // 左键单机事件
  const singleMachineEvent = click => {
    const pickedObject = viewer.scene.pick(click.position);
        const pickedObject = viewer.scene.pick(click.position)
    if (Cesium.defined(pickedObject) && pickedObject.id) {
      const entity = pickedObject.id;
      positionC3 = entity?.position?._value;
      if (!positionC3) return;
      viewer.scene.postRender.removeEventListener(labelBox);
      viewer.scene.postRender.addEventListener(labelBox);
            const entity = pickedObject.id
            positionC3 = entity?.position?._value
            if (!positionC3) return
            viewer.scene.postRender.removeEventListener(labelBox)
            viewer.scene.postRender.addEventListener(labelBox)
    }
  };
    }
  // 移除 点 和 gjson 实体
  const removeEntities = () => {
    viewer.dataSources?.removeAll(true);
    viewer.entities?.removeAll();
  };
        viewer.dataSources?.removeAll(true)
        viewer.entities?.removeAll()
    }
  // 移除弹框标签
  const removeLabel = () => {
    viewer.scene.postRender.removeEventListener(labelBox);
    const dom = document.querySelector('#mapPopUpBox');
        viewer.scene.postRender.removeEventListener(labelBox)
        const dom = document.querySelector('#mapPopUpBox')
    if (dom && dom.parentNode) {
      dom.parentNode.removeChild(dom);
            dom.parentNode.removeChild(dom)
    }
  };
    }
  // 移除所有监听事件,变量置空
  const removeAll = () => {
    removeEntities();
    removeLabel();
    viewer.camera.moveEnd.removeEventListener(determineScaling);
    handler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    handler?.destroy();
    viewer = null;
        removeEntities()
        removeLabel()
        viewer.camera.moveEnd.removeEventListener(determineScaling)
        handler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler?.destroy()
        viewer = null
    active = null
    handler = null;
    positionC3 = null;
  };
        handler = null
        positionC3 = null
    }
  const init = () => {
    viewer = window.$viewer;
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(singleMachineEvent, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    listenerHeight();
  };
        viewer = window.$viewer
        handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
        handler.setInputAction(singleMachineEvent, Cesium.ScreenSpaceEventType.LEFT_CLICK)
        listenerHeight()
    }
  // onMounted(() => {
  //   nextTick(() => {
  //     viewer = window.$viewer;
@@ -210,5 +210,5 @@
  //   });
  // });
  return { init,removeAll };
};
    return { init, removeAll }
}
src/views/Home/useUavHome/useUavHome.js
@@ -1,121 +1,146 @@
import * as Cesium from 'cesium';
import aggregationImg from '@/assets/images/home/useUavHome/aggregation.png';
import uavImg from '@/assets/images/home/useUavHome/uavImg.png';
import MapPopUpBox from '@/views/Home/useUavHome/MapPopUpBox.vue';
import { render } from 'vue';
import { useStore } from 'vuex';
import { getCenterPoint } from '@/utils/cesium/mapUtil';
import cesiumOperation from '@/utils/cesium-tsa';
import { HeadingPitchRange } from 'cesium';
import { getDeviceRegion, getDeviceRegionCount } from '@/api/home/aggregation';
import * as Cesium from 'cesium'
import aggregationImg from '@/assets/images/home/useUavHome/aggregation.png'
import uavImg from '@/assets/images/home/useUavHome/uavImg.png'
import MapPopUpBox from '@/views/Home/useUavHome/MapPopUpBox.vue'
import { render } from 'vue'
import { useStore } from 'vuex'
import { getCenterPoint } from '@/utils/cesium/mapUtil'
import cesiumOperation from '@/utils/cesium-tsa'
import { HeadingPitchRange } from 'cesium'
import { getDeviceRegion, getDeviceRegionCount } from '@/api/home/aggregation'
/**
 * 机巢聚合功能
 */
export const useUavHome = () => {
  const { flyTo } = cesiumOperation();
    const { flyTo } = cesiumOperation()
  let scalingJudgment = [
    { name: '县', splashedList: [], gJson: null, show: false,outline:{}, value: [0, 48651], height: 31753 },
    { name: '市', splashedList: [], gJson: null, show: false,outline:{}, value: [48651, 314863], height: 257731 },
    { name: '省', splashedList: [], gJson: null, show: false,outline:{}, value: [314863, 3796280000], height: 1987280 },
  ];
  let viewer = null;
  let active = null;
  let handler = null;
  let positionC3 = null;
  let currentEntity = null;
        {
            name: '县',
            splashedList: [],
            gJson: null,
            show: false,
            outline: {},
            value: [0, 48651],
            height: 31753,
        },
        {
            name: '市',
            splashedList: [],
            gJson: null,
            show: false,
            outline: {},
            value: [48651, 314863],
            height: 257731,
        },
        {
            name: '省',
            splashedList: [],
            gJson: null,
            show: false,
            outline: {},
            value: [314863, 3796280000],
            height: 1987280,
        },
    ]
    let viewer = null
    let active = null
    let handler = null
    let positionC3 = null
    let currentEntity = null
  const listenerHeight = () => {
    determineScaling();
    viewer.camera.moveEnd.addEventListener(determineScaling);
  };
        determineScaling()
        viewer.camera.moveEnd.addEventListener(determineScaling)
    }
  // 确定缩放比例
  const determineScaling = index => {
    console.log('确定缩放比例');
    if (!viewer) return;
    let height = viewer.camera.positionCartographic.height;
        console.log('确定缩放比例')
        if (!viewer) return
        let height = viewer.camera.positionCartographic.height
    // 根据高度展示对应的 gJson
    for (let [index, item] of scalingJudgment.entries()) {
      if (!item.show) return;
            if (!item.show) return
      if (height > item.value[0] && height <= item.value[1]) {
        if (active === item.name) return;
        active = item.name;
        removeEntities();
        removeLabel();
                if (active === item.name) return
                active = item.name
                removeEntities()
                removeLabel()
        item.gJson ?  aggregation(item) :  splashed(item)
        renderOutline(item)
        break;
                break
      }
    }
  };
    }
  function convertToHierarchy(code) {
    const codeStr = code.toString();
    const provinceCode = codeStr.slice(0, 2) + '0000';
    const cityCode = codeStr.slice(0, 4) + '00';
        const codeStr = code.toString()
        const provinceCode = codeStr.slice(0, 2) + '0000'
        const cityCode = codeStr.slice(0, 4) + '00'
    if (codeStr.slice(2, 4) === '00' && codeStr.slice(4, 6) === '00') {
      return [provinceCode];
            return [provinceCode]
    } else if (codeStr.slice(4, 6) === '00') {
      return [provinceCode, cityCode];
            return [provinceCode, cityCode]
    }
    return [provinceCode, cityCode, code];
        return [provinceCode, cityCode, code]
  }
  const store = useStore();
  const selectedAreaCode = computed(() => store.state.user.selectedAreaCode);
    const store = useStore()
    const selectedAreaCode = computed(() => store.state.user.selectedAreaCode)
  function getDeviceCount(areaCode) {
    return getDeviceRegionCount({areaCode}).then(res => {
      return res?.data?.data || [];
    });
            return res?.data?.data || []
        })
  }
  function getDeviceList(areaCode) {
    return getDeviceRegion({areaCode}).then(res => {
      return res?.data?.data || [];
    });
            return res?.data?.data || []
        })
  }
  const findFun = (featItem, numItem) => Number(featItem.region_code.slice(0, 6)) === numItem.properties.adcode;
  const { VITE_APP_BASE } = import.meta.env;
  const defaultDir = `${VITE_APP_BASE}public/geoJson/100000/`;
    const findFun = (featItem, numItem) =>
        Number(featItem.region_code.slice(0, 6)) === numItem.properties.adcode
    const { VITE_APP_BASE } = import.meta.env
    const defaultDir = `${VITE_APP_BASE}public/geoJson/100000/`
  const getFiler = async (url) => {
    const gJson = await import(/* @vite-ignore */ url);
    return JSON.parse(JSON.stringify(gJson));
    const getFiler = async url => {
        const gJson = await import(/* @vite-ignore */ url)
        return JSON.parse(JSON.stringify(gJson))
  }
  const getOutLine = async (jsonPathPre,hierarchy) => {
    const parentGJson = await getFiler(`${defaultDir}${jsonPathPre}/index.json`)
    let features = parentGJson.features.find(
      item => item.properties.adcode === Number(hierarchy[hierarchy.length - 1])
    );
    return  { type: "FeatureCollection", features: [features] }
        )
        return { type: 'FeatureCollection', features: [features] }
  }
  const injectData = (gJson,dataList) => {
    return {
      ...gJson,
      features: gJson.features.map(item => ({ ...item, data: dataList.find(item1 => findFun(item1, item)) })),
            features: gJson.features.map(item => ({
                ...item,
                data: dataList.find(item1 => findFun(item1, item)),
            })),
    }
  }
  watch(
    selectedAreaCode,
    async (newValue, oldValue) => {
      if (newValue) {
        const list = await getDeviceCount(newValue);
        const splashedList = await getDeviceList(newValue);
        console.log(list);
        console.log(splashedList);
        const hierarchy = convertToHierarchy(newValue.slice(0, 6));
        const jsonPath = hierarchy.join('/');
        const jsonPathPre = hierarchy.slice(0, hierarchy.length - 1).join('/');
        scalingJudgment = scalingJudgment.map(item => ({ ...item, show: true }));
        scalingJudgment[0].gJson = null;
        scalingJudgment[0].splashedList = splashedList;
                const list = await getDeviceCount(newValue)
                const splashedList = await getDeviceList(newValue)
                console.log(list)
                console.log(splashedList)
                const hierarchy = convertToHierarchy(newValue.slice(0, 6))
                const jsonPath = hierarchy.join('/')
                const jsonPathPre = hierarchy.slice(0, hierarchy.length - 1).join('/')
                scalingJudgment = scalingJudgment.map(item => ({ ...item, show: true }))
                scalingJudgment[0].gJson = null
                scalingJudgment[0].splashedList = splashedList
        active = null
        // 省
        if (hierarchy.length === 1) {
@@ -127,29 +152,29 @@
              ...item,
              data: list.flatMap(item => item.childrens || []).find(item1 => findFun(item1, item)),
            })),
          };
          scalingJudgment[2].gJson = injectData(gJson2,list);
          const { lng, lat } = getCenterPoint(gJson2.features.map(item => item.properties.center));
          flyTo({ longitude: lng, latitude: lat }, 0, scalingJudgment[2].height);
                    }
                    scalingJudgment[2].gJson = injectData(gJson2, list)
                    const { lng, lat } = getCenterPoint(gJson2.features.map(item => item.properties.center))
                    flyTo({ longitude: lng, latitude: lat }, 0, scalingJudgment[2].height)
        }
        // 市
        if (hierarchy.length === 2) {
          scalingJudgment[2].gJson = null;
          scalingJudgment[2].show = false;
                    scalingJudgment[2].gJson = null
                    scalingJudgment[2].show = false
          const gJson1 = await getFiler(`${defaultDir}${jsonPath}/index.json`)
          scalingJudgment[1].gJson = injectData(gJson1,list);
          const center = getCenterPoint(gJson1.features.map(item => item.properties.center));
          flyTo({ longitude: center.lng, latitude: center.lat }, 0, scalingJudgment[1].height);
                    scalingJudgment[1].gJson = injectData(gJson1, list)
                    const center = getCenterPoint(gJson1.features.map(item => item.properties.center))
                    flyTo({ longitude: center.lng, latitude: center.lat }, 0, scalingJudgment[1].height)
        }
        // 区县
        if (hierarchy.length === 3) {
          scalingJudgment[1].gJson = null;
          scalingJudgment[1].show = false;
          scalingJudgment[2].gJson = null;
          scalingJudgment[2].show = false;
                    scalingJudgment[1].gJson = null
                    scalingJudgment[1].show = false
                    scalingJudgment[2].gJson = null
                    scalingJudgment[2].show = false
          const outlineGJson = await getOutLine(jsonPathPre,hierarchy)
          const center = outlineGJson.features[0].properties.center;
          flyTo({ longitude: center[0], latitude: center[1] }, 0, scalingJudgment[0].height);
                    const center = outlineGJson.features[0].properties.center
                    flyTo({ longitude: center[0], latitude: center[1] }, 0, scalingJudgment[0].height)
        }
        // 轮廓
        const outlineGJson = await getOutLine(jsonPathPre,hierarchy)
@@ -157,7 +182,7 @@
      }
    },
    { immediate: true, deep: true }
  );
    )
  //散点机巢
  function splashed(row) {
@@ -185,49 +210,50 @@
            data: item,
          },
        },
      });
    });
            })
        })
  }
  // 渲染轮廓
  const renderOutline = (item) => {
    item.outline && Cesium.GeoJsonDataSource.load(item.outline).then(dataSource => {
      viewer.dataSources.add(dataSource);
      const entities = dataSource.entities.values;
    const renderOutline = item => {
        item.outline &&
            Cesium.GeoJsonDataSource.load(item.outline).then(dataSource => {
                viewer.dataSources.add(dataSource)
                const entities = dataSource.entities.values
      entities.forEach(entity => {
        // 隐藏多边形填充
        entity.polygon.material = Cesium.Color.TRANSPARENT;
        entity.polygon.outline = false; // 关闭原生轮廓
                    entity.polygon.material = Cesium.Color.TRANSPARENT
                    entity.polygon.outline = false // 关闭原生轮廓
        // 创建独立折线作为轮廓
        const positions = entity.polygon.hierarchy.getValue().positions;
                    const positions = entity.polygon.hierarchy.getValue().positions
        viewer.entities.add({
          polyline: {
            positions: positions,
            width: 5, // 直接设置宽度
            material: new Cesium.PolylineGlowMaterialProperty({
              glowPower: 0.5,
              color: Cesium.Color.AQUA
                                color: Cesium.Color.AQUA,
            }),
            clampToGround: true // 贴地显示
                            clampToGround: true, // 贴地显示
                        },
                    })
                })
            })
          }
        });
      });
    });
  };
  // 聚合机巢
  const aggregation = (item, flyTo) => {
    if (!item.gJson) return;
        if (!item.gJson) return
    const featuresList = item.gJson.features.map(item => ({
      name: item.properties.name,
      position: item.properties.center,
      data: item.data,
      id: item.region_code,
    }));
        }))
    // 遍历特征并添加实体
    featuresList.forEach(feature => {
      if (!feature.position) return;
      const position = Cesium.Cartesian3.fromDegrees(feature.position[0], feature.position[1]);
            if (!feature.position) return
            const position = Cesium.Cartesian3.fromDegrees(feature.position[0], feature.position[1])
      viewer.entities.add({
        position: position,
        label: {
@@ -239,8 +265,8 @@
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -9),
        }
      });
                },
            })
      viewer.entities.add({
        id: feature.id,
        position: position,
@@ -262,22 +288,22 @@
            data: feature.data,
          },
        },
      });
    });
            })
        })
    // 加载新的 GeoJSON 数据
    Cesium.GeoJsonDataSource.load(item.gJson).then(dataSource => {
      viewer.dataSources.add(dataSource);
      item.dataSource = dataSource; // 保存数据源以便后续删除
            viewer.dataSources.add(dataSource)
            item.dataSource = dataSource // 保存数据源以便后续删除
      // 获取数据源中的实体
      const entities = dataSource.entities.values;
            const entities = dataSource.entities.values
      entities.forEach(entity => {
        entity.polygon.material = new Cesium.ColorMaterialProperty(
          Cesium.Color.YELLOW.withAlpha(0) // 透明填充
        );
        entity.polygon.outline = new Cesium.ConstantProperty(true); // 显示边框
        entity.polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.AQUAMARINE );
      });
                )
                entity.polygon.outline = new Cesium.ConstantProperty(true) // 显示边框
                entity.polygon.outlineColor = new Cesium.ConstantProperty(Cesium.Color.AQUAMARINE)
            })
      flyTo &&
        viewer.flyTo(dataSource, {
          offset: new Cesium.HeadingPitchRange(
@@ -286,93 +312,93 @@
            0 // range: 0 (默认距离)
          ),
          duration: 0.5,
        });
    });
  };
                })
        })
    }
  // 获取弹框box
  const getLabelDom = data => {
    const vNode = h(MapPopUpBox, { data, removeLabel });
    const tooltipContainer = document.createElement('div');
    tooltipContainer.id = 'mapPopUpBox';
    tooltipContainer.style.position = 'absolute';
    tooltipContainer.style.transform = 'translateY(-50%)';
    tooltipContainer.style.pointerEvents = 'none';
    document.querySelector('.page-index').append(tooltipContainer);
    render(vNode, tooltipContainer);
    return tooltipContainer;
  };
        const vNode = h(MapPopUpBox, { data, removeLabel })
        const tooltipContainer = document.createElement('div')
        tooltipContainer.id = 'mapPopUpBox'
        tooltipContainer.style.position = 'absolute'
        tooltipContainer.style.transform = 'translateY(-50%)'
        tooltipContainer.style.pointerEvents = 'none'
        document.querySelector('.page-index').append(tooltipContainer)
        render(vNode, tooltipContainer)
        return tooltipContainer
    }
  // 弹框位置刷新
  const labelBoxRender = () => {
    let dom = document.querySelector('#mapPopUpBox');
        let dom = document.querySelector('#mapPopUpBox')
    if (!dom) {
      dom = getLabelDom(currentEntity.properties.customData._value.data);
            dom = getLabelDom(currentEntity.properties.customData._value.data)
    }
    const screenPosition = viewer.scene.cartesianToCanvasCoordinates(positionC3);
        const screenPosition = viewer.scene.cartesianToCanvasCoordinates(positionC3)
    if (screenPosition) {
      dom.style.left = `${screenPosition.x}px`;
      dom.style.top = `${screenPosition.y}px`;
      dom.style.display = 'block';
            dom.style.left = `${screenPosition.x}px`
            dom.style.top = `${screenPosition.y}px`
            dom.style.display = 'block'
    }
  };
    }
  // 左键单机事件
  const singleMachineEvent = async click => {
    const pickedObject = viewer.scene.pick(click.position);
        const pickedObject = viewer.scene.pick(click.position)
    if (Cesium.defined(pickedObject) && pickedObject.id) {
      const entity = pickedObject.id;
      currentEntity = entity;
      positionC3 = entity?.position?._value;
      if (!positionC3) return;
      removeLabel();
            const entity = pickedObject.id
            currentEntity = entity
            positionC3 = entity?.position?._value
            if (!positionC3) return
            removeLabel()
      const customData = entity.properties.customData._value.data
      console.log(customData);
            console.log(customData)
      if (customData.device_sn){
        store.commit('setSingleUavHome', { id: '123' });
                store.commit('setSingleUavHome', { id: '123' })
        return
      }
      viewer.scene.postRender.addEventListener(labelBoxRender);
            viewer.scene.postRender.addEventListener(labelBoxRender)
    }
  };
    }
  const removeDom = () => {
    const dom = document.querySelector('#mapPopUpBox');
        const dom = document.querySelector('#mapPopUpBox')
    if (dom && dom.parentNode) {
      dom.parentNode.removeChild(dom);
            dom.parentNode.removeChild(dom)
    }
  };
    }
  // 移除 点 和 gjson 实体
  const removeEntities = () => {
    viewer.dataSources?.removeAll(true);
    viewer.entities?.removeAll();
  };
        viewer.dataSources?.removeAll(true)
        viewer.entities?.removeAll()
    }
  // 移除弹框标签
  const removeLabel = () => {
    viewer.scene.postRender.removeEventListener(labelBoxRender);
    removeDom();
  };
        viewer.scene.postRender.removeEventListener(labelBoxRender)
        removeDom()
    }
  // 移除所有监听事件,变量置空
  const removeAll = () => {
    removeEntities();
    removeLabel();
    viewer.camera.moveEnd.removeEventListener(determineScaling);
    handler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    handler?.destroy();
    viewer = null;
    active = null;
    handler = null;
    positionC3 = null;
    currentEntity = null;
  };
        removeEntities()
        removeLabel()
        viewer.camera.moveEnd.removeEventListener(determineScaling)
        handler?.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
        handler?.destroy()
        viewer = null
        active = null
        handler = null
        positionC3 = null
        currentEntity = null
    }
  const init = () => {
    viewer = window.$viewer;
    handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    handler.setInputAction(singleMachineEvent, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    listenerHeight();
  };
        viewer = window.$viewer
        handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
        handler.setInputAction(singleMachineEvent, Cesium.ScreenSpaceEventType.LEFT_CLICK)
        listenerHeight()
    }
  // onMounted(() => {
  //   nextTick(() => {
  //     viewer = window.$viewer;
@@ -382,5 +408,5 @@
  //   });
  // });
  return { init, removeAll };
};
    return { init, removeAll }
}
src/websocket/index.js
@@ -1,4 +1,4 @@
import ReconnectingWebSocket from 'reconnecting-websocket';
import ReconnectingWebSocket from 'reconnecting-websocket'
/**
 * ConnectWebSocket 类
@@ -6,69 +6,69 @@
 */
class ConnectWebSocket {
    _url;
    _socket;
    _hasInit;
    _messageHandler;
    _url
    _socket
    _hasInit
    _messageHandler
    constructor(url) {
        this._url = url;
        this._socket = null;
        this._hasInit = false;
        this._messageHandler = null;
        this._url = url
        this._socket = null
        this._hasInit = false
        this._messageHandler = null
    }
    initSocket() {
        if (this._hasInit) {
            return;
            return
        }
        if (!this._url) {
            return;
            return
        }
        // 会自动重连,无需处理重连逻辑
        this._socket = new ReconnectingWebSocket(this._url, [], {
            maxReconnectionDelay: 20000, // 断开后最大的重连时间: 20s,每多一次重连,会增加 1.3 倍,5 * 1.3 * 1.3 * 1.3...
            minReconnectionDelay: 5000, // 断开后最短的重连时间: 5s
            maxRetries: 5,
        });
        this._hasInit = true;
        })
        this._hasInit = true
        this._socket.addEventListener('open', this._onOpen.bind(this));
        this._socket.addEventListener('close', this._onClose.bind(this));
        this._socket.addEventListener('error', this._onError.bind(this));
        this._socket.addEventListener('message', this._onMessage.bind(this));
        this._socket.addEventListener('open', this._onOpen.bind(this))
        this._socket.addEventListener('close', this._onClose.bind(this))
        this._socket.addEventListener('error', this._onError.bind(this))
        this._socket.addEventListener('message', this._onMessage.bind(this))
    }
    _onOpen() {
        console.log('连接成功');
        console.log('连接成功')
    }
    _onClose() {
        console.log('连接已断开');
        console.log('连接已断开')
    }
    _onError() {
        console.log('连接 error');
        console.log('连接 error')
    }
    registerMessageHandler(messageHandler) {
        this._messageHandler = messageHandler;
        this._messageHandler = messageHandler
    }
    _onMessage(msg) {
        // const data = JSON.parse(msg.data);
        this._messageHandler && this._messageHandler(msg.data);
        this._messageHandler && this._messageHandler(msg.data)
    }
    sendMessage = (message) => {
    sendMessage = message => {
        // 目前只供AI聊天使用
        this._socket?.send(message)
        // this._socket?.send(JSON.stringify(message.data));
    };
    }
    close() {
        this._socket?.close();
        this._socket?.close()
    }
}
export default ConnectWebSocket;
export default ConnectWebSocket
src/websocket/util/config.js
@@ -1,14 +1,13 @@
import { ELocalStorageKey } from '@/utils/http/enums';
import { ELocalStorageKey } from '@/utils/http/enums'
export function getWebsocketUrl() {
    const token = localStorage.getItem(ELocalStorageKey.Token) || '';
    const url =
        import.meta.env.VITE_APP_WS_API_URL + '?x-auth-token=' + encodeURI(token);
    return url;
    const token = localStorage.getItem(ELocalStorageKey.Token) || ''
    const url = import.meta.env.VITE_APP_WS_API_URL + '?x-auth-token=' + encodeURI(token)
    return url
}
// AI 指令飞行
export function getAIWebsocketUrl() {
    const token = localStorage.getItem(ELocalStorageKey.Token) || '';
    const token = localStorage.getItem(ELocalStorageKey.Token) || ''
    const url = `${import.meta.env.VITE_APP_WS_API_URL}?x-auth-token=${encodeURI(token)}`
    return url;
    return url
}