Commit 7e9002af by 周志凯

[feat]: add auth

1 parent a846ef09
......@@ -156,10 +156,6 @@ html, body, #app {
transition: width 0.1s linear;
}
.move-animate {
/* animation: move 2s ease-in-out infinite; */
}
.result-progress__text {
display: inline-block;
margin: 0 5px;
......@@ -200,6 +196,41 @@ html, body, #app {
border-radius: 20px;
}
/* login */
#loginApp {
width: 100%;
height: 100%;
}
.login-container {
width: 100%;
height: 100%;
background: url(../image/login_bg.png) no-repeat;
background-size: 100% 100%;
text-align: right;
}
.login-form {
display: inline-block;
width: 20%;
padding-top: 30vh;
margin-right: 10%;
color: #fff;
box-sizing: border-box;
}
.login-title {
text-align: left;
}
input::-webkit-autofill {
background-color: transparent;
box-shadow: 0 0 0 1000px rgba(255, 255, 255, 0) inset !important;
-webkit-box-shadow: 0 0 0 1000px rgba(255, 255, 255, 0) inset !important;
-webkit-text-fill-color: #fff !important;
transition: background-clor 5000s ease-in-out 0s;
}
@keyframes move {
0% {
background-position: 0 0;
......
......@@ -7,16 +7,6 @@
<link rel="stylesheet" href="./css/common.css">
<link rel="stylesheet" href="./css/page.css">
<script src="./js/browser.min.js"></script>
<script
src="./js/jquery-3.1.0.min.js"
type="text/javascript"
charset="utf-8"
></script>
<!-- import Vue before Element -->
<script src="./js/vue.js"></script>
<!-- import JavaScript -->
<script src="./js/index.js"></script>
<script src="./js/common.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
......@@ -32,11 +22,11 @@
<el-radio-button label="compare" v-if="locationHref">数据比对</el-radio-button>
</el-radio-group>
</div>
<div v-show="dateFormat == 'rerun'">
<div v-show="dateFormat === 'rerun'">
<div class="param">
<div class="bloc-mall-box">
<div style="float: right;">
<span style="font-size:20px;">集团:</span>
<span>集团:</span>
<el-select
v-model="accountVal"
filterable
......@@ -72,7 +62,7 @@
</div>
<div class="bloc-mall-box">
<div style="float: left;margin-left:2%;">
<span style="font-size:20px;">商场:</span>
<span>商场:</span>
<el-select
v-model="mallVal"
filterable
......@@ -110,7 +100,7 @@
<div class="param" style="padding: 5px 0 15px;">
<div class="bloc-mall-box">
<div style="float: right;margin-right: 50px;">
<span style="font-size:20px;">开始日期:</span>
<span>开始日期:</span>
<el-date-picker
v-model="startTime"
type="date"
......@@ -123,7 +113,7 @@
</div>
<div class="bloc-mall-box">
<div style="float: left;margin-left:2%;">
<span style="font-size:20px;">结束日期:</span>
<span>结束日期:</span>
<el-date-picker
v-model="endTime"
type="date"
......@@ -225,7 +215,7 @@
</div>
</div>
</div>
<div v-show="dateFormat == 'repair'">
<div v-show="dateFormat === 'repair'">
<div class="data-type">
<div class="level">
<el-radio-group v-model="UrlType" size="small">
......@@ -239,6 +229,109 @@
</div>
<div v-show="UrlType == 'faceRecognitions'">
<div class="data-select">
<span>集团:</span>
<el-select
v-model="accountVal"
filterable
multiple
collapse-tags
clearable
placeholder="请选择集团"
class="mall-sel-box"
@change="accountchange(true)"
>
<div
:class="isAccoutSelAll ? 'sel-all-box selected' : 'sel-all-box'"
@click="selAllHandle('accout')"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">全选</span>
</div>
<el-option
v-for="item in accoutOpts"
:key="item.id"
:label="item.name"
:value="item.id"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">{{ item.name }}</span>
</el-option>
</el-select>
<span>商场/门店:</span>
<el-select
v-model="mallVal"
filterable
multiple
collapse-tags
clearable
placeholder="请选择商场"
class="mall-sel-box"
@change="mallchange(true)"
>
<div
:class="isMallSelAll ? 'sel-all-box selected' : 'sel-all-box'"
@click="selAllHandle()"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">全选</span>
</div>
<el-option
v-for="item in mallOpts"
:key="item.id"
:label="item.name"
:value="item.id"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">{{ item.name }}</span>
</el-option>
</el-select>
</div>
<div class="data-select">
<span>监控点名称:</span>
<el-select
v-model="gateVal"
filterable
clearable
placeholder="请选择监控点"
@change="getChannel"
>
<el-option
v-for="(item, index) in gateOpt"
:key="item.index"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
<span>设备序列号:</span>
<!-- <el-select v-model="deviceVal" filterable clearable placeholder="请选择设备序列号">
<el-option v-for="(item, index) in deviceOpt" :key="index" :label="item.name" :value="item.value">
</el-option>
</el-select> -->
<el-select
v-model="channelVal"
filterable
clearable
placeholder="请选择通道设备序列号"
>
<el-option
v-for="item in channelOpt"
:key="item.id"
:label="item.name"
:value="item.value"
>
</el-option>
</el-select>
</div>
<div class="data-select">
<span>源数据日期:</span>
<el-date-picker
v-model="sourceDate"
......@@ -288,43 +381,6 @@
</el-time-picker>
</div>
<div class="data-select">
<span>监控点名称:</span>
<el-select
v-model="gateVal"
filterable
clearable
placeholder="请选择监控点"
@change="getChannel"
>
<el-option
v-for="(item, index) in gateOpt"
:key="item.index"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
<span>设备序列号:</span>
<!-- <el-select v-model="deviceVal" filterable clearable placeholder="请选择设备序列号">
<el-option v-for="(item, index) in deviceOpt" :key="index" :label="item.name" :value="item.value">
</el-option>
</el-select> -->
<el-select
v-model="channelVal"
filterable
clearable
placeholder="请选择通道设备序列号"
>
<el-option
v-for="item in channelOpt"
:key="item.id"
:label="item.name"
:value="item.value"
>
</el-option>
</el-select>
</div>
<div class="data-select">
<el-button
type="primary"
:loading="butShow"
......@@ -375,6 +431,105 @@
</div>
<div v-show="UrlType == 'trafficRecognition'" class="data-type">
<div class="data-select">
<span>集团:</span>
<el-select
v-model="accountVal"
filterable
multiple
collapse-tags
clearable
placeholder="请选择集团"
class="mall-sel-box"
@change="accountchange"
>
<div
:class="isAccoutSelAll ? 'sel-all-box selected' : 'sel-all-box'"
@click="selAllHandle('accout')"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">全选</span>
</div>
<el-option
v-for="item in accoutOpts"
:key="item.id"
:label="item.name"
:value="item.id"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">{{ item.name }}</span>
</el-option>
</el-select>
<span>商场/门店:</span>
<el-select
v-model="mallVal"
filterable
multiple
collapse-tags
clearable
placeholder="请选择商场"
class="mall-sel-box"
@change="mallchange"
>
<div
:class="isMallSelAll ? 'sel-all-box selected' : 'sel-all-box'"
@click="selAllHandle()"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">全选</span>
</div>
<el-option
v-for="item in mallOpts"
:key="item.id"
:label="item.name"
:value="item.id"
>
<span class="custom-checkbox__input">
<span class="custom-checkbox__inner"></span>
</span>
<span style="padding-left: 5px;">{{ item.name }}</span>
</el-option>
</el-select>
</div>
<div class="data-select">
<span>监控点名称:</span>
<el-select
v-model="gateVal"
filterable
clearable
placeholder="请选择监控点"
@change="getChannel"
>
<el-option
v-for="(item, index) in gateOpt"
:key="item.index"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
<span>通道设备序列号:</span>
<el-select
v-model="channelVal"
filterable
clearable
placeholder="请选择通道设备序列号"
>
<el-option
v-for="item in channelOpt"
:key="item.id"
:label="item.name"
:value="item.value"
>
</el-option>
</el-select>
</div>
<div class="data-select">
<span>修补日期:</span>
<el-date-picker
v-model="repairDate"
......@@ -423,39 +578,6 @@
class="input-class"
></el-input>
</div>
<div class="data-select">
<span>监控点名称:</span>
<el-select
v-model="gateVal"
filterable
clearable
placeholder="请选择监控点"
@change="getChannel"
>
<el-option
v-for="(item, index) in gateOpt"
:key="item.index"
:label="item.name"
:value="item.id"
>
</el-option>
</el-select>
<span>通道设备序列号:</span>
<el-select
v-model="channelVal"
filterable
clearable
placeholder="请选择通道设备序列号"
>
<el-option
v-for="item in channelOpt"
:key="item.id"
:label="item.name"
:value="item.value"
>
</el-option>
</el-select>
</div>
<div class="data-select" style="margin-top: 0.8%;">
<el-button type="primary" @click="repairPreview"
>效果预览</el-button
......@@ -489,7 +611,7 @@
</div>
</div>
<!-- repair end -->
<div v-show="dateFormat == 'compare'">
<div v-show="dateFormat === 'compare'">
<div class="data-type">
<div class="level" style="margin-bottom: 10px">
<el-radio-group
......@@ -961,1125 +1083,22 @@
</div>
</div>
</div>
</body>
<script>
const trafficOptions = [
"mall/countData",
"floor/countData",
"zone/countData",
"gate/countData"
];
const faceOptions = [
"mall/faceSta",
"floor/faceSta",
"zone/faceSta",
"gate/faceSta"
];
// const TAB_API = {
// featureRevisit: '',
// featureLibRebuild: [],
// }
new Vue({
el: "#app",
data: function() {
return {
pickerOpts: {
disabledDate(time) {
return Date.parse(time) > Date.parse(new Date());
}
},
radio: "mall",
dateFormat: "rerun",
dateLevelList: [
{ label: 'rerun', name: '数据重跑' },
{ label: 'repair', name: '数据修补' },
{ label: 'revisitFeature', name: '特征重提' },
{ label: 'rebuildFeatureLib', name: '特征库重建' },
{ label: 'rematchPerson', name: '人员重新比对' }
],
UrlType: "trafficRecognition",
compareType: "custom",
count: null,
dateCount: null,
day: "",
hour: "",
min: "",
startDate: "",
endDate: "",
sourceDate: "",
sourceStartTime: "00:00:00",
sourceEndTime: "23:59:59",
aimsDate: "",
aimsStartTime: "00:00:00",
aimsEndTime: "23:59:59",
referenceDate: "",
repairDate: "",
accountVal: [],
mallVal: [],
mallOpts: [],
accountId: [],
accoutOpts: [],
deviceVal: "",
gateVal: "",
channelVal: "",
showDiv: true,
loading: "",
gateOpt: [],
deviceOpt: [],
channelOpt: [],
date: "",
butShow: false,
startShow: false,
tafficShow: false,
startRange: "0.85",
endRange: "1.2",
isMallSelAll: false,
isAccoutSelAll: false,
//全选
checkedTraffic: [],
checkAllTraffic: false,
isIndeterminateTraffic: false,
checkedFace: [],
checkAllFace: false,
isIndeterminateFace: false,
checkTraffic: [
{
name: "",
value: "mall/countData"
},
{
name: "",
value: "floor/countData"
},
{
name: "",
value: "zone/countData"
},
{
name: "",
value: "gate/countData"
}
],
checkFace: [
{
name: "",
value: "mall/faceSta"
},
{
name: "",
value: "floor/faceSta"
},
{
name: "",
value: "zone/faceSta"
},
{
name: "",
value: "gate/faceSta"
}
],
progressName: {
mallcountData: "商场客流",
floorcountData: "楼层客流",
zonecountData: "店铺客流",
gatecountData: "监控点客流",
mallfaceSta: "商场人脸",
floorfaceSta: "楼层人脸",
zonefaceSta: "店铺人脸",
gatefaceSta: "监控点人脸"
},
startTime: "",
endTime: "",
traffStartTime: "00:00:00",
traffEndTime: "23:59:59",
webSocketObj: {},
repairWebSocket: null,
dateTime: [],
progressList: [],
repairProgList: [],
traProgList: [],
tipShow: false,
tipStyle: {},
lineDate: "",
lineMallId: "",
lineMallName: "",
locationHref: false,
/// 特征重提
query: {
accountVal: [],
mallVal: [],
dateVal: null
},
featureRevisitType: 0,
featureLibRebuildType: 1,
rematchPersonType: 1,
featureRevisitList: [
{ label: '人脸+全身照特征', value: 0 },
{ label: '人脸特征', value: 1 },
{ label: '全身照特征', value: 2 },
{ label: '店员特征', value: 3 }
],
featureLibRebuildList: [
{ label: '店员库重建', value: 1 },
{ label: '顾客库重建', value: 2 }
],
rematchPersonList: [
{ label: '店员对比', value: 1 },
{ label: '顾客对比', value: 2 }
],
socket: null,
results: [],
startTiming: 0,
endTiming: 0,
footerText: ''
};
},
filters: {
formatTime(val) {
function autoPrefixZero(num) {
return num > 10 ? num : '0' + num
}
const day = parseInt(val / (24 * 60 * 60 * 1000)) + 1
const hour = parseInt(val % (24 * 60 * 60 * 1000) / (60 * 60 * 1000))
const minutes = parseInt(val % (60 * 60 * 1000) / (60 * 1000))
const seconds = parseInt(val % (60 * 1000) / 1000)
if (val < 1000 || val < 60 * 1000) {
return `${val % (60 * 1000) / 1000} 秒`
} else if (val < 60 * 60 * 1000) {
return `${autoPrefixZero(minutes)} 分钟 ${autoPrefixZero(seconds)} 秒`
} else if (val < 24 * 60 * 60 * 1000) {
return `${autoPrefixZero(hour)} 小时 ${autoPrefixZero(minutes)} 分钟 ${autoPrefixZero(seconds)} 秒`
} else {
return `${autoPrefixZero(day)}${autoPrefixZero(hour)} 小时 ${autoPrefixZero(minutes)} 分钟 ${autoPrefixZero(seconds)} 秒`
}
}
},
computed: {
isResultsShow() {
return this.dateFormat === 'revisitFeature' ||
this.dateFormat === 'rebuildFeatureLib' ||
this.dateFormat === 'rematchPerson'
},
isSendDateParam() {
if (
(this.dateFormat === 'rebuildFeatureLib'
&& this.featureLibRebuildType === 1
) || (
this.dateFormat === 'revisitFeature'
&& this.featureRevisitType === 3)
) {
return false
}
return true
},
totalTime() {
const { startTiming, endTiming } = this
return endTiming - startTiming
// return this.formatDateToStamp(endTiming) - this.formatDateToStamp(startTiming)
}
},
watch: {
accountVal: {
handler: function (val) {
if(val && val.length) {
this.query.accountVal = val
}
},
deep: true
},
mallVal: {
handler: function (val) {
if(val && val.length) {
this.query.mallVal = val
}
},
deep: true
},
dateFormat: function(val) {
var typeHandler = {
'revisitFeature': this.featureRevisitType,
'rebuildFeatureLib': this.featureLibRebuildType,
'rematchPerson': this.rematchPersonType
}
this.footerText = val === 'compare' ? '数据对比' : this.dateLevelList.find(item => item.label === val).name
this.socket && this.socket.close()
this.results.length && (this.results = [])
this.startTiming = this.endTiming = 0
this.query.type = typeof typeHandler[val] === 'undefined'
? null
: typeHandler[val]
},
featureRevisitType(val) {
this.query.type = val
},
featureLibRebuildType(val) {
this.query.type = val
},
rematchPersonType(val) {
this.query.type = val
}
},
created: function() {
this.locationHref =
location.href.indexOf("?super") != -1 ? true : false;
this.getAccount();
},
mounted: function() {
this.query.dateVal = this.createDate()
this.startTime = this.createDate();
this.endTime = this.createDate();
},
methods: {
createDate() {
var nowDate = new Date();
var day = nowDate.getDate();
var month = nowDate.getMonth() + 1;
var year = nowDate.getFullYear();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (day >= 0 && day <= 9) {
day = "0" + day;
}
return year + "-" + month + "-" + day;
},
getProgressName(val) {
return this.progressName[val];
},
getProgressStyle(stepCount, status, oldStepCount) {
if (stepCount == "stepType") {
if (status == "gatecountData" || status == "gatefaceSta") {
return { "margin-left": "448px", "font-size": "18px" };
} else {
return { "margin-left": "465px", "font-size": "18px" };
}
} else {
return {
width: (stepCount - oldStepCount) * 405 + "px",
"background-color": status ? "#409EFF" : "#f56c6c",
"margin-left": oldStepCount * 405 + 50 + "px"
};
}
},
lineOver(tag, dates, mallIds, mallNames) {
let evt = tag || window.event,
_top,
_left;
_top = window.innerHeight - evt.y;
_left = window.innerWidth - evt.x;
this.tipStyle = {
top: evt.y - 50 + "px",
left: evt.x + "px"
};
this.lineDate = dates;
this.lineMallId = mallIds.join(",");
this.lineMallName = mallNames;
this.tipShow = true;
},
lineOut() {
this.tipShow = false;
},
handleCheckAllChangeTraffic(val) {
// console.log('val',val)
this.checkedTraffic = val ? trafficOptions : [];
// console.log(this.checkedTraffic)
this.isIndeterminateTraffic = false;
},
handleCheckAllChangeFace(val) {
// console.log('val',val)
this.checkedFace = val ? faceOptions : [];
// console.log(this.checkedFace)
this.isIndeterminateFace = false;
},
handleCheckedCitiesChangeTraffic(value) {
// console.log(this.checkedTraffic)
let checkedCount = value.length;
this.checkAllTraffic = checkedCount === this.checkTraffic.length;
this.isIndeterminateTraffic =
checkedCount > 0 && checkedCount < this.checkTraffic.length;
},
handleCheckedCitiesChangeFace(value) {
// console.log(this.checkedFace)
let checkedCount = value.length;
this.checkAllFace = checkedCount === this.checkFace.length;
this.isIndeterminateFace =
checkedCount > 0 && checkedCount < this.checkFace.length;
},
accountchange() {
this.isAccoutSelAll = this.isAccoutSelAll
? this.accountVal.length < this.accoutOpts.length
? false
: true
: this.accountVal.length < this.accoutOpts.length
? false
: true;
if (this.accountVal.length > 0) {
this.getMall();
}
},
mallchange() {
this.isMallSelAll = this.isMallSelAll
? this.mallVal.length < this.mallOpts.length
? false
: true
: this.mallVal.length < this.mallOpts.length
? false
: true;
},
selAllHandle(level) {
if (level == "accout") {
if (this.isAccoutSelAll) {
this.accountVal = [];
this.isAccoutSelAll = false;
this.getMall();
} else {
this.accountVal = [];
this.accoutOpts.forEach(item => {
this.accountVal.push(item.id);
});
this.isAccoutSelAll = true;
this.getMall();
}
} else {
if (this.isMallSelAll) {
this.mallVal = [];
this.isMallSelAll = false;
} else {
this.mallVal = [];
this.mallOpts.forEach(item => {
this.mallVal.push(item.id);
});
this.isMallSelAll = true;
}
}
},
getAccount: function() {
var _this = this;
_this.accoutOpts = [];
$.ajax({
type: "get",
dataType: "json",
url: apiUrl + "accounts",
contentType: "application/json; charset=utf-8",
success: function(data) {
_this.accoutOpts = data;
if (_this.accoutOpts.length > 0) {
_this.accountVal = [_this.accoutOpts[0].id];
}
_this.getMall();
},
error: function(err) {
console.log(err);
}
});
},
getMall: function() {
var _this = this;
_this.mallOpts = [];
$.ajax({
type: "get",
dataType: "json",
url: apiUrl + "malls",
data: {
accountIds: _this.accountVal.join(",")
},
contentType: "application/json; charset=utf-8",
success: function(data) {
_this.mallOpts = data;
if (_this.mallOpts.length > 0) {
_this.mallVal = [_this.mallOpts[0].id];
}
_this.isMallSelAll =
_this.mallVal.length == _this.mallOpts.length ? true : false;
},
error: function(err) {
console.log(err);
}
});
},
getGate: function() {
var _this = this;
$.ajax({
type: "get",
dataType: "json",
url: apiUrl + "gates",
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log(data)
_this.gateOpt = data;
_this.gateVal = _this.gateOpt[0].id;
// _this.getDevice()
_this.getChannel();
},
error: function(err) {
console.log(err);
}
});
},
getDevice: function() {
var _this = this;
$.ajax({
type: "get",
dataType: "json",
url: apiUrl + "devices",
data: {
gateId: this.gateVal
},
contentType: "application/json; charset=utf-8",
success: function(data) {
// console.log(data)
_this.deviceOpt = [];
_this.deviceVal = "";
for (var i = 0; i < data.length; i++) {
var temp = {};
temp.name = data[i];
temp.value = data[i];
temp.id = i;
_this.deviceOpt.push(temp);
}
_this.deviceVal = _this.deviceOpt[0].value;
// console.log(_this.deviceOpt)
},
error: function(res) {
console.log(res);
}
});
},
dateLevel: function() {
if (this.dateFormat == "repair") {
this.getGate();
} else {
// this.getMall();
}
},
getLevel: function() {},
getNumber() {
this.repairProgList = [];
if (this.UrlType == "trafficRecognition") {
// this.getChannel()
} else {
// this.getChannel()
// this.getDevice()
}
},
getChannel() {
var _this = this;
$.ajax({
type: "get",
dataType: "json",
url: apiUrl + "channels",
contentType: "application/json; charset=utf-8",
data: {
gateId: this.gateVal
},
success: function(data) {
// console.log(data)
_this.channelOpt = [];
for (var i = 0; i < data.length; i++) {
var temp = {};
temp.name = data[i];
temp.value = data[i];
temp.id = i;
_this.channelOpt.push(temp);
}
_this.channelVal =
_this.channelOpt.length > 0 ? _this.channelOpt[0].value : "";
// console.log(_this.channelOpt)
},
error: function(res) {
console.log(res);
}
});
},
clearDiv() {
$("#showDiv").empty();
},
startData: function() {
this.progressList = [];
if (this.webSocketObj) {
for (var key in this.webSocketObj) {
this.webSocketObj[key].close();
}
}
let params = {},
startDate = "",
endDate = "";
params = {
startDate: this.startTime + " 00:00:00",
endDate: this.endTime + " 00:00:00",
mallIds: this.mallVal,
scheduleType: "",
mark: Date.parse(new Date())
};
this.checkedTraffic.forEach((item, index) => {
let _scheduleType = "";
let websocket = item.split("/");
websocket.forEach(item1 => {
_scheduleType += item1;
});
params.scheduleType = _scheduleType;
this.openWebSock(_scheduleType, item, params);
});
this.checkedFace.forEach((item, index) => {
let _scheduleType = "";
let websocket = item.split("/");
websocket.forEach(item1 => {
_scheduleType += item1;
});
params.scheduleType = _scheduleType;
this.openWebSock(_scheduleType, item, params);
});
},
openWebSock(wsUrl, url, params, processKey = 'progressList') {
// browser 兼容
// var wsHost = window.location.host;
var socketUrl = "";
var webSock_Url = webSockUrl ? webSockUrl : window.location.host;
var obj = {
stepList: []
};
obj.stepType = wsUrl;
obj.mark = params.mark;
if (!webSockUrl) {
webSock = window.location.host;
}
socketUrl = "ws://" + webSock_Url + "/recal/schedule/" + wsUrl;
this[processKey].push(obj);
var _this = this;
if ("WebSocket" in window) {
_this.webSocketObj[wsUrl] = new WebSocket(socketUrl);
} else if ("MozWebSocket" in window) {
_this.webSocketObj[wsUrl] = new MozWebSocket(socketUrl);
} else {
_this.webSocketObj[wsUrl] = new SockJS(socketUrl);
}
var param = JSON.parse(JSON.stringify(params));
try {
_this.webSocketObj[wsUrl].onopen = function(event) {
console.log("WebSocket:已连接");
_this.returnData(url, param);
};
_this.webSocketObj[wsUrl].onclosed = function() {
console.log("WebSocket关闭");
};
_this.webSocketObj[wsUrl].onmessage = function(evt) {
var msg = JSON.parse(evt.data);
_this[processKey].forEach((item, index) => {
if (
item.stepType == msg.scheduleType &&
item.mark == msg.mark
) {
var stepObj = {};
stepObj.dates = msg.dates;
stepObj.mallIds = msg.mallIds;
stepObj.mallNames = msg.mallNames;
stepObj.status = msg.status;
stepObj.stepCount = msg.stepCount;
item.stepList.push(stepObj);
item.precentsucess = msg.stepCount
? Math.floor(msg.stepCount * 100)
: 0;
}
});
// console.log('list',_this[processKey])
};
_this.webSocketObj[wsUrl].onerror = function(event) {
console.log("设备WebSocket:发生错误 ");
console.log(event);
};
} catch (error) {}
},
returnData: function(urls, params) {
// console.log(urls,params)
var _this = this;
$.ajax({
type: "post",
dataType: "json",
async: true,
url: apiUrl + urls,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
success: function(data) {
if (data) {
_this.loading = "";
_this.showDiv = true;
let text = "";
text +=
"本次共执行job " +
data.total +
" 个,成功 " +
data.success +
" 个,失败 " +
data.failed +
" 个.</br>";
if (data.failedJob && data.failedJob.length > 0) {
text += "-----失败job详情-----</br>";
text += data.failedJob.join("</br>");
if (data.data) {
text += "</br>" + data.data;
}
}
if (data.successJob && data.successJob.length > 0) {
text += "-----成功job详情-----</br>";
text += data.successJob.join("</br>");
}
text += "</br>-----------------------------------------------";
text += "</br>";
text += "</br>";
text += "</br>";
$("#showDiv").append(text);
}
},
error: function(res) {
_this.loading = "";
alert("Sorry, The requested property could not be found.");
}
});
},
getDateCount: function() {
var _this = this;
this.butShow = true;
var urls = "faceRecognitions/count";
var params = {
startTime: this.sourceDate + " " + this.sourceStartTime,
endTime: this.sourceDate + " " + this.sourceEndTime,
channelSerialnum: this.channelVal
};
$.ajax({
type: "get",
dataType: "json",
async: true,
url: apiUrl + urls,
data: params,
success: function(data) {
_this.butShow = false;
_this.dateCount = data;
},
error: function(res) {
_this.butShow = false;
console.log(res);
}
});
},
repairParams: function(type) {
this.repairProgList = [];
if (this.repairWebSocket) {
this.repairWebSocket.close();
}
var url = "",
params = {};
if (type == "face") {
this.startShow = true;
setTimeout(() => {
this.startShow = false;
}, 3000);
var url = "simulation/faceRecognition";
var params = {
sourceStartDate: this.sourceDate + " " + this.sourceStartTime,
sourceEndDate: this.sourceDate + " " + this.sourceEndTime,
targetStartDate: this.aimsDate + " " + this.aimsStartTime,
targetEndDate: this.aimsDate + " " + this.aimsEndTime,
channelSerialnum: this.channelVal,
count: Number(this.count),
scheduleType: "simulationfaceRecognition",
mark: Date.parse(new Date())
};
} else {
this.tafficShow = true;
setTimeout(() => {
this.tafficShow = false;
}, 3000);
url = "simulation/countData";
params = {
sourceStartDate: this.referenceDate + " " + this.traffStartTime,
sourceEndDate: this.referenceDate + " " + this.traffEndTime,
targetStartDate: this.repairDate + " " + this.traffStartTime,
targetEndDate: this.repairDate + " " + this.traffEndTime,
channelSerialnum: this.channelVal,
minFactor: this.startRange,
maxFactor: this.endRange,
scheduleType: "simulationcountData",
mark: Date.parse(new Date())
};
}
this.openFaceTraffWebSock(url, params);
},
compareParams: function(type) {
params = {
startDate: this.startTime + " 00:00:00",
endDate: this.endTime + " 00:00:00",
mallIds: this.mallVal,
scheduleType: "",
mark: Date.parse(new Date())
};
var url = "/mall/" + this.compareType;
this.returnData(url, params);
},
openFaceTraffWebSock(url, params) {
// browser 兼容
// var wsHost = window.location.host;
var socketUrl = "";
var webSock_Url = webSockUrl ? webSockUrl : window.location.host;
var obj = {
stepList: []
};
obj.stepType = params.scheduleType;
obj.mark = params.mark;
socketUrl =
"ws://" + webSock_Url + "/recal/schedule/" + params.scheduleType;
this.repairProgList.push(obj);
var _this = this;
if ("WebSocket" in window) {
_this.repairWebSocket = new WebSocket(socketUrl);
} else if ("MozWebSocket" in window) {
_this.repairWebSocket = new MozWebSocket(socketUrl);
} else {
_this.repairWebSocket = new SockJS(socketUrl);
}
var param = JSON.parse(JSON.stringify(params));
try {
_this.repairWebSocket.onopen = function(event) {
console.log("WebSocket:已连接");
_this.repairData(url, params);
};
_this.repairWebSocket.onclosed = function() {
console.log("WebSocket关闭");
};
_this.repairWebSocket.onmessage = function(evt) {
var msg = JSON.parse(evt.data);
_this.repairProgList.forEach((item, index) => {
if (
item.stepType == msg.scheduleType &&
item.mark == msg.mark
) {
var stepObj = {};
stepObj.counttime = msg.counttime;
stepObj.serialnum = msg.serialnum;
stepObj.status = msg.status;
stepObj.stepCount = msg.stepCount;
item.stepList.push(stepObj);
item.precentsucess = msg.stepCount
? Math.floor(msg.stepCount * 100)
: 0;
}
});
};
_this.webSocketObj[wsUrl].onerror = function(event) {
console.log("设备WebSocket:发生错误 ");
console.log(event);
};
} catch (error) {}
},
repairData(url, params) {
$.ajax({
type: "post",
dataType: "json",
async: true,
url: apiUrl + url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
success: function(data) {
if (data) {
let text = "";
text +=
"本次共执行job " +
data.total +
" 个,成功 " +
data.success +
" 个,失败 " +
data.failed +
" 个.</br>";
if (data.failedJob && data.failedJob.length > 0) {
text += "-----失败job详情-----</br>";
text += data.failedJob.join("</br>");
if (data.data) {
text += "</br>" + data.data;
}
}
if (data.successJob && data.successJob.length > 0) {
text += "-----成功job详情-----</br>";
text += data.successJob.join("</br>");
}
text += "</br>-----------------------------------------------";
text += "</br>";
text += "</br>";
text += "</br>";
$("#showDiv").append(text);
}
},
error: function(res) {
console.log(res);
}
});
},
repairPreview: function() {
var url = "preview/countData";
var params = {
sourceStartDate: this.referenceDate + " " + this.traffStartTime,
sourceEndDate: this.referenceDate + " " + this.traffEndTime,
targetStartDate: this.repairDate + " " + this.traffStartTime,
targetEndDate: this.repairDate + " " + this.traffEndTime,
channelSerialnum: this.channelVal,
minFactor: this.startRange,
maxFactor: this.endRange,
scheduleType: "simulationcountData",
mark: Date.parse(new Date())
};
$.ajax({
type: "post",
dataType: "json",
async: true,
url: apiUrl + url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
success: function(data) {
if (data) {
let text = "";
text +=
"本次共执行job " +
data.total +
" 个,成功 " +
data.success +
" 个,失败 " +
data.failed +
" 个.</br>";
if (data.failedJob && data.failedJob.length > 0) {
text += "-----失败job详情-----</br>";
text += data.failedJob.join("</br>");
if (data.data) {
text += "</br>" + data.data;
}
}
if (data.successJob && data.successJob.length > 0) {
text += "-----成功job详情-----</br>";
text += data.successJob.join("</br>");
if (data.data) {
console.log(data.data);
data.data.forEach(item => {
text +=
"</br>" +
" 设备序列号: " +
item.deviceSerialnum +
" 时间: " +
item.counttime +
" 进客流: " +
item.innum +
" 出客流: " +
item.outnum;
});
}
}
text += "</br>-----------------------------------------------";
text += "</br>";
text += "</br>";
text += "</br>";
$("#showDiv").append(text);
}
},
error: function(res) {
console.log(res);
}
});
},
onSearchClick: function() {
/////////////////////////////特征重提////////////////////////////////////////////////
// '/mall/feature'
// startDate,endDate,mallIds,scheduleType,featureType
// featureType==0 提取人体+人脸;featureType==1 提取人脸特征;featureType==2提取人体特征
/////////////////////////////特征库重建////////////////////////////////////////////////
// 重新建立顾客池 /mall/customPool
// 参数 mallIds,startDate,endDate,scheduleType
// 重建建立店员特征池 /mall/staffPool
// 参数 mallIds,scheduleType
/////////////////////////////人员重新对比////////////////////////////////////////////////
// 重新匹配顾客 /mall/custom
// 参数 mallIds,startDate,endDate,scheduleType
// 店员重新比对 /mall/staff
// 参数 mallIds,startDate,endDate,scheduleType
if (this.socket) {
this.socket.close()
this.socket = null
}
this.results = []
this.startTiming = 0
this.endTiming = 0
const TAB_API = {
revisitFeature: (val) => {
return val === 3 ? 'mall/staffFeature' : 'mall/feature'
},
rebuildFeatureLib: (val) => {
return val === 1 ? 'mall/staffPool' : 'mall/customPool'
},
rematchPerson: (val) => {
return val === 1 ? 'mall/staff' : 'mall/custom'
}
}
const { dateFormat, query, isSendDateParam } = this
const {
dateVal, mallVal, type
} = query
var urlPath = TAB_API[dateFormat](type)
var scheduleType = dateFormat + type
var parameter = {
// startDate: dateVal ? dateVal + ' 00:00:00' : null,
// endDate: dateVal ? dateVal + ' 23:59:59' : null,
mallIds: mallVal || null,
scheduleType: scheduleType,
// featureType: dateFormat === 'revisitFeature' ? type : null
}
if (isSendDateParam) {
parameter.startDate = dateVal + ' 00:00:00'
parameter.endDate = dateVal + ' 23:59:59'
}
if (dateFormat === 'revisitFeature') {
parameter.featureType = type
}
var socketParameter = {
scheduleType: scheduleType,
// callback: 'fetchApi',
callbackUrlPath: urlPath,
callbackParam: parameter
}
this.onSocketConnect(socketParameter)
},
/**
* websocket 连接
* @param {string} scheduleType
* @param {string} wsUrl
* @param {string} callbackUrlPath
* @param {object} callbackParam
*/
onSocketConnect({ scheduleType, callbackUrlPath, callbackParam }) {
var self = this,
wsUrl = webSockUrl || window.location.host,
socketUrl = "ws://" + wsUrl + "/recal/schedule/" + scheduleType
if ("WebSocket" in window) {
self.socket = new WebSocket(socketUrl);
} else if ("MozWebSocket" in window) {
self.socket = new MozWebSocket(socketUrl);
} else {
self.socket = new SockJS(socketUrl);
}
try {
self.socket.onopen = function(ev) {
self.startTiming = +new Date()
self.fetchApi(callbackUrlPath, callbackParam)
};
self.socket.onclosed = function() {
console.log('socket:onclose')
};
self.socket.onmessage = function(ev) {
var msg = JSON.parse(ev.data)
console.log('[onmessage]:', msg)
self.dealMessage(msg)
if (msg.stepCount === 1) {
self.endTiming = +new Date()
self.socket.close()
}
};
self.socket.onerror = function(ev) {
console.log("设备WebSocket:发生错误 ");
console.log(ev);
}
} catch (error) {
console.log('onSocketConnect:', error)
}
},
fetchApi(urlPath, parameter) {
const {
dateVal, mallVal, type
} = this.query
var self = this
$.ajax({
type: "post",
dataType: "json",
async: true,
url: apiUrl + urlPath,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parameter),
success: function(res) {
console.log(res)
},
error: function(err) {
console.log(err)
}
})
},
dealMessage(msg) {
// scheduleType
const { dates, mallIds, mallNames, status, stepCount, scheduleType, counter } = msg
var self = this
var resObj = {}
resObj.dates = dates
resObj.mallIds = mallIds
resObj.mallNames = mallNames
resObj.status = status
resObj.progress = self.floatToPercent(stepCount)
resObj.totalNum = 0
resObj.totalPage = 0
resObj.current = 0
resObj.curPageSize = 0
resObj.currentPage = 0
resObj.scheduleType = scheduleType
if (counter) {
// dataNum dateMallNum step totalData totalDate totalMall totalMallDateProduct allDataCount
resObj.totalNum = counter.allDataCount
resObj.totalPage = counter.totalMallDateProduct
resObj.current = counter.dataNum
resObj.curPageSize = counter.totalData
resObj.currentPage = counter.dateMallNum
}
if (self.results.length) {
const isSameScheduleType = self.results.some(item => item.scheduleType === scheduleType)
isSameScheduleType
? self.results.forEach(item => {
//
item.progress = self.floatToPercent(stepCount)
if (counter) {
item.totalNum = counter.allDataCount
item.totalPage = counter.totalMallDateProduct
item.current = counter.dataNum
item.curPageSize = counter.totalData
item.currentPage = counter.dateMallNum
}
})
: self.results.push(resObj)
resObj = {}
} else {
self.results.push(resObj)
resObj = {}
}
// 滚动至底部
// this.$nextTick(() => {
// this.$refs.scrollbarRef.wrap.scrollTop = this.$refs.scrollbarRef.wrap.scrollHeight
// })
},
formatDateToStamp(date) {
if (!date) return false
typeof date === 'string' && (date = new Date(date.replace(/-/g, '/')))
return date.getTime()
},
floatToPercent(floatNum) {
if (!floatNum) return 0
var formatNum = Math.floor(floatNum * 100)
return formatNum >= 100 ? 100 : formatNum
},
onClearClick() {
if (this.dateFormat === 'revisitFeature' ||
this.dateFormat === 'rebuildFeatureLib' ||
this.dateFormat === 'rematchPerson') {
this.startTiming = 0
this.endTiming = 0
this.results = []
}
// else {
document.getElementById('showDiv').innerHTML = ''
// }
}
}
});
</script>
<script src="./js/cookie.js"></script>
<script src="./js/permission.js"></script>
<!-- import Vue before Element -->
<script src="./js/vue.js"></script>
<!-- import JavaScript -->
<script src="./js/index.js"></script>
<script src="./js/axios.js"></script>
<script
src="./js/jquery-3.1.0.min.js"
type="text/javascript"
charset="utf-8"
></script>
<script src="./js/common.js" type="text/javascript" charset="utf-8"></script>
<script src="./js/request.js"></script>
<script src="./js/api.js"></script>
<script src="./js/home.js"></script>
</body>
</html>
const API = {
Login: '/users/login',
Accounts: '/accounts',
Malls: '/malls',
Gates: '/gates',
Devices: '/devices',
Channels: '/channels',
Mall: '/mall/',
FaceRecognitionsCount: '/faceRecognitions/count',
SimulationFaceRecognition: '/simulation/faceRecognition',
SimulationCountData: '/simulation/countData',
PreviewCountData: '/preview/countData',
mallStaffFeature: '/mall/staffFeature',
MallFeature: '/mall/feature',
MallStaffPool: '/mall/staffPool',
MallCustomPool: '/mall/customPool',
MallStaff: '/mall/staff',
MallCustom: '/mall/custom'
}
const WSAPI = {
RecalSchedule: '/recal/schedule/'
}
/* axios v0.19.2 | (c) 2020 by Matt Zabriskie */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["axios"] = factory();
else
root["axios"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var bind = __webpack_require__(3);
var Axios = __webpack_require__(4);
var mergeConfig = __webpack_require__(22);
var defaults = __webpack_require__(10);
/**
* Create an instance of Axios
*
* @param {Object} defaultConfig The default config for the instance
* @return {Axios} A new instance of Axios
*/
function createInstance(defaultConfig) {
var context = new Axios(defaultConfig);
var instance = bind(Axios.prototype.request, context);
// Copy axios.prototype to instance
utils.extend(instance, Axios.prototype, context);
// Copy context to instance
utils.extend(instance, context);
return instance;
}
// Create the default instance to be exported
var axios = createInstance(defaults);
// Expose Axios class to allow class inheritance
axios.Axios = Axios;
// Factory for creating new instances
axios.create = function create(instanceConfig) {
return createInstance(mergeConfig(axios.defaults, instanceConfig));
};
// Expose Cancel & CancelToken
axios.Cancel = __webpack_require__(23);
axios.CancelToken = __webpack_require__(24);
axios.isCancel = __webpack_require__(9);
// Expose all/spread
axios.all = function all(promises) {
return Promise.all(promises);
};
axios.spread = __webpack_require__(25);
module.exports = axios;
// Allow use of default import syntax in TypeScript
module.exports.default = axios;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var bind = __webpack_require__(3);
/*global toString:true*/
// utils is a library of generic helper functions non-specific to axios
var toString = Object.prototype.toString;
/**
* Determine if a value is an Array
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Array, otherwise false
*/
function isArray(val) {
return toString.call(val) === '[object Array]';
}
/**
* Determine if a value is undefined
*
* @param {Object} val The value to test
* @returns {boolean} True if the value is undefined, otherwise false
*/
function isUndefined(val) {
return typeof val === 'undefined';
}
/**
* Determine if a value is a Buffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Buffer, otherwise false
*/
function isBuffer(val) {
return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)
&& typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);
}
/**
* Determine if a value is an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an ArrayBuffer, otherwise false
*/
function isArrayBuffer(val) {
return toString.call(val) === '[object ArrayBuffer]';
}
/**
* Determine if a value is a FormData
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an FormData, otherwise false
*/
function isFormData(val) {
return (typeof FormData !== 'undefined') && (val instanceof FormData);
}
/**
* Determine if a value is a view on an ArrayBuffer
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
*/
function isArrayBufferView(val) {
var result;
if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
result = ArrayBuffer.isView(val);
} else {
result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
}
return result;
}
/**
* Determine if a value is a String
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a String, otherwise false
*/
function isString(val) {
return typeof val === 'string';
}
/**
* Determine if a value is a Number
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Number, otherwise false
*/
function isNumber(val) {
return typeof val === 'number';
}
/**
* Determine if a value is an Object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is an Object, otherwise false
*/
function isObject(val) {
return val !== null && typeof val === 'object';
}
/**
* Determine if a value is a Date
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Date, otherwise false
*/
function isDate(val) {
return toString.call(val) === '[object Date]';
}
/**
* Determine if a value is a File
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a File, otherwise false
*/
function isFile(val) {
return toString.call(val) === '[object File]';
}
/**
* Determine if a value is a Blob
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Blob, otherwise false
*/
function isBlob(val) {
return toString.call(val) === '[object Blob]';
}
/**
* Determine if a value is a Function
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Function, otherwise false
*/
function isFunction(val) {
return toString.call(val) === '[object Function]';
}
/**
* Determine if a value is a Stream
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a Stream, otherwise false
*/
function isStream(val) {
return isObject(val) && isFunction(val.pipe);
}
/**
* Determine if a value is a URLSearchParams object
*
* @param {Object} val The value to test
* @returns {boolean} True if value is a URLSearchParams object, otherwise false
*/
function isURLSearchParams(val) {
return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
}
/**
* Trim excess whitespace off the beginning and end of a string
*
* @param {String} str The String to trim
* @returns {String} The String freed of excess whitespace
*/
function trim(str) {
return str.replace(/^\s*/, '').replace(/\s*$/, '');
}
/**
* Determine if we're running in a standard browser environment
*
* This allows axios to run in a web worker, and react-native.
* Both environments support XMLHttpRequest, but not fully standard globals.
*
* web workers:
* typeof window -> undefined
* typeof document -> undefined
*
* react-native:
* navigator.product -> 'ReactNative'
* nativescript
* navigator.product -> 'NativeScript' or 'NS'
*/
function isStandardBrowserEnv() {
if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||
navigator.product === 'NativeScript' ||
navigator.product === 'NS')) {
return false;
}
return (
typeof window !== 'undefined' &&
typeof document !== 'undefined'
);
}
/**
* Iterate over an Array or an Object invoking a function for each item.
*
* If `obj` is an Array callback will be called passing
* the value, index, and complete array for each item.
*
* If 'obj' is an Object callback will be called passing
* the value, key, and complete object for each property.
*
* @param {Object|Array} obj The object to iterate
* @param {Function} fn The callback to invoke for each item
*/
function forEach(obj, fn) {
// Don't bother if no value provided
if (obj === null || typeof obj === 'undefined') {
return;
}
// Force an array if not already something iterable
if (typeof obj !== 'object') {
/*eslint no-param-reassign:0*/
obj = [obj];
}
if (isArray(obj)) {
// Iterate over array values
for (var i = 0, l = obj.length; i < l; i++) {
fn.call(null, obj[i], i, obj);
}
} else {
// Iterate over object keys
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
fn.call(null, obj[key], key, obj);
}
}
}
}
/**
* Accepts varargs expecting each argument to be an object, then
* immutably merges the properties of each object and returns result.
*
* When multiple objects contain the same key the later object in
* the arguments list will take precedence.
*
* Example:
*
* ```js
* var result = merge({foo: 123}, {foo: 456});
* console.log(result.foo); // outputs 456
* ```
*
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function merge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = merge(result[key], val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Function equal to merge with the difference being that no reference
* to original objects is kept.
*
* @see merge
* @param {Object} obj1 Object to merge
* @returns {Object} Result of all merge properties
*/
function deepMerge(/* obj1, obj2, obj3, ... */) {
var result = {};
function assignValue(val, key) {
if (typeof result[key] === 'object' && typeof val === 'object') {
result[key] = deepMerge(result[key], val);
} else if (typeof val === 'object') {
result[key] = deepMerge({}, val);
} else {
result[key] = val;
}
}
for (var i = 0, l = arguments.length; i < l; i++) {
forEach(arguments[i], assignValue);
}
return result;
}
/**
* Extends object a by mutably adding to it the properties of object b.
*
* @param {Object} a The object to be extended
* @param {Object} b The object to copy properties from
* @param {Object} thisArg The object to bind function to
* @return {Object} The resulting value of object a
*/
function extend(a, b, thisArg) {
forEach(b, function assignValue(val, key) {
if (thisArg && typeof val === 'function') {
a[key] = bind(val, thisArg);
} else {
a[key] = val;
}
});
return a;
}
module.exports = {
isArray: isArray,
isArrayBuffer: isArrayBuffer,
isBuffer: isBuffer,
isFormData: isFormData,
isArrayBufferView: isArrayBufferView,
isString: isString,
isNumber: isNumber,
isObject: isObject,
isUndefined: isUndefined,
isDate: isDate,
isFile: isFile,
isBlob: isBlob,
isFunction: isFunction,
isStream: isStream,
isURLSearchParams: isURLSearchParams,
isStandardBrowserEnv: isStandardBrowserEnv,
forEach: forEach,
merge: merge,
deepMerge: deepMerge,
extend: extend,
trim: trim
};
/***/ }),
/* 3 */
/***/ (function(module, exports) {
'use strict';
module.exports = function bind(fn, thisArg) {
return function wrap() {
var args = new Array(arguments.length);
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i];
}
return fn.apply(thisArg, args);
};
};
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var buildURL = __webpack_require__(5);
var InterceptorManager = __webpack_require__(6);
var dispatchRequest = __webpack_require__(7);
var mergeConfig = __webpack_require__(22);
/**
* Create a new instance of Axios
*
* @param {Object} instanceConfig The default config for the instance
*/
function Axios(instanceConfig) {
this.defaults = instanceConfig;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager()
};
}
/**
* Dispatch a request
*
* @param {Object} config The config specific for this request (merged with this.defaults)
*/
Axios.prototype.request = function request(config) {
/*eslint no-param-reassign:0*/
// Allow for axios('example/url'[, config]) a la fetch API
if (typeof config === 'string') {
config = arguments[1] || {};
config.url = arguments[0];
} else {
config = config || {};
}
config = mergeConfig(this.defaults, config);
// Set config.method
if (config.method) {
config.method = config.method.toLowerCase();
} else if (this.defaults.method) {
config.method = this.defaults.method.toLowerCase();
} else {
config.method = 'get';
}
// Hook up interceptors middleware
var chain = [dispatchRequest, undefined];
var promise = Promise.resolve(config);
this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
};
Axios.prototype.getUri = function getUri(config) {
config = mergeConfig(this.defaults, config);
return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, '');
};
// Provide aliases for supported request methods
utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url
}));
};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
/*eslint func-names:0*/
Axios.prototype[method] = function(url, data, config) {
return this.request(utils.merge(config || {}, {
method: method,
url: url,
data: data
}));
};
});
module.exports = Axios;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
function encode(val) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, '+').
replace(/%5B/gi, '[').
replace(/%5D/gi, ']');
}
/**
* Build a URL by appending params to the end
*
* @param {string} url The base of the url (e.g., http://www.google.com)
* @param {object} [params] The params to be appended
* @returns {string} The formatted url
*/
module.exports = function buildURL(url, params, paramsSerializer) {
/*eslint no-param-reassign:0*/
if (!params) {
return url;
}
var serializedParams;
if (paramsSerializer) {
serializedParams = paramsSerializer(params);
} else if (utils.isURLSearchParams(params)) {
serializedParams = params.toString();
} else {
var parts = [];
utils.forEach(params, function serialize(val, key) {
if (val === null || typeof val === 'undefined') {
return;
}
if (utils.isArray(val)) {
key = key + '[]';
} else {
val = [val];
}
utils.forEach(val, function parseValue(v) {
if (utils.isDate(v)) {
v = v.toISOString();
} else if (utils.isObject(v)) {
v = JSON.stringify(v);
}
parts.push(encode(key) + '=' + encode(v));
});
});
serializedParams = parts.join('&');
}
if (serializedParams) {
var hashmarkIndex = url.indexOf('#');
if (hashmarkIndex !== -1) {
url = url.slice(0, hashmarkIndex);
}
url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
}
return url;
};
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
function InterceptorManager() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
InterceptorManager.prototype.use = function use(fulfilled, rejected) {
this.handlers.push({
fulfilled: fulfilled,
rejected: rejected
});
return this.handlers.length - 1;
};
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*/
InterceptorManager.prototype.eject = function eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
};
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*/
InterceptorManager.prototype.forEach = function forEach(fn) {
utils.forEach(this.handlers, function forEachHandler(h) {
if (h !== null) {
fn(h);
}
});
};
module.exports = InterceptorManager;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var transformData = __webpack_require__(8);
var isCancel = __webpack_require__(9);
var defaults = __webpack_require__(10);
/**
* Throws a `Cancel` if cancellation has been requested.
*/
function throwIfCancellationRequested(config) {
if (config.cancelToken) {
config.cancelToken.throwIfRequested();
}
}
/**
* Dispatch a request to the server using the configured adapter.
*
* @param {object} config The config that is to be used for the request
* @returns {Promise} The Promise to be fulfilled
*/
module.exports = function dispatchRequest(config) {
throwIfCancellationRequested(config);
// Ensure headers exist
config.headers = config.headers || {};
// Transform request data
config.data = transformData(
config.data,
config.headers,
config.transformRequest
);
// Flatten headers
config.headers = utils.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers
);
utils.forEach(
['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
function cleanHeaderConfig(method) {
delete config.headers[method];
}
);
var adapter = config.adapter || defaults.adapter;
return adapter(config).then(function onAdapterResolution(response) {
throwIfCancellationRequested(config);
// Transform response data
response.data = transformData(
response.data,
response.headers,
config.transformResponse
);
return response;
}, function onAdapterRejection(reason) {
if (!isCancel(reason)) {
throwIfCancellationRequested(config);
// Transform response data
if (reason && reason.response) {
reason.response.data = transformData(
reason.response.data,
reason.response.headers,
config.transformResponse
);
}
}
return Promise.reject(reason);
});
};
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
/**
* Transform the data for a request or a response
*
* @param {Object|String} data The data to be transformed
* @param {Array} headers The headers for the request or response
* @param {Array|Function} fns A single function or Array of functions
* @returns {*} The resulting transformed data
*/
module.exports = function transformData(data, headers, fns) {
/*eslint no-param-reassign:0*/
utils.forEach(fns, function transform(fn) {
data = fn(data, headers);
});
return data;
};
/***/ }),
/* 9 */
/***/ (function(module, exports) {
'use strict';
module.exports = function isCancel(value) {
return !!(value && value.__CANCEL__);
};
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var normalizeHeaderName = __webpack_require__(11);
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
function setContentTypeIfUnset(headers, value) {
if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
headers['Content-Type'] = value;
}
}
function getDefaultAdapter() {
var adapter;
if (typeof XMLHttpRequest !== 'undefined') {
// For browsers use XHR adapter
adapter = __webpack_require__(12);
} else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {
// For node use HTTP adapter
adapter = __webpack_require__(12);
}
return adapter;
}
var defaults = {
adapter: getDefaultAdapter(),
transformRequest: [function transformRequest(data, headers) {
normalizeHeaderName(headers, 'Accept');
normalizeHeaderName(headers, 'Content-Type');
if (utils.isFormData(data) ||
utils.isArrayBuffer(data) ||
utils.isBuffer(data) ||
utils.isStream(data) ||
utils.isFile(data) ||
utils.isBlob(data)
) {
return data;
}
if (utils.isArrayBufferView(data)) {
return data.buffer;
}
if (utils.isURLSearchParams(data)) {
setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
return data.toString();
}
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
return data;
}],
transformResponse: [function transformResponse(data) {
/*eslint no-param-reassign:0*/
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
return data;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: -1,
validateStatus: function validateStatus(status) {
return status >= 200 && status < 300;
}
};
defaults.headers = {
common: {
'Accept': 'application/json, text/plain, */*'
}
};
utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});
module.exports = defaults;
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = function normalizeHeaderName(headers, normalizedName) {
utils.forEach(headers, function processHeader(value, name) {
if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
headers[normalizedName] = value;
delete headers[name];
}
});
};
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
var settle = __webpack_require__(13);
var buildURL = __webpack_require__(5);
var buildFullPath = __webpack_require__(16);
var parseHeaders = __webpack_require__(19);
var isURLSameOrigin = __webpack_require__(20);
var createError = __webpack_require__(14);
module.exports = function xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
if (utils.isFormData(requestData)) {
delete requestHeaders['Content-Type']; // Let the browser set it
}
var request = new XMLHttpRequest();
// HTTP basic authentication
if (config.auth) {
var username = config.auth.username || '';
var password = config.auth.password || '';
requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
}
var fullPath = buildFullPath(config.baseURL, config.url);
request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);
// Set the request timeout in MS
request.timeout = config.timeout;
// Listen for ready state
request.onreadystatechange = function handleLoad() {
if (!request || request.readyState !== 4) {
return;
}
// The request errored out and we didn't get a response, this will be
// handled by onerror instead
// With one exception: request that using file: protocol, most browsers
// will return status as 0 even though it's a successful request
if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
return;
}
// Prepare the response
var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
var response = {
data: responseData,
status: request.status,
statusText: request.statusText,
headers: responseHeaders,
config: config,
request: request
};
settle(resolve, reject, response);
// Clean up request
request = null;
};
// Handle browser request cancellation (as opposed to a manual cancellation)
request.onabort = function handleAbort() {
if (!request) {
return;
}
reject(createError('Request aborted', config, 'ECONNABORTED', request));
// Clean up request
request = null;
};
// Handle low level network errors
request.onerror = function handleError() {
// Real errors are hidden from us by the browser
// onerror should only fire if it's a network error
reject(createError('Network Error', config, null, request));
// Clean up request
request = null;
};
// Handle timeout
request.ontimeout = function handleTimeout() {
var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded';
if (config.timeoutErrorMessage) {
timeoutErrorMessage = config.timeoutErrorMessage;
}
reject(createError(timeoutErrorMessage, config, 'ECONNABORTED',
request));
// Clean up request
request = null;
};
// Add xsrf header
// This is only done if running in a standard browser environment.
// Specifically not if we're in a web worker, or react-native.
if (utils.isStandardBrowserEnv()) {
var cookies = __webpack_require__(21);
// Add xsrf header
var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?
cookies.read(config.xsrfCookieName) :
undefined;
if (xsrfValue) {
requestHeaders[config.xsrfHeaderName] = xsrfValue;
}
}
// Add headers to the request
if ('setRequestHeader' in request) {
utils.forEach(requestHeaders, function setRequestHeader(val, key) {
if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
// Remove Content-Type if data is undefined
delete requestHeaders[key];
} else {
// Otherwise add header to the request
request.setRequestHeader(key, val);
}
});
}
// Add withCredentials to request if needed
if (!utils.isUndefined(config.withCredentials)) {
request.withCredentials = !!config.withCredentials;
}
// Add responseType to request if needed
if (config.responseType) {
try {
request.responseType = config.responseType;
} catch (e) {
// Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
// But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
if (config.responseType !== 'json') {
throw e;
}
}
}
// Handle progress if needed
if (typeof config.onDownloadProgress === 'function') {
request.addEventListener('progress', config.onDownloadProgress);
}
// Not all browsers support upload events
if (typeof config.onUploadProgress === 'function' && request.upload) {
request.upload.addEventListener('progress', config.onUploadProgress);
}
if (config.cancelToken) {
// Handle cancellation
config.cancelToken.promise.then(function onCanceled(cancel) {
if (!request) {
return;
}
request.abort();
reject(cancel);
// Clean up request
request = null;
});
}
if (requestData === undefined) {
requestData = null;
}
// Send the request
request.send(requestData);
});
};
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var createError = __webpack_require__(14);
/**
* Resolve or reject a Promise based on response status.
*
* @param {Function} resolve A function that resolves the promise.
* @param {Function} reject A function that rejects the promise.
* @param {object} response The response.
*/
module.exports = function settle(resolve, reject, response) {
var validateStatus = response.config.validateStatus;
if (!validateStatus || validateStatus(response.status)) {
resolve(response);
} else {
reject(createError(
'Request failed with status code ' + response.status,
response.config,
null,
response.request,
response
));
}
};
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var enhanceError = __webpack_require__(15);
/**
* Create an Error with the specified message, config, error code, request and response.
*
* @param {string} message The error message.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The created error.
*/
module.exports = function createError(message, config, code, request, response) {
var error = new Error(message);
return enhanceError(error, config, code, request, response);
};
/***/ }),
/* 15 */
/***/ (function(module, exports) {
'use strict';
/**
* Update an Error with the specified config, error code, and response.
*
* @param {Error} error The error to update.
* @param {Object} config The config.
* @param {string} [code] The error code (for example, 'ECONNABORTED').
* @param {Object} [request] The request.
* @param {Object} [response] The response.
* @returns {Error} The error.
*/
module.exports = function enhanceError(error, config, code, request, response) {
error.config = config;
if (code) {
error.code = code;
}
error.request = request;
error.response = response;
error.isAxiosError = true;
error.toJSON = function() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: this.config,
code: this.code
};
};
return error;
};
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var isAbsoluteURL = __webpack_require__(17);
var combineURLs = __webpack_require__(18);
/**
* Creates a new URL by combining the baseURL with the requestedURL,
* only when the requestedURL is not already an absolute URL.
* If the requestURL is absolute, this function returns the requestedURL untouched.
*
* @param {string} baseURL The base URL
* @param {string} requestedURL Absolute or relative URL to combine
* @returns {string} The combined full path
*/
module.exports = function buildFullPath(baseURL, requestedURL) {
if (baseURL && !isAbsoluteURL(requestedURL)) {
return combineURLs(baseURL, requestedURL);
}
return requestedURL;
};
/***/ }),
/* 17 */
/***/ (function(module, exports) {
'use strict';
/**
* Determines whether the specified URL is absolute
*
* @param {string} url The URL to test
* @returns {boolean} True if the specified URL is absolute, otherwise false
*/
module.exports = function isAbsoluteURL(url) {
// A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
// RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
// by any combination of letters, digits, plus, period, or hyphen.
return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
};
/***/ }),
/* 18 */
/***/ (function(module, exports) {
'use strict';
/**
* Creates a new URL by combining the specified URLs
*
* @param {string} baseURL The base URL
* @param {string} relativeURL The relative URL
* @returns {string} The combined URL
*/
module.exports = function combineURLs(baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
: baseURL;
};
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
// Headers whose duplicates are ignored by node
// c.f. https://nodejs.org/api/http.html#http_message_headers
var ignoreDuplicateOf = [
'age', 'authorization', 'content-length', 'content-type', 'etag',
'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
'last-modified', 'location', 'max-forwards', 'proxy-authorization',
'referer', 'retry-after', 'user-agent'
];
/**
* Parse headers into an object
*
* ```
* Date: Wed, 27 Aug 2014 08:58:49 GMT
* Content-Type: application/json
* Connection: keep-alive
* Transfer-Encoding: chunked
* ```
*
* @param {String} headers Headers needing to be parsed
* @returns {Object} Headers parsed into an object
*/
module.exports = function parseHeaders(headers) {
var parsed = {};
var key;
var val;
var i;
if (!headers) { return parsed; }
utils.forEach(headers.split('\n'), function parser(line) {
i = line.indexOf(':');
key = utils.trim(line.substr(0, i)).toLowerCase();
val = utils.trim(line.substr(i + 1));
if (key) {
if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
return;
}
if (key === 'set-cookie') {
parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
} else {
parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
}
}
});
return parsed;
};
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs have full support of the APIs needed to test
// whether the request URL is of the same origin as current location.
(function standardBrowserEnv() {
var msie = /(msie|trident)/i.test(navigator.userAgent);
var urlParsingNode = document.createElement('a');
var originURL;
/**
* Parse a URL to discover it's components
*
* @param {String} url The URL to be parsed
* @returns {Object}
*/
function resolveURL(url) {
var href = url;
if (msie) {
// IE needs attribute set twice to normalize properties
urlParsingNode.setAttribute('href', href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
urlParsingNode.pathname :
'/' + urlParsingNode.pathname
};
}
originURL = resolveURL(window.location.href);
/**
* Determine if a URL shares the same origin as the current location
*
* @param {String} requestURL The URL to test
* @returns {boolean} True if URL shares the same origin, otherwise false
*/
return function isURLSameOrigin(requestURL) {
var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
return (parsed.protocol === originURL.protocol &&
parsed.host === originURL.host);
};
})() :
// Non standard browser envs (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return function isURLSameOrigin() {
return true;
};
})()
);
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
module.exports = (
utils.isStandardBrowserEnv() ?
// Standard browser envs support document.cookie
(function standardBrowserEnv() {
return {
write: function write(name, value, expires, path, domain, secure) {
var cookie = [];
cookie.push(name + '=' + encodeURIComponent(value));
if (utils.isNumber(expires)) {
cookie.push('expires=' + new Date(expires).toGMTString());
}
if (utils.isString(path)) {
cookie.push('path=' + path);
}
if (utils.isString(domain)) {
cookie.push('domain=' + domain);
}
if (secure === true) {
cookie.push('secure');
}
document.cookie = cookie.join('; ');
},
read: function read(name) {
var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
return (match ? decodeURIComponent(match[3]) : null);
},
remove: function remove(name) {
this.write(name, '', Date.now() - 86400000);
}
};
})() :
// Non standard browser env (web workers, react-native) lack needed support.
(function nonStandardBrowserEnv() {
return {
write: function write() {},
read: function read() { return null; },
remove: function remove() {}
};
})()
);
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var utils = __webpack_require__(2);
/**
* Config-specific merge-function which creates a new config-object
* by merging two configuration objects together.
*
* @param {Object} config1
* @param {Object} config2
* @returns {Object} New object resulting from merging config2 to config1
*/
module.exports = function mergeConfig(config1, config2) {
// eslint-disable-next-line no-param-reassign
config2 = config2 || {};
var config = {};
var valueFromConfig2Keys = ['url', 'method', 'params', 'data'];
var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy'];
var defaultToConfig2Keys = [
'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer',
'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName',
'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress',
'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent',
'httpsAgent', 'cancelToken', 'socketPath'
];
utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
}
});
utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) {
if (utils.isObject(config2[prop])) {
config[prop] = utils.deepMerge(config1[prop], config2[prop]);
} else if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (utils.isObject(config1[prop])) {
config[prop] = utils.deepMerge(config1[prop]);
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
var axiosKeys = valueFromConfig2Keys
.concat(mergeDeepPropertiesKeys)
.concat(defaultToConfig2Keys);
var otherKeys = Object
.keys(config2)
.filter(function filterAxiosKeys(key) {
return axiosKeys.indexOf(key) === -1;
});
utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) {
if (typeof config2[prop] !== 'undefined') {
config[prop] = config2[prop];
} else if (typeof config1[prop] !== 'undefined') {
config[prop] = config1[prop];
}
});
return config;
};
/***/ }),
/* 23 */
/***/ (function(module, exports) {
'use strict';
/**
* A `Cancel` is an object that is thrown when an operation is canceled.
*
* @class
* @param {string=} message The message.
*/
function Cancel(message) {
this.message = message;
}
Cancel.prototype.toString = function toString() {
return 'Cancel' + (this.message ? ': ' + this.message : '');
};
Cancel.prototype.__CANCEL__ = true;
module.exports = Cancel;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
'use strict';
var Cancel = __webpack_require__(23);
/**
* A `CancelToken` is an object that can be used to request cancellation of an operation.
*
* @class
* @param {Function} executor The executor function.
*/
function CancelToken(executor) {
if (typeof executor !== 'function') {
throw new TypeError('executor must be a function.');
}
var resolvePromise;
this.promise = new Promise(function promiseExecutor(resolve) {
resolvePromise = resolve;
});
var token = this;
executor(function cancel(message) {
if (token.reason) {
// Cancellation has already been requested
return;
}
token.reason = new Cancel(message);
resolvePromise(token.reason);
});
}
/**
* Throws a `Cancel` if cancellation has been requested.
*/
CancelToken.prototype.throwIfRequested = function throwIfRequested() {
if (this.reason) {
throw this.reason;
}
};
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
CancelToken.source = function source() {
var cancel;
var token = new CancelToken(function executor(c) {
cancel = c;
});
return {
token: token,
cancel: cancel
};
};
module.exports = CancelToken;
/***/ }),
/* 25 */
/***/ (function(module, exports) {
'use strict';
/**
* Syntactic sugar for invoking a function and expanding an array for arguments.
*
* Common use case would be to use `Function.prototype.apply`.
*
* ```js
* function f(x, y, z) {}
* var args = [1, 2, 3];
* f.apply(null, args);
* ```
*
* With `spread` this example can be re-written.
*
* ```js
* spread(function(x, y, z) {})([1, 2, 3]);
* ```
*
* @param {Function} callback
* @returns {Function}
*/
module.exports = function spread(callback) {
return function wrap(arr) {
return callback.apply(null, arr);
};
};
/***/ })
/******/ ])
});
;
//# sourceMappingURL=axios.map
\ No newline at end of file
window.apiUrl = ''
window.webSockUrl = ''
\ No newline at end of file
window._CONF_ = {
reportApiUrl: 'https://store.keliuyun.com/report',
apiUrl: 'http://192.168.9.146:8080',
webSockUrl: ''
}
/**
* [MDN](https://developer.mozilla.org/zh-CN/docs/Web/API/Document/cookie#Syntax)
*/
const Cookies = {
get: function (sKey) {
return decodeURIComponent(
document.cookie.replace(
new RegExp(
"(?:(?:^|.*;)\\s*" +
encodeURIComponent(sKey).replace(/[-.+*]/g, "\\$&") +
"\\s*\\=\\s*([^;]*).*$)|^.*$"
), "$1"
)
) || null
},
/**
* 写入
* @param {string} sKey necessary
* @param {string} sValue necessary
* @param {number|null|date|object|Infinity|string} vEnd optional
* @param {string|null} sPath optional
* @param {string|null} sDomain optional
* @param {boolean|null} bSecure optional
*/
set: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey ||
/^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)
) {
return false
}
let sExpires = ''
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity
? '; expires=Fri, 31 Dec 9999 23:59:59 GMT'
: '; max-age=' + vEnd
break;
case String:
sExpires = '; expires=' + vEnd
break;
case Date:
sExpires = '; expires=' + vEnd.toUTCString()
break;
}
}
document.cookie = encodeURIComponent(sKey) + '=' +
encodeURIComponent(sValue) + sExpires +
(sDomain ? '; domain=' + sDomain : '') +
(sPath ? '; path=' + sPath : '') +
(bSecure ? '; secure' : '')
return true
},
remove: function (sKey, sPath, sDomain) {
if (!sKey || !this.has(sKey)) return false
document.cookie = encodeURIComponent(sKey) +
'=; expires=Thu, 01 Jan 1970 00:00:00 GMT' +
(sDomain ? '; domain=' + sDomain : '') +
(sPath ? '; path=' + sPath : '')
return true
},
has: function (sKey) {
return (
new RegExp('(?:^|;\\s*)' +
encodeURIComponent(sKey).replace(/[-.+*]/g, '\\$&') +
'\\s*\\='
)
).test(document.cookie)
},
keys: function () {
let aKeys = document.cookie.replace(
/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g,
''
).split(/\s*(?:\=[^;]*)?;\s*/)
for (let nIdx = 0;nIdx < aKeys.length;nIdx++) {
aKeys[nIdx] = decodeURIComponent(aKeys[nIdx])
}
return aKeys
}
}
const trafficOptions = [
"mall/countData",
"floor/countData",
"zone/countData",
"gate/countData"
];
const faceOptions = [
"mall/faceSta",
"floor/faceSta",
"zone/faceSta",
"gate/faceSta"
];
// const TAB_API = {
// featureRevisit: '',
// featureLibRebuild: [],
// }
new Vue({
el: "#app",
data: function() {
return {
pickerOpts: {
disabledDate(time) {
return Date.parse(time) > Date.parse(new Date());
}
},
radio: "mall",
dateFormat: "rerun",
dateLevelList: [
{ label: 'rerun', name: '数据重跑' },
{ label: 'repair', name: '数据修补' },
{ label: 'revisitFeature', name: '特征重提' },
{ label: 'rebuildFeatureLib', name: '特征库重建' },
{ label: 'rematchPerson', name: '人员重新比对' }
],
UrlType: "trafficRecognition",
compareType: "custom",
count: null,
dateCount: null,
day: "",
hour: "",
min: "",
startDate: "",
endDate: "",
sourceDate: "",
sourceStartTime: "00:00:00",
sourceEndTime: "23:59:59",
aimsDate: "",
aimsStartTime: "00:00:00",
aimsEndTime: "23:59:59",
referenceDate: "",
repairDate: "",
accountVal: [],
mallVal: [],
mallOpts: [],
accountId: [],
accoutOpts: [],
deviceVal: "",
gateVal: "",
channelVal: "",
showDiv: true,
loading: "",
gateOpt: [],
deviceOpt: [],
channelOpt: [],
date: "",
butShow: false,
startShow: false,
tafficShow: false,
startRange: "0.85",
endRange: "1.2",
isMallSelAll: false,
isAccoutSelAll: false,
//全选
checkedTraffic: [],
checkAllTraffic: false,
isIndeterminateTraffic: false,
checkedFace: [],
checkAllFace: false,
isIndeterminateFace: false,
checkTraffic: [
{
name: "",
value: "mall/countData"
},
{
name: "",
value: "floor/countData"
},
{
name: "",
value: "zone/countData"
},
{
name: "",
value: "gate/countData"
}
],
checkFace: [
{
name: "",
value: "mall/faceSta"
},
{
name: "",
value: "floor/faceSta"
},
{
name: "",
value: "zone/faceSta"
},
{
name: "",
value: "gate/faceSta"
}
],
progressName: {
mallcountData: "商场客流",
floorcountData: "楼层客流",
zonecountData: "店铺客流",
gatecountData: "监控点客流",
mallfaceSta: "商场人脸",
floorfaceSta: "楼层人脸",
zonefaceSta: "店铺人脸",
gatefaceSta: "监控点人脸"
},
startTime: "",
endTime: "",
traffStartTime: "00:00:00",
traffEndTime: "23:59:59",
webSocketObj: {},
repairWebSocket: null,
dateTime: [],
progressList: [],
repairProgList: [],
traProgList: [],
tipShow: false,
tipStyle: {},
lineDate: "",
lineMallId: "",
lineMallName: "",
locationHref: false,
/// 特征重提
query: {
accountVal: [],
mallVal: [],
dateVal: null
},
featureRevisitType: 0,
featureLibRebuildType: 1,
rematchPersonType: 1,
featureRevisitList: [
{ label: '人脸+全身照特征', value: 0 },
{ label: '人脸特征', value: 1 },
{ label: '全身照特征', value: 2 },
{ label: '店员特征', value: 3 }
],
featureLibRebuildList: [
{ label: '店员库重建', value: 1 },
{ label: '顾客库重建', value: 2 }
],
rematchPersonList: [
{ label: '店员对比', value: 1 },
{ label: '顾客对比', value: 2 }
],
socket: null,
results: [],
startTiming: 0,
endTiming: 0,
footerText: ''
};
},
filters: {
formatTime(val) {
function autoPrefixZero(num) {
return num > 10 ? num : '0' + num
}
const day = parseInt(val / (24 * 60 * 60 * 1000)) + 1
const hour = parseInt(val % (24 * 60 * 60 * 1000) / (60 * 60 * 1000))
const minutes = parseInt(val % (60 * 60 * 1000) / (60 * 1000))
const seconds = parseInt(val % (60 * 1000) / 1000)
if (val < 1000 || val < 60 * 1000) {
return `${val % (60 * 1000) / 1000} 秒`
} else if (val < 60 * 60 * 1000) {
return `${autoPrefixZero(minutes)} 分钟 ${autoPrefixZero(seconds)} 秒`
} else if (val < 24 * 60 * 60 * 1000) {
return `${autoPrefixZero(hour)} 小时 ${autoPrefixZero(minutes)} 分钟 ${autoPrefixZero(seconds)} 秒`
} else {
return `${autoPrefixZero(day)}${autoPrefixZero(hour)} 小时 ${autoPrefixZero(minutes)} 分钟 ${autoPrefixZero(seconds)} 秒`
}
}
},
computed: {
isResultsShow() {
return this.dateFormat === 'revisitFeature' ||
this.dateFormat === 'rebuildFeatureLib' ||
this.dateFormat === 'rematchPerson'
},
isSendDateParam() {
if (
(this.dateFormat === 'rebuildFeatureLib'
&& this.featureLibRebuildType === 1
) || (
this.dateFormat === 'revisitFeature'
&& this.featureRevisitType === 3)
) {
return false
}
return true
},
totalTime() {
const { startTiming, endTiming } = this
return endTiming - startTiming
// return this.formatDateToStamp(endTiming) - this.formatDateToStamp(startTiming)
}
},
watch: {
accountVal: {
handler: function (val) {
if(val && val.length) {
this.query.accountVal = val
}
},
deep: true
},
mallVal: {
handler: function (val) {
if(val && val.length) {
this.query.mallVal = val
}
},
deep: true
},
dateFormat: function(val) {
var typeHandler = {
'revisitFeature': this.featureRevisitType,
'rebuildFeatureLib': this.featureLibRebuildType,
'rematchPerson': this.rematchPersonType
}
this.footerText = val === 'compare' ? '数据对比' : this.dateLevelList.find(item => item.label === val).name
this.socket && this.socket.close()
this.results.length && (this.results = [])
this.startTiming = this.endTiming = 0
this.query.type = typeof typeHandler[val] === 'undefined'
? null
: typeHandler[val]
},
featureRevisitType(val) {
this.query.type = val
},
featureLibRebuildType(val) {
this.query.type = val
},
rematchPersonType(val) {
this.query.type = val
}
},
created: function() {
this.locationHref =
location.href.indexOf("?super") != -1 ? true : false;
this.getAccount();
},
mounted: function() {
this.query.dateVal = this.createDate()
this.startTime = this.createDate();
this.endTime = this.createDate();
},
methods: {
createDate() {
var nowDate = new Date();
var day = nowDate.getDate();
var month = nowDate.getMonth() + 1;
var year = nowDate.getFullYear();
if (month >= 1 && month <= 9) {
month = "0" + month;
}
if (day >= 0 && day <= 9) {
day = "0" + day;
}
return year + "-" + month + "-" + day;
},
getProgressName(val) {
return this.progressName[val];
},
getProgressStyle(stepCount, status, oldStepCount) {
if (stepCount == "stepType") {
if (status == "gatecountData" || status == "gatefaceSta") {
return { "margin-left": "448px", "font-size": "18px" };
} else {
return { "margin-left": "465px", "font-size": "18px" };
}
} else {
return {
width: (stepCount - oldStepCount) * 405 + "px",
"background-color": status ? "#409EFF" : "#f56c6c",
"margin-left": oldStepCount * 405 + 50 + "px"
};
}
},
lineOver(tag, dates, mallIds, mallNames) {
let evt = tag || window.event,
_top,
_left;
_top = window.innerHeight - evt.y;
_left = window.innerWidth - evt.x;
this.tipStyle = {
top: evt.y - 50 + "px",
left: evt.x + "px"
};
this.lineDate = dates;
this.lineMallId = mallIds.join(",");
this.lineMallName = mallNames;
this.tipShow = true;
},
lineOut() {
this.tipShow = false;
},
handleCheckAllChangeTraffic(val) {
// console.log('val',val)
this.checkedTraffic = val ? trafficOptions : [];
// console.log(this.checkedTraffic)
this.isIndeterminateTraffic = false;
},
handleCheckAllChangeFace(val) {
// console.log('val',val)
this.checkedFace = val ? faceOptions : [];
// console.log(this.checkedFace)
this.isIndeterminateFace = false;
},
handleCheckedCitiesChangeTraffic(value) {
// console.log(this.checkedTraffic)
let checkedCount = value.length;
this.checkAllTraffic = checkedCount === this.checkTraffic.length;
this.isIndeterminateTraffic =
checkedCount > 0 && checkedCount < this.checkTraffic.length;
},
handleCheckedCitiesChangeFace(value) {
// console.log(this.checkedFace)
let checkedCount = value.length;
this.checkAllFace = checkedCount === this.checkFace.length;
this.isIndeterminateFace =
checkedCount > 0 && checkedCount < this.checkFace.length;
},
accountchange(linkGate) {
this.isAccoutSelAll = this.isAccoutSelAll
? this.accountVal.length < this.accoutOpts.length
? false
: true
: this.accountVal.length < this.accoutOpts.length
? false
: true;
if (this.accountVal.length > 0) {
this.getMall(linkGate);
}
},
mallchange(linkGate) {
this.isMallSelAll = this.isMallSelAll
? this.mallVal.length < this.mallOpts.length
? false
: true
: this.mallVal.length < this.mallOpts.length
? false
: true;
if (linkGate) {
this.getGate()
}
},
selAllHandle(level) {
if (level == "accout") {
if (this.isAccoutSelAll) {
this.accountVal = [];
this.isAccoutSelAll = false;
this.getMall();
} else {
this.accountVal = [];
this.accoutOpts.forEach(item => {
this.accountVal.push(item.id);
});
this.isAccoutSelAll = true;
this.getMall();
}
} else {
if (this.isMallSelAll) {
this.mallVal = [];
this.isMallSelAll = false;
} else {
this.mallVal = [];
this.mallOpts.forEach(item => {
this.mallVal.push(item.id);
});
this.isMallSelAll = true;
}
}
},
getAccount: function() {
var _this = this;
_this.accoutOpts = [];
get(window._CONF_.apiUrl + API.Accounts).then(function(data) {
_this.accoutOpts = data;
if (_this.accoutOpts.length > 0) {
_this.accountVal = [_this.accoutOpts[0].id];
}
_this.getMall();
}).catch(err => {
console.log('err', err)
})
},
getMall: function() {
var _this = this;
_this.mallOpts = [];
get(window._CONF_.apiUrl + API.Malls, {
accountIds: _this.accountVal.join(",")
}).then(function(data) {
_this.mallOpts = data;
if (_this.mallOpts.length > 0) {
_this.mallVal = [_this.mallOpts[0].id];
}
_this.isMallSelAll =
_this.mallVal.length == _this.mallOpts.length ? true : false;
})
},
getGate: function() {
var _this = this;
get(window._CONF_.apiUrl + API.Gates, {
accountIds: _this.accountVal.join(","),
mallIds: _this.mallVal.join(',')
}).then(function(data) {
_this.gateOpt = data;
_this.gateVal = _this.gateOpt[0].id;
// _this.getDevice()
_this.getChannel();
})
},
getDevice: function() {
var _this = this;
get(window._CONF_.apiUrl + API.Devices, {
// accountIds: _this.accountVal.join(","),
// mallIds: _this.mallVal.join(','),
gateId: this.gateVal
}).then(function(data) {
_this.deviceOpt = [];
_this.deviceVal = "";
for (var i = 0; i < data.length; i++) {
var temp = {};
temp.name = data[i];
temp.value = data[i];
temp.id = i;
_this.deviceOpt.push(temp);
}
_this.deviceVal = _this.deviceOpt[0].value;
})
},
dateLevel: function() {
if (this.dateFormat == "repair") {
this.getGate();
} else {
// this.getMall();
}
},
getLevel: function() {},
getNumber() {
this.repairProgList = [];
if (this.UrlType == "trafficRecognition") {
// this.getChannel()
} else {
// this.getChannel()
// this.getDevice()
}
},
getChannel() {
var _this = this;
get(window._CONF_.apiUrl + API.Channels, {
// accountIds: _this.accountVal.join(","),
// mallIds: _this.mallVal.join(','),
gateId: this.gateVal
}).then(function(data) {
_this.channelOpt = [];
for (var i = 0; i < data.length; i++) {
var temp = {};
temp.name = data[i];
temp.value = data[i];
temp.id = i;
_this.channelOpt.push(temp);
}
_this.channelVal =
_this.channelOpt.length > 0 ? _this.channelOpt[0].value : "";
})
},
clearDiv() {
$("#showDiv").empty();
},
startData: function() {
this.progressList = [];
if (this.webSocketObj) {
for (var key in this.webSocketObj) {
this.webSocketObj[key].close();
}
}
let params = {},
startDate = "",
endDate = "";
params = {
startDate: this.startTime + " 00:00:00",
endDate: this.endTime + " 00:00:00",
mallIds: this.mallVal,
scheduleType: "",
mark: Date.parse(new Date())
};
this.checkedTraffic.forEach((item, index) => {
let _scheduleType = "";
let websocket = item.split("/");
websocket.forEach(item1 => {
_scheduleType += item1;
});
params.scheduleType = _scheduleType;
this.openWebSock(_scheduleType, item, params);
});
this.checkedFace.forEach((item, index) => {
let _scheduleType = "";
let websocket = item.split("/");
websocket.forEach(item1 => {
_scheduleType += item1;
});
params.scheduleType = _scheduleType;
this.openWebSock(_scheduleType, item, params);
});
},
openWebSock(wsUrl, url, params, processKey = 'progressList') {
// browser 兼容
// var wsHost = window.location.host;
var socketUrl = "";
var webSock_Url = window._CONF_.webSockUrl || window.location.host;
var obj = {
stepList: []
};
obj.stepType = wsUrl;
obj.mark = params.mark;
if (!webSockUrl) {
webSock = window.location.host;
}
socketUrl = "ws://" + webSock_Url + WSAPI.WSAPI + wsUrl;
this[processKey].push(obj);
var _this = this;
if ("WebSocket" in window) {
_this.webSocketObj[wsUrl] = new WebSocket(socketUrl);
} else if ("MozWebSocket" in window) {
_this.webSocketObj[wsUrl] = new MozWebSocket(socketUrl);
} else {
_this.webSocketObj[wsUrl] = new SockJS(socketUrl);
}
var param = JSON.parse(JSON.stringify(params));
try {
_this.webSocketObj[wsUrl].onopen = function(event) {
console.log("WebSocket:已连接");
_this.returnData(url, param);
};
_this.webSocketObj[wsUrl].onclosed = function() {
console.log("WebSocket关闭");
};
_this.webSocketObj[wsUrl].onmessage = function(evt) {
var msg = JSON.parse(evt.data);
_this[processKey].forEach((item, index) => {
if (
item.stepType == msg.scheduleType &&
item.mark == msg.mark
) {
var stepObj = {};
stepObj.dates = msg.dates;
stepObj.mallIds = msg.mallIds;
stepObj.mallNames = msg.mallNames;
stepObj.status = msg.status;
stepObj.stepCount = msg.stepCount;
item.stepList.push(stepObj);
item.precentsucess = msg.stepCount
? Math.floor(msg.stepCount * 100)
: 0;
}
});
// console.log('list',_this[processKey])
};
_this.webSocketObj[wsUrl].onerror = function(event) {
console.log("设备WebSocket:发生错误 ");
console.log(event);
};
} catch (error) {}
},
returnData: function(urls, params) {
// console.log(urls,params)
var _this = this;
post(window._CONF_.apiUrl + urls, JSON.stringify(params)).then(function(data) {
if (data) {
_this.loading = "";
_this.showDiv = true;
_this.renderResultToHtml(data)
}
}).catch(function(err) {
_this.loading = "";
alert("Sorry, The requested property could not be found.");
})
},
getDateCount: function() {
var _this = this;
this.butShow = true;
var params = {
startTime: this.sourceDate + " " + this.sourceStartTime,
endTime: this.sourceDate + " " + this.sourceEndTime,
channelSerialnum: this.channelVal
};
get(window._CONF_.apiUrl + API.FaceRecognitionsCount, params).then(function(data) {
_this.butShow = false;
_this.dateCount = data;
}).catch(function(err) {
_this.butShow = false;
console.log(err);
})
// $.ajax({
// type: "get",
// dataType: "json",
// async: true,
// url: window._CONF_.apiUrl + urls,
// headers: {
// Authorization: Cookies.get('atoken')
// },
// data: params,
// success: function(data) {
// _this.butShow = false;
// _this.dateCount = data;
// },
// error: function(res) {
// _this.butShow = false;
// console.log(res);
// }
// });
},
repairParams: function(type) {
this.repairProgList = [];
if (this.repairWebSocket) {
this.repairWebSocket.close();
}
var url = "",
params = {};
if (type == "face") {
this.startShow = true;
setTimeout(() => {
this.startShow = false;
}, 3000);
var url = API.SimulationFaceRecognition;
var params = {
sourceStartDate: this.sourceDate + " " + this.sourceStartTime,
sourceEndDate: this.sourceDate + " " + this.sourceEndTime,
targetStartDate: this.aimsDate + " " + this.aimsStartTime,
targetEndDate: this.aimsDate + " " + this.aimsEndTime,
channelSerialnum: this.channelVal,
count: Number(this.count),
scheduleType: "simulationfaceRecognition",
mark: Date.parse(new Date())
};
} else {
this.tafficShow = true;
setTimeout(() => {
this.tafficShow = false;
}, 3000);
url = API.SimulationCountData;
params = {
sourceStartDate: this.referenceDate + " " + this.traffStartTime,
sourceEndDate: this.referenceDate + " " + this.traffEndTime,
targetStartDate: this.repairDate + " " + this.traffStartTime,
targetEndDate: this.repairDate + " " + this.traffEndTime,
channelSerialnum: this.channelVal,
minFactor: this.startRange,
maxFactor: this.endRange,
scheduleType: "simulationcountData",
mark: Date.parse(new Date())
};
}
this.openFaceTraffWebSock(url, params);
},
compareParams: function(type) {
params = {
startDate: this.startTime + " 00:00:00",
endDate: this.endTime + " 00:00:00",
mallIds: this.mallVal,
scheduleType: "",
mark: Date.parse(new Date())
};
var url = API.Mall + this.compareType;
this.returnData(url, params);
},
openFaceTraffWebSock(url, params) {
// browser 兼容
// var wsHost = window.location.host;
var socketUrl = "";
var webSock_Url = window._CONF_.webSockUrl || window.location.host;
var obj = {
stepList: []
};
obj.stepType = params.scheduleType;
obj.mark = params.mark;
socketUrl =
"ws://" + webSock_Url + WSAPI.RecalSchedule + params.scheduleType;
this.repairProgList.push(obj);
var _this = this;
if ("WebSocket" in window) {
_this.repairWebSocket = new WebSocket(socketUrl);
} else if ("MozWebSocket" in window) {
_this.repairWebSocket = new MozWebSocket(socketUrl);
} else {
_this.repairWebSocket = new SockJS(socketUrl);
}
var param = JSON.parse(JSON.stringify(params));
try {
_this.repairWebSocket.onopen = function(event) {
console.log("WebSocket:已连接");
_this.repairData(url, params);
};
_this.repairWebSocket.onclosed = function() {
console.log("WebSocket关闭");
};
_this.repairWebSocket.onmessage = function(evt) {
var msg = JSON.parse(evt.data);
_this.repairProgList.forEach((item, index) => {
if (
item.stepType == msg.scheduleType &&
item.mark == msg.mark
) {
var stepObj = {};
stepObj.counttime = msg.counttime;
stepObj.serialnum = msg.serialnum;
stepObj.status = msg.status;
stepObj.stepCount = msg.stepCount;
item.stepList.push(stepObj);
item.precentsucess = msg.stepCount
? Math.floor(msg.stepCount * 100)
: 0;
}
});
};
_this.webSocketObj[wsUrl].onerror = function(event) {
console.log("设备WebSocket:发生错误 ");
console.log(event);
};
} catch (error) {}
},
repairData(url, params) {
let that = this
post(window._CONF_.apiUrl + url, JSON.stringify(params)).then(function(data) {
if (data) {
that.renderResultToHtml(data)
}
})
},
repairPreview: function() {
var params = {
sourceStartDate: this.referenceDate + " " + this.traffStartTime,
sourceEndDate: this.referenceDate + " " + this.traffEndTime,
targetStartDate: this.repairDate + " " + this.traffStartTime,
targetEndDate: this.repairDate + " " + this.traffEndTime,
channelSerialnum: this.channelVal,
minFactor: this.startRange,
maxFactor: this.endRange,
scheduleType: "simulationcountData",
mark: Date.parse(new Date())
};
let that = this
post(window._CONF_.apiUrl + API.PreviewCountData, JSON.stringify(params)).then(function(data) {
if (data) {
that.renderResultToHtml(data, true)
}
})
},
renderResultToHtml(data, hasSccessDetail) {
let text = "本次共执行job " +
data.total +
" 个,成功 " +
data.success +
" 个,失败 " +
data.failed +
" 个.</br>";
if (data.failedJob && data.failedJob.length > 0) {
text += "-----失败job详情-----</br>";
text += data.failedJob.join("</br>");
if (data.data) {
text += "</br>" + data.data;
}
}
if (data.successJob && data.successJob.length > 0) {
text += "-----成功job详情-----</br>";
text += data.successJob.join("</br>");
if (hasSccessDetail) {
if (data.data) {
console.log(data.data);
data.data.forEach(item => {
text +=
"</br>" +
" 设备序列号: " +
item.deviceSerialnum +
" 时间: " +
item.counttime +
" 进客流: " +
item.innum +
" 出客流: " +
item.outnum;
});
}
}
}
text += "</br>-----------------------------------------------";
text += "</br>";
text += "</br>";
text += "</br>";
$("#showDiv").append(text);
},
onSearchClick: function() {
/////////////////////////////特征重提////////////////////////////////////////////////
// '/mall/feature'
// startDate,endDate,mallIds,scheduleType,featureType
// featureType==0 提取人体+人脸;featureType==1 提取人脸特征;featureType==2提取人体特征
/////////////////////////////特征库重建////////////////////////////////////////////////
// 重新建立顾客池 /mall/customPool
// 参数 mallIds,startDate,endDate,scheduleType
// 重建建立店员特征池 /mall/staffPool
// 参数 mallIds,scheduleType
/////////////////////////////人员重新对比////////////////////////////////////////////////
// 重新匹配顾客 /mall/custom
// 参数 mallIds,startDate,endDate,scheduleType
// 店员重新比对 /mall/staff
// 参数 mallIds,startDate,endDate,scheduleType
if (this.socket) {
this.socket.close()
this.socket = null
}
this.results = []
this.startTiming = 0
this.endTiming = 0
const TAB_API = {
revisitFeature: (val) => {
return val === 3 ? API.mallStaffFeature : API.MallFeature
},
rebuildFeatureLib: (val) => {
return val === 1 ? API.MallStaffPool : API.MallCustomPool
},
rematchPerson: (val) => {
return val === 1 ? API.MallStaff : API.MallCustom
}
}
const { dateFormat, query, isSendDateParam } = this
const {
dateVal, mallVal, type
} = query
var urlPath = TAB_API[dateFormat](type)
var scheduleType = dateFormat + type
var parameter = {
// startDate: dateVal ? dateVal + ' 00:00:00' : null,
// endDate: dateVal ? dateVal + ' 23:59:59' : null,
mallIds: mallVal || null,
scheduleType: scheduleType,
// featureType: dateFormat === 'revisitFeature' ? type : null
}
if (isSendDateParam) {
parameter.startDate = dateVal + ' 00:00:00'
parameter.endDate = dateVal + ' 23:59:59'
}
if (dateFormat === 'revisitFeature') {
parameter.featureType = type
}
var socketParameter = {
scheduleType: scheduleType,
// callback: 'fetchApi',
callbackUrlPath: urlPath,
callbackParam: parameter
}
this.onSocketConnect(socketParameter)
},
/**
* websocket 连接
* @param {string} scheduleType
* @param {string} wsUrl
* @param {string} callbackUrlPath
* @param {object} callbackParam
*/
onSocketConnect({ scheduleType, callbackUrlPath, callbackParam }) {
var self = this,
wsUrl = window._CONF_.webSockUrl || window.location.host,
socketUrl = "ws://" + wsUrl + WSAPI.RecalSchedule + scheduleType
if ("WebSocket" in window) {
self.socket = new WebSocket(socketUrl);
} else if ("MozWebSocket" in window) {
self.socket = new MozWebSocket(socketUrl);
} else {
self.socket = new SockJS(socketUrl);
}
try {
self.socket.onopen = function(ev) {
self.startTiming = +new Date()
self.fetchApi(callbackUrlPath, callbackParam)
};
self.socket.onclosed = function() {
console.log('socket:onclose')
};
self.socket.onmessage = function(ev) {
var msg = JSON.parse(ev.data)
console.log('[onmessage]:', msg)
self.dealMessage(msg)
if (msg.stepCount === 1) {
self.endTiming = +new Date()
self.socket.close()
}
};
self.socket.onerror = function(ev) {
console.log("设备WebSocket:发生错误 ");
console.log(ev);
}
} catch (error) {
console.log('onSocketConnect:', error)
}
},
fetchApi(urlPath, parameter) {
const {
dateVal, mallVal, type
} = this.query
var self = this
post(window._CONF_.apiUrl + urlPath, JSON.stringify(parameter)).then(function(res) {
console.log(res)
})
},
dealMessage(msg) {
// scheduleType
const { dates, mallIds, mallNames, status, stepCount, scheduleType, counter } = msg
var self = this
var resObj = {}
resObj.dates = dates
resObj.mallIds = mallIds
resObj.mallNames = mallNames
resObj.status = status
resObj.progress = self.floatToPercent(stepCount)
resObj.totalNum = 0
resObj.totalPage = 0
resObj.current = 0
resObj.curPageSize = 0
resObj.currentPage = 0
resObj.scheduleType = scheduleType
if (counter) {
// dataNum dateMallNum step totalData totalDate totalMall totalMallDateProduct allDataCount
resObj.totalNum = counter.allDataCount
resObj.totalPage = counter.totalMallDateProduct
resObj.current = counter.dataNum
resObj.curPageSize = counter.totalData
resObj.currentPage = counter.dateMallNum
}
if (self.results.length) {
const isSameScheduleType = self.results.some(item => item.scheduleType === scheduleType)
isSameScheduleType
? self.results.forEach(item => {
//
item.progress = self.floatToPercent(stepCount)
if (counter) {
item.totalNum = counter.allDataCount
item.totalPage = counter.totalMallDateProduct
item.current = counter.dataNum
item.curPageSize = counter.totalData
item.currentPage = counter.dateMallNum
}
})
: self.results.push(resObj)
resObj = {}
} else {
self.results.push(resObj)
resObj = {}
}
// 滚动至底部
// this.$nextTick(() => {
// this.$refs.scrollbarRef.wrap.scrollTop = this.$refs.scrollbarRef.wrap.scrollHeight
// })
},
formatDateToStamp(date) {
if (!date) return false
typeof date === 'string' && (date = new Date(date.replace(/-/g, '/')))
return date.getTime()
},
floatToPercent(floatNum) {
if (!floatNum) return 0
var formatNum = Math.floor(floatNum * 100)
return formatNum >= 100 ? 100 : formatNum
},
onClearClick() {
if (this.dateFormat === 'revisitFeature' ||
this.dateFormat === 'rebuildFeatureLib' ||
this.dateFormat === 'rematchPerson') {
this.startTiming = 0
this.endTiming = 0
this.results = []
}
// else {
document.getElementById('showDiv').innerHTML = ''
// }
}
}
});
(function() {
console.log('location', location, Cookies.get('atoken'))
if (!Cookies.get('atoken')) {
window.location.replace(window.location.href + 'login.html')
}
})()
\ No newline at end of file
const Axios = axios.create({
baseURL: window._CONF_.apiUrl,
timeout: 0,
withCredentials: true,
headers: {
"Content-Type": "application/json;charset=UTF-8"
}
})
Axios.interceptors.request.use(
config => {
const atoken = Cookies.get('atoken')
console.log('atoken', atoken)
atoken && (config.headers.Authorization = atoken)
return config
},
error => {
return Promise.reject(error)
}
)
Axios.interceptors.response.use(
res => {
console.log(res)
if (res.data.enote || res.data.code === 401) {
ELEMENT.MessageBox.alert('授权到期, 请重新登录', '提示', {
confirmButtonText: '确定',
callback: action => {
console.log('action', action)
window.location.replace(window.location.href + 'login.html')
}
});
} else {
return Promise.resolve(res.data)
}
},
error => {
console.log(error)
return Promise.reject(error)
}
)
function get(url, params = {}, config = {}) {
params['s'] = +new Date()
console.log('params', params)
return Axios.get(url, { ...config, params })
}
function post(url, params, config = {}) {
return Axios.post(url, params, config)
}
function deletes(url, params, config = {}) {
return Axios.delete(url, params, config)
}
function put(url, params, config = {}) {
return Axios.put(url, params, config)
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="./css/index.css" />
<link rel="stylesheet" href="./css/common.css">
<link rel="stylesheet" href="./css/page.css">
<script src="./js/browser.min.js"></script>
</head>
<body>
<!-- <div id="loginApp" v-cloak> -->
<div id="loginApp">
<div class="login-container">
<el-form :model="loginForm" :rules="rules" ref="loginForm" class="login-form">
<div class="login-header">
<h3 class="login-title">Login Form</h3>
</div>
<el-form-item prop="loginName">
<el-input ref="username" v-model.trim="loginForm.loginName"></el-input>
</el-form-item>
<el-form-item prop="password">
<el-input ref="password" type="password" v-model.trim="loginForm.password">
</el-input>
</el-form-item>
<el-button type="primary" style="width: 100%;" @click="submitForm">登 录</el-button>
</el-form>
</div>
</div>
<!-- import Vue before Element -->
<script src="./js/vue.js"></script>
<!-- import JavaScript -->
<script src="./js/index.js"></script>
<script src="./js/axios.js"></script>
<script src="./js/common.js" type="text/javascript" charset="utf-8"></script>
<script src="./js/cookie.js"></script>
<script src="./js/request.js"></script>
<script>
new Vue({
el: '#loginApp',
data() {
const validateUsername = (rule, value, callback) => {
if (!value) {
callback(new Error('请输入用户名'))
} else {
callback()
}
}
const validatePassword = (rule, value, callback) => {
const regexp = /^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/
if (!value) {
callback(new Error('请输入密码'))
} else if (!regexp.test(value)) {
callback(new Error('请输入不小于六位包含字母数字的密码!'))
} else {
callback()
}
}
return {
loginForm: {
loginName: '',
password: ''
},
// paswordType: 'password',
rules: {
loginName: [
{ required: true, trigger: 'blur', validator: validateUsername }
],
password: [
{ required: true, trigger: 'blur', validator: validatePassword }
]
}
}
},
mounted() {
// console.log({ get, post })
// if (this.loginForm.name === '') {
// this.$refs.username.focus()
// } else if (this.loginForm.password === '') {
// this.$refs.password.focus()
// }
},
methods: {
submitForm() {
this.$refs.loginForm.validate(valid => {
if (valid) {
post(
window._CONF_.reportApiUrl + '/users/login',
this.loginForm
).then(res => {
const { data, code } = res
if (code === 200) {
Cookies.set('atoken', data.atoken)
const currentPath = window.location.href
window.location.replace(currentPath.substr(0, currentPath.lastIndexOf('/') + 1))
}
})
.catch(err => {
console.log(err)
})
}
})
},
resetForm() {
this.loginForm.name = ''
this.loginForm.password = ''
this.$refs.loginForm.resetFields()
},
}
})
</script>
</body>
</html>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!