wenzheng.yang
2023-04-27 31e64e0e144815e6176c1b6b81eae8dc68688570
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import store from '../store/index.js'
//离线百度地图js-api
export function mymap(ak) {
    return new Promise(function(resolve, reject) {
 
        var script = document.createElement('script')
        script.type = 'text/javascript'
        // script.src = `http://47.92.123.194:8044/baidumap_apiV2_offline/baidumapv2/baidumap_offline_v2_20160921_min.js`
        // document.head.appendChild(script)
        script.src = `/static/baidumap_apiV2_offline/baidumapv2/baidumap_offline_v2_20160921.js`
        script.onerror = reject
        script.onload = this.getMap()
        document.head.appendChild(script)
        // resolve(1);
        // setTimeout(()=>{
        //     mapInit();
        // },1000)
    })
}
 
export function mapInit() {
    console.log("mapInit")
    var CenterPoint = "0,0"; //中心点
    var tileLayer = new BMap.TileLayer({
        isTransparentPng: true
    });
    tileLayer.getTilesUrl = function(tileCoord, zoom) {
        // console.log(zoom)
        var x = tileCoord.x;
        var y = tileCoord.y;
        return '/static/' + zoom + '/tile' + x + '_' + y + '.png';
    }
    var MyMap = new BMap.MapType('MyMap', tileLayer, {
        minZoom: 18,
        maxZoom: 19
    });
    var mmap = new BMap.Map("allmap", {
        mapType: MyMap
    }); //在百度地图容器中创建一个地图
    mmap.centerAndZoom(new BMap.Point(CenterPoint.split(',')[0], CenterPoint.split(',')[1]), (Number(18) + Number(19)) /
        2);
 
    mmap.addEventListener('click', function(e) {
        console.log(e.point)
    });
    mmap.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
    mmap.addControl(new BMap.ScaleControl()); //开启比例尺
}
 
/**
 * 参数数组arr的每一项为每一个点的:经度,纬度
 * 如 arr = [
 *       [116.427929, 39.904887],
 *       [116.427935, 39.904811],
 *       [116.427863, 39.904774],
 *       [116.42781, 39.90475],
 *       [116.427739, 39.904725],
 *       [116.42768, 39.904722],
 *       [116.427627, 39.904718],
 *       [116.427543, 39.904721],
 *       [116.427541, 39.90476],
 *       [116.427539, 39.904799],
 *       [116.427537, 39.904852],
 *       [116.427545, 39.904891],
 *       [116.427604, 39.904887],
 *       [116.427659, 39.904888],
 *       [116.427757, 39.904887],
 *       [116.427845, 39.904888],
 *   ]
 *   返回中心点的数组[经度,纬度]
 */
export function getPointsCenter(arr) {
    let centerLonLat = []
        if (arr.length) {
            const lon = []
            const lat = []
            const poly = [];
            for (let i = 0, len = arr.length; i < len; i++) {
                lon.push(arr[i][0])
                lat.push(arr[i][1])
            }
            for (let i = 0, len = lon.length; i < len; i++) {
                poly.push({
                    x: parseFloat(lon[i]),
                    y: parseFloat(lat[i]),
                    z: 0
                });
            }
            const sortedLongitudeArray = poly.map(item => item.x).sort();
            const sortedLatitudeArray = poly.map(item => item.y).sort();
            const centerLongitude = ((parseFloat(sortedLongitudeArray[0]) + parseFloat(sortedLongitudeArray[sortedLongitudeArray.length - 1])) / 2).toFixed(14);
            const centerLatitude = ((parseFloat(sortedLatitudeArray[0]) + parseFloat(sortedLatitudeArray[sortedLatitudeArray.length - 1])) / 2).toFixed(14);
            console.log(centerLongitude, centerLatitude);
            centerLonLat = [Number(centerLongitude), Number(centerLatitude)]
        }
        return centerLonLat;
}
 
 
//生成表、连接表
export function connChart(typeName) {
    let model = null
    if (typeName == 'label') {
        model = uni.$sql.model('label', {
            baoliu12: String, //绑定围栏
            baoliu4: String, //高度
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //序号
            p_department: String, //所属部门
            p_name: String, //绑定名称
            p_tagid: {
                type:String,
                unique: true, // 不能重复
                notNull: true, // 非空
            }, //标签ID
            p_status:{
                type: Number,
                default: 0 //默认值
            },//标签状态
            p_time:String//标签蜂鸣时间
        });
    } else if (typeName == 'fence') {
        model = uni.$sql.model('fence', {
            addtime: String, //添加围栏时间(绘制时间)
            baoliu1: String, //围栏高度(告警高度)
            baoliu7: String, //围栏是否启动(启动1未启动0)
            bumen: String, //关联部门
            centerpoint: String, //围栏中心点
            color: String, //围栏颜色
            floor: String, //围栏所在图层
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //序号
            max: String, //最大值(x,y)
            min: String, //最小值(x,y)
            name: String, //围栏名称
            shape: String, //围栏形状,多边形或矩形
            start: String, //围栏生效开始时间
            stop: String, //围栏生效结束时间
            type: String, //围栏类型,考勤区域,出去告警,进入告警,巡检区域,视频区域
            zuobiao: String ,//围栏坐标-xy坐标,单位米
            pts:String//围栏坐标-经纬度
        });
    } else if (typeName == 'work') {
        model = uni.$sql.model('work', {
            addtime: String, //添加时间
            beizhu: String, //备注
            department: String, //绑定部门
            fenceaddtime: String, //围栏添加时间
            fencename: String, //围栏名称
            high: String, //围栏高度
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //序号
            tagid: String, //绑定标签ID
            type: String, //操作步骤
        })
    } else if (typeName == 'alarm') {
        model = uni.$sql.model('alarm', {
            baoliu1: String, //坐标
            baoliu2: String, //围栏名称
            baoliu3: String, //关联部门
            objectid: String, //关联标签
            status: String, //状态
            time: String, //告警时间
            type: String, //告警原因
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //序号
        })
    } else if (typeName == 'base') {
        model = uni.$sql.model('base', {
            POSX: String, //基站X坐标
            POSY: String, //基站Y坐标
            POSZ: String, //基站Z坐标
            jingdu:String,
            weidu:String,
            anchorid: String, //基站ID
            anchorip: String, //基站的IP地址
            anchormode: String, //基站的状态在线1离线0
            gonglv: String, //基站功率
            greateTime: String, //基站更新时间
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //基站序号
            jiaozhundistance: String, //基站校准值
            layer: String, //基站所在的层
            liangcheng: String, //基站的量程,默认无限制
            version: String, //基站版本
            zu: String, //基站所在的分组
            updateGao:{
                type: String,
                default: '0.2' //默认值
            },//修正高、单位米
        })
    } else if (typeName == 'map') {
        model = uni.$sql.model('map', {
            addTime: String, //添加时间
            floor: {
                type: String,
                default: '0' //默认值
            }, //地图层
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //序号
            mapname: String, //地图名称
            filename: String, //文件真实名称
            filepath: String, //文件存储路径
            minzoom: String, //地图最小缩放级别
            maxzoom: String, //地图最大缩放级别
            x0_length: String, //x0原点X坐标
            x_Pixel: String, //图片实际长像素
            x_Truelength: String, //地图x实长厘米
            y0_width: String, //y0原点Y坐标
            y_Pixel: String, //图片实际宽像素
            y_Truewidth: String, //地图y实长厘米
        })
    } else if (typeName == 'department') {
        model = uni.$sql.model('department', {
            addTime: String, //添加时间
            id: {
                type: Number, // 类型
                primaryKey: true, // 主键
                unique: true, // 不能重复
                notNull: true, // 非空
                autoIncrement: true // 自增
            }, //序号
            department_id: String, //部门id
            department_name: String, //部门名称
        })
    } else if (typeName == 'sys') {
        model = uni.$sql.model('sys', {
            baoliu13: String, //视图刷新速率
            baoliu14: String, //标签数量上限
            baoliu15: String, //围栏数量上限
            real_trak_time: String, //实时轨迹时长
            udpAdress: String, //交互地址
            baoliu20: String, //交互端口
            gas_show: String, //是否显示围栏
            baoliu17: String, //是否缩略显示信息
            viewAnckid: String, //是否显示基站
            baoliu16: String, //是否显示轨迹
            yulan_map: String ,//百度地图切换
            show_password:String//是否输入密码
        })
    }
    return model;
}
 
// //在线百度地图js-api
// export function mymap_1(ak) {
//     return new Promise(function(resolve, reject) {
//         window.init = function() {
//             resolve(BMapLib)
//         }
//         var script = document.createElement('script')
//         script.type = 'text/javascript'
//         script.src = `https://api.map.baidu.com/library/AreaRestriction/1.2/src/AreaRestriction_min.js?callback=init`
//         script.onerror = reject
//         document.head.appendChild(script)
//     })
// }
 
//坐标转换-分换成度
export function transition(x,y){//x:经度,y:纬度
    var lng = 0.0
    var lat = 0.0
    x=x+''
    y=y+''
    lng = parseFloat(x.slice(0,2))+parseFloat(x.slice(2))/60
    lat = parseFloat(y.slice(0,3))+parseFloat(y.slice(3))/60 
    return {
        lng: lng,
        lat: lat
    }
}
 
//坐标转换-米换成度
export function coordinateConverter(x, y,map_x,map_y) { //x:横向坐标移动多少米,y:纵向坐标移动多少米 (可为负)
    var lng = 0.0000089 //1米的经度
    var lat = 0.0000089 //1米的纬度
    map_x=parseFloat(map_x) 
    map_y=parseFloat(map_y)
    map_x=(map_x/500).toFixed(9)
    map_y=(map_y/500).toFixed(9)
    // console.log(map_x,map_y)
    lng = parseFloat((lng * x /map_x).toFixed(9))
    lat = parseFloat((lat * y /map_y).toFixed(9))
    return {
        lng: lng,
        lat: lat
    }
}
 
/** 
        选择照片
        @parms method 选照片方式
*/
export function chooseImage(method) {
    return new Promise((resolve, reject) => {
        uni.chooseImage({
            count: 1, //上传图片的数量,默认是9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
            sourceType: ['album'], //album 从相册选图,camera 使用相机
            success: (res) => {
                const tempFiles = res.tempFiles; //拿到选择的图片,是一个数组
                var index = tempFiles[0].path.lastIndexOf("\/");
                var name = tempFiles[0].path.substring(index + 1, tempFiles[0].path
                    .length); //截取文件名称
                // for (var i = 0; i < tempFiles.length; i++) {
                //     var index = tempFiles[i].path.lastIndexOf("\/");
                //     var name = tempFiles[i].path.substring(index + 1, tempFiles[i].path
                //         .length); //截取文件名称
                //     //后缀名、大小限制
                //     if (!limitsEffect(name, tempFiles[i].size)) {
                //         resolve([])
                //     }
 
                //     const arrayBuffer = uni.getFileSystemManager().readFileSync(tempFiles[i]
                //         .path) //将文件二进制化
                //     tempFiles[i]['arrayBuffer'] = arrayBuffer
                //     tempFiles[i]['name'] = name
                // }
                return resolve({
                    tempFiles: tempFiles,
                    name: name
                });
            }
 
        });
 
    })
}
export function exportExcel(arr) {
    //要导出的数据
    // const res = [{
    //         name: "jack",
    //         age: 123,
    //         gender: "man"
    //     },
    //     {
    //         name: "marry",
    //         age: 666,
    //         gender: "man"
    //     },
    //     {
    //         name: "sun",
    //         age: 88888888,
    //         gender: "man"
    //     }
    // ]
    let str = arr.map(m => {
 
        let str2 = Object.values(m).map(mp => {
            return `<td>${mp}</td>`
        }).join('')
        return `<tr>${str2}</tr>`
    }).join('')
 
    let str1 = Object.keys(arr[0]).map(mp => {
        return `<td>${mp}</td>`
    }).join('')
    str = `<tr>${str1}</tr>${str}`
    console.log(str);
 
    let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office" 
        xmlns:x="urn:schemas-microsoft-com:office:excel" 
        xmlns="http://www.w3.org/TR/REC-html40">
        <head><!--[if gte mso 9]><xml encoding="UTF-8"><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
        <x:Name>sheet1</x:Name>
        <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
        </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head><body><table>${str}</table></body></html>`;
 
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function(fs) {
        // 可通过fs进行文件操作 
        console.log("Request file system success!");
        console.log(fs.name);
        fs.root.getFile(
            `ceshi.xlsx`, {
                create: true,
                exclusive: false
            },
            fileEntry => {
                console.log(1);
                fileEntry.createWriter(
                    writer => {
                        writer.onwrite = e => {
                            // that.count = 100;
                            // that.tap = `成功导出[${length}]条数据,文件路径为:${e.target.fileName}`;
                            console.log(e.target.fileName);
                            setTimeout(function() {
                                // that.proshow = false;
                                uni.openDocument({
                                    filePath: `file://${e.target.fileName}`, //这里必须加file://否则会报错打不开文件
                                    success: function(res) {
                                        console.log(2233, res);
 
                                    },
                                    fail(res) {
                                        console.log(res);
                                    }
                                });
                            }, 2000);
                        };
                        `在这里插入代码片`
                        writer.write(template);
                    },
                    function(e) {
                        uni.showToast({
                            title: '导出文件失败,请检查你的权限',
                            icon: 'none'
                        });
                    }
                );
            },
            e => {
                console.log(e);
            }
        );
 
    }, function(e) {
        alert("Request file system failed: " + e.message);
    });
}
 
//解压缩文件
export function decompress(name, filePath) {
    return new Promise((resolve, reject) => {
        var File = plus.android.importClass("java.io.File");
        // let environment = plus.android.importClass("android.os.Environment");
        // var sdRoot = environment.getExternalStorageDirectory();
        var dir = new File(`/storage/emulated/0/Android/data/uni.pictures/${name}/`)
        // if(!dir.exists()){
        //     console.log(sdRoot)
        //     console.log('创建目录')
        //     var logo=dir.mkdir()
        //     console.log(logo)
        // }
        var zipfile = filePath;
        var targetPath = `/storage/emulated/0/Android/data/uni.pictures/${name}/`;
        plus.zip.decompress(zipfile, targetPath,
            function() {
                console.log("解压成功!");
                console.log(dir.list())
                resolve({
                    dirList: dir.list()
                })
            },
            function(error) {
                console.log("解压失败!");
                reject()
            });
    })
}
 
/** 
        选择文件
        @parms time 超时
 */
export function chooseFile() {
    return new Promise((resolve, reject) => {
        var AfDocument = uni.requireNativePlugin("Aq-ChooseFile");
        AfDocument.openMode({
            size: '1', //选择总数量
            paths: ['/storage/emulated/0'], //自定义选择目录
            isDown: true, //是否下钻(true 筛选当前目录以下的所有文件,fales 只筛选当前目录文件) 
            types: [{
                name: '文档',
                value: ["doc", "wps", "docx", "xls", "xlsx", "pdf", "zip"]
            }, {
                name: '视频',
                value: ["mp4"]
            }, {
                name: '音乐',
                value: ['mp3', 'flac']
            }, {
                name: '图片',
                value: ['jpg', 'png']
            }]
        }, (res) => {
            console.log(res)
            // this.data = JSON.stringify(res);
            resolve(res.res[0])
        })
    })
}
 
/** 
        下载文件
        @parms url 文件地址
        @parms name 文件名称
*/
export function downloadFile(url, name) {
    uni.downloadFile({
        url: url, //文件下载地址
        success: (res) => {
            console.log(res)
            const filePath = res.tempFilePath
            const originName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length)
            const fileName = escape(originName)
            plus.io.resolveLocalFileSystemURL(filePath, orinFile => {
                plus.io.resolveLocalFileSystemURL('_downloads', dstDir => {
                    orinFile.moveTo(dstDir, fileName, dstFile => {
                        uni.openDocument({
                            filePath: plus.io.convertAbsoluteFileSystem(
                                dstFile.fullPath),
                            success: res => {
                                console.log('打开文档成功', dstFile)
                            },
                            fail: (err) => {
                                console.log(err)
                            }
                        })
                    }, err => {
                        console.log(err, err.message)
                    })
                })
            })
        },
        fail: (error) => {
            console.log(error)
        }
    });
}
 
 
 
export function saveFile(path){
    return new Promise((resolve, reject) => {
        uni.saveFile({
              tempFilePath: path,
              success: function (res) {
                  console.log(res)
                var savedFilePath = res.savedFilePath;
                resolve({savedFilePath:savedFilePath})
              }
        });
    })
}
 
// 获取WiFi信息
export function getWiFiIP() {
    // MainActivity
    var MainActivity = plus.android.runtimeMainActivity()
    // Context
    var Context = plus.android.importClass('android.content.Context')
    // WiFi 相关包  
    plus.android.importClass("android.net.wifi.WifiManager")
    plus.android.importClass("android.net.wifi.WifiInfo")
    plus.android.importClass("android.net.wifi.ScanResult")
    plus.android.importClass("java.util.ArrayList")
    // WiFi 管理实例
    var wifiManager = MainActivity.getSystemService(Context.WIFI_SERVICE)
    // 开启 WiFi
    // wifiManager.setWifiEnabled(true)
    // 当前连接 WiFi 信息  
    var wifiInfo = wifiManager.getConnectionInfo()
    console.log(wifiInfo.toString())
    var ipAddress = wifiInfo.getIpAddress()
    var ip = ((ipAddress & 0xff) + "." + (ipAddress>>8 & 0xff) + "." + (ipAddress>>16 & 0xff) + "." + (ipAddress>>24 & 0xff))
    console.log(ip)
    return ip
}