// -------------------------------------------------------------页面初始化操作

let myTaskListStateFalse = {}; // 我的任务暂存未读数据列表<id,T>
let plusStatus = false;
mui.plusReady(function() {
	if (plus) {
		plusStatus = true;
		console.log("plus初始化成功！")
		// 获取当前定位
		getLocalAddr();
		// plus start
	}
}, true);
// plus end
var mask = mui.createMask(function() {
	console.log("图片过大,压缩中!!!")
});
// 系统运行环境
let SYSTEM_ENVIRONMENT = "Beta";
let ENVIRONMENT = {
	// 本地测试环境（公司服务器DMS服务）
	DEV: {
		DMS_BASE_RUL: "http://121.43.55.7:2101",
		myTaskColumnId: 48, // 我的任务
		myTaskInfoColumnId: 1161, // 我的任务详情
		knowledgeRetrievalColumnId: 23, // 知识检索
		myMarksColumnId: 1218, // 我的标记栏目id
		myMarksModelId: 600 // 我的标记模型id
	},
	// 本地测试环境（政务内网DMS服务）
	Beta: {
		DMS_BASE_RUL: "http://117.131.26.69:10081",
		myTaskColumnId: 1794, // 我的任务
		myTaskInfoColumnId: 1537, // 我的任务详情
		knowledgeRetrievalColumnId: 1396, // 知识检索
		myMarksColumnId: 1538, // 我的标记栏目id
		myMarksModelId: 910 // 我的标记模型id
	}
}
let allCount = 0; // 数据总条数
let pageSize = 10; // 每页显示数据条数
let page = 0; // 初始页
let searchStateValue = 0;
let fileList = {};
// 每页配置信息（注意每一个key指的是主页的每个按钮的class）
const pageParam = {
	// 我的任务
	"myTask": {
		columnId: ENVIRONMENT[SYSTEM_ENVIRONMENT].myTaskColumnId,
		states: "0,1",
		userIdColumnName: "c_user_id",
		searchColumnName: "title",
		orderColumnName: "create_time",
		orderByType: 2,
		taskStatusTag: {
			0: {
				class: "WarningTag",
				title: "未读"
			},
			1: {
				class: "SuccessTag",
				title: "已读"
			}
		}
	},
	// 任务详情（任务和疑点关联表）
	"myTaskInfo": {
		columnId: ENVIRONMENT[SYSTEM_ENVIRONMENT].myTaskInfoColumnId,
		states: "0,1,2,3",
		userIdColumnName: "c_user_id",
		searchColumnName: "c_doubtful_points",
		orderColumnName: "c_create_time",
		orderByType: 2,
		params: {
			searchColumnName: "c_task_id",
			value: localStorage.getItem('taskId')
		},
		taskStatusTag: {
			0: {
				class: "WarningTag",
				title: "未核查"
			},
			1: {
				class: "SuccessTag",
				title: "已核查"
			}
		}
	},
	// 知识检索
	"knowledgeRetrieval": {
		columnId: ENVIRONMENT[SYSTEM_ENVIRONMENT].knowledgeRetrievalColumnId,
		states: "0,2,3",
		searchColumnName: "title",
		orderColumnName: "create_time",
		orderByType: 2,
		taskStatusTag: {
			1: {
				class: "WarningTag",
				title: "待审核"
			},
			2: {
				class: "BrandTag",
				title: "已审核"
			},
			3: {
				class: "SuccessTag",
				title: "已发布"
			},
			4: {
				class: "InfoTag",
				title: "已回退"
			},
			5: {
				class: "DangerTag",
				title: "已撤回"
			}
		}
	},
	// 我的标记
	"myMarks": {
		columnId: ENVIRONMENT[SYSTEM_ENVIRONMENT].myMarksColumnId,
		states: "0,1",
		searchColumnName: "title",
		orderColumnName: "create_time",
		orderByType: 2,
		taskStatusTag: {
			0: {
				class: "InfoTag",
				title: "未上传"
			},
			1: {
				class: "SuccessTag",
				title: "已上传"
			},
		}
	}
}
let page_e; // mui-pullRefresh
// 后台服务地址
const DMS_BASE_RUL = ENVIRONMENT[SYSTEM_ENVIRONMENT].DMS_BASE_RUL;
// 接口URL
const loginUrl = "/proxy_oauth/user/login";
// token验证
const getUserInfoUrl = "/proxy_oauth/api/user/getUserInfo";
// 分页获取dms数据
const getDataListUrl = "/proxy_dms/content/selectContentList";
// 上传文件接口（提示跨域？？？）
const proxyDmsFileUploadFile = "/proxy_dms/file/uploadFile";
// 更新dms数据
const updateContent = "/proxy_dms/content/updateContent";
// 更新dms状态
const updateAudit = "/proxy_dms/content/updateAudit";
// 添加dms数据
const addContent = "/proxy_dms/content/addContent";
// ajax配置
let requestSettins = {
	type: "POST",
	async: true,
	crossDomain: true,
	processData: false,
	contentType: false,
	timeout: 10000,
	headers: {
		"token": localStorage.getItem("token")
	}
};
// 记住密码变量
let isActive = localStorage.key('isActive') ? localStorage.getItem('isActive') : false;
// 标题自动填充
if (document.getElementById('data-list-title') && localStorage.getItem('taskName')) {
	document.getElementById('data-list-title').innerHTML = localStorage.getItem('taskName');
}
if (document.getElementById('taskName')) {
	if (localStorage.getItem('taskName')) {
		document.getElementById('taskName').style.display = "blck";
		document.getElementById('taskName').innerHTML = localStorage.getItem('taskName');
	} else {
		document.getElementById('taskName').style.display = "none";
	}
}
// 地图页面标题记忆
if (document.getElementById("mapTitle") && localStorage.getItem("mapTitle")) {
	document.getElementById('mapTitle').innerHTML = localStorage.getItem('mapTitle');
}
// 搜索框判断并初始化
if (document.getElementById('searchInput')) {
	mui.init({
		pullRefresh: {
			container: "#listMoveDom", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
			up: {
				height: 50, //可选.默认50.触发上拉加载拖动距离
				auto: true, //可选,默认false.自动上拉加载一次
				contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
				contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
				callback: getMoveMyTaskList //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			},
			// container: ".mui-content", //待刷新区域标识，querySelector能定位的css选择器均可，比如：id、.class等
			// down: {
			// 	style: 'circle', //必选，下拉刷新样式，目前支持原生5+ ‘circle’ 样式
			// 	color: '#2BD009', //可选，默认“#2BD009” 下拉刷新控件颜色
			// 	height: '50px', //可选,默认50px.下拉刷新控件的高度,
			// 	range: '100px', //可选 默认100px,控件可下拉拖拽的范围
			// 	offset: '0px', //可选 默认0px,下拉刷新控件的起始位置
			// 	// auto: true, //可选,默认false.首次加载自动上拉刷新一次
			// 	callback: getMoveMyTaskList //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
			// }
		}
	});
	muiInit();
	// 存在搜索框的话开始监听
	document.getElementById('searchInput').addEventListener('keypress', function(event) {
		if (event.keyCode == 13) {
			document.activeElement.blur(); // 收起模拟键盘
			resetPageInfo();
			event.preventDefault(); // 阻止页面刷新
		}
	})
} else {
	mui.init();
	muiInit();
}
// -------------------------------------------------------------自定义的mui事件监听事件
function muiInit() {
	// 获取设备类型，后续很有可能会用到
	if (mui.os.ios) {
		console.log('苹果设备')
		console.log('version：' + mui.os.version)
	} else if (mui.os.android) {
		console.log('安卓设备')
		console.log('version：' + mui.os.version)
	}
	// 如果在首页存在autoLogin元素，自动登录判断
	if (document.getElementById('autoLogin')) {
		console.log("存在autoLogin元素，自动登录判断")
		if (isActive) {
			document.getElementById('userName').value = localStorage.key('userName') ? localStorage
				.getItem(
					'userName') : '';
			document.getElementById('passWord').value = localStorage.key('passWord') ? localStorage
				.getItem(
					'passWord') : '';
		}
		document.getElementById('autoLogin').checked = isActive;
		if (localStorage.getItem('token') != null) {
			getUserInfo({
				dataType: "json",
				headers: {
					"token": localStorage.getItem('token')
				}
			}, function success(res, textStatus, xhr) {
				if (res.code == 200) {
					mui.alert('欢迎回来！', '系统提示', function() {
						// 跳转到主页
						mui.openWindow("pages/home.html", "home");
					});
				} else {
					mui.alert('token过期请重新登录！', '系统提示', function() {
						localStorage.removeItem("token");
					});
				}
			}, function error(xhr, type, errorThrown) {
				mui.alert('token过期请重新登录！', '系统提示', function() {
					localStorage.removeItem("token");
				});
			});
		}
	}
	// 监听用户点击状态触发事件
	mui('body').on('tap', '#loginButton', function() {
		login();
	}).on('tap', '.loginOut', function() {
		clearSearchValue();
		mui.toast('退出成功', '系统提示');
		localStorage.removeItem("token");
		mui.openWindow("../index.html", "login");
	}).on('tap', '.myTasks', function() {
		// 我的任务页面跳转
		clearSearchValue();
		mui.openWindow("myTask.html", "myTask")
	}).on('tap', '.customMarking', function() {
		// 自定义标记页面跳转
		clearSearchValue();
		if (localStorage.getItem("taskName")) {
			localStorage.removeItem('taskName');
		}
		localStorage.setItem("mapTitle", "自定义标记");
		mui.openWindow("map.html", "customMarking")
	}).on('tap', '.toMapPage', function() {
		// 自定义标记页面跳转
		clearSearchValue();
		localStorage.setItem("markerId", this.dataset.markerId);
		let pageName = document.getElementById('pageName') ? document.getElementById('pageName')
			.value :
			'myTask';
		if (pageName === "myTaskInfo") {
			localStorage.setItem("mapTitle", "我的任务");
		} else if (pageName === "myMarks") {
			localStorage.setItem("mapTitle", "我的标记");
		}
		mui.openWindow("map.html", "customMarking")
	}).on('tap', '.toMyTask', function() {
		// 我的任务页面跳转
		clearSearchValue();
		mui.openWindow("myTask.html", "myTask")
	}).on('tap', '.knowledgeRetrieval', function() {
		// 知识检索页面跳转
		clearSearchValue();
		mui.openWindow("lawsAndRegulations.html", "lawsAndRegulations")
	}).on('tap', '.myMarks', function() {
		// 我的标记页面跳转
		clearSearchValue();
		mui.openWindow("myMark.html", "myMarks")
	}).on('tap', '#addMyMarker', function() {
		// console.log(document.getElementById('taskName'));
		if (localStorage.getItem("latlngLat")) {
			localStorage.setItem('showMyMarkerBottomBox', 'true');
			let mapBottomBoxInnerHtml = `<div class="mapWarning">新建标记</div>
			<div class="displayFlex2"><div>标题:</div><input id="markerTitle" value="" placeholder="请添加标题" /></div>
			<div class="displayFlex2"><div>位置:</div><input id="markerLocalAddr" value="" placeholder="请描述位置" /></div>
			<div class="arrowdown" data-state="0"><span class="mui-icon mui-icon-arrowdown"></span></div>
		<div id="mapImageList">
			<div id="uploadImage">
				<div><span class="mui-icon mui-icon-plus"></span></div>
				<div><span>上传照片</span></div>
			</div>
		</div>
		
		<div>
			<p>描述:</p>
			<textarea name="" id="mapTextArea" placeholder="请添加描述" cols="30" rows="3"></textarea>
		</div>
			<div class="paperplaneMyMarker"><span class="mui-icon mui-icon-paperplane"></span>提交</div>`;
			document.getElementById('mapBottomBox').innerHTML = mapBottomBoxInnerHtml;
			document.getElementById('mapBottomBox').style.bottom = "0";
		} else {
			mui.alert('请先选择地图中的一个点', '系统提示')
		}
	}).on('tap', '.paperplaneMyMarker', function() {
		if (document.getElementById("markerTitle")) {
			let markerTitle = document.getElementById("markerTitle").value;
			let markerLocalAddr = document.getElementById("markerLocalAddr").value;
			let mapTextArea = document.getElementById("mapTextArea").value;
			let content = {
				title: markerTitle,
				content: "app自定义标记",
				c_date_time: new Date().getTime(),
				c_editorid: localStorage.getItem("userId"),
				c_boolean: true,
				c_content: {
					"type": "Feature",
					"properties": {
						"title": markerTitle,
						"desc": mapTextArea,
						"state": 0,
						"localAddr": markerLocalAddr,
						"fileList": fileList
					},
					"geometry": {
						"coordinates": [
							[
								[localStorage.getItem("latlngLat") * 1, localStorage
									.getItem("latlngLng") *
									1
								]
							]
						],
						"type": "Point"
					}
				}
			}
			let paramData = new FormData();
			paramData.append("content", JSON.stringify(content));
			paramData.append("columnId", ENVIRONMENT[SYSTEM_ENVIRONMENT].myMarksColumnId);
			paramData.append("modelId", ENVIRONMENT[SYSTEM_ENVIRONMENT].myMarksModelId);
			addContentData({
				data: paramData
			}, function(res) {
				let resData = JSON.parse(res);
				if (resData.code == 200) {
					mui.toast('提交成功');
					localStorage.setItem('showMyMarkerBottomBox', 'false');
					document.getElementById('mapBottomBox').style.bottom = "-100%";
				}
			}, function(e) {
				mui.alert(e, '系统提示')
			})
		} else {
			mui.alert('请先添加标题', '系统提示')
		}
	}).on('change', '#autoLogin', function() {
		isActive = this.checked ? "true" : "false";
		localStorage.setItem('isActive', isActive);
	}).on('tap', '.taskItem', function() {
		let taskId = this.dataset.taskId;
		let taskName = this.dataset.taskName;
		if (myTaskListStateFalse[taskId]) {
			let myTaskListStateFalseItem = myTaskListStateFalse[taskId];
			let content = {
				"id": myTaskListStateFalseItem.id,
				"title": myTaskListStateFalseItem.title,
				"content": myTaskListStateFalseItem.content
			};
			let columnId = Number(myTaskListStateFalseItem.column_id);
			let modelId = Number(myTaskListStateFalseItem.model_id);
			let paramData2 = new FormData();
			paramData2.append("columnId", columnId);
			paramData2.append("id", myTaskListStateFalseItem.id);
			paramData2.append("state", 1);
			updateAuditState({
				data: paramData2
			}, function(res) {
				let resData = JSON.parse(res);
				if (resData.code == 200) {
					// 我的任务详情页面跳转
					clearSearchValue();
					localStorage.setItem("taskId", taskId);
					localStorage.setItem("taskName", taskName);
					mui.openWindow({
						url: "myTaskInfo.html",
						id: "myTaskInfo",
						extras: {
							taskId: taskId,
							taskName: taskName
						}
					})
				}
			}, function(e) {
				console.log(e)
			})
		} else {
			// 我的任务详情页面跳转
			clearSearchValue();
			localStorage.setItem("taskId", taskId);
			localStorage.setItem("taskName", taskName);
			mui.openWindow({
				url: "myTaskInfo.html",
				id: "myTaskInfo",
				extras: {
					taskId: taskId,
					taskName: taskName
				}
			})
		}
	}).on('tap', '#reSearch', function() {
		// 数据列表刷新，搜索框重置
		mui.confirm("是否重置并刷新?", "系统提示", function(status) {
			if (status.index == 1) {
				clearSearchValue();
				resetPageInfo();
			}
		})
	}).on('tap', '#searchState', function() {
		var statePicker = new mui.PopPicker();
		let pageName = document.getElementById('pageName') ? document.getElementById('pageName')
			.value :
			'myTask';
		let pickerData = [{
			value: 0,
			text: "所有"
		}];
		for (let item in pageParam[pageName].taskStatusTag) {
			pickerData.push({
				value: item,
				text: pageParam[pageName].taskStatusTag[item].title
			})
		}
		statePicker.setData(pickerData);
		statePicker.show(function(items) {
			searchStateValue = items[0].value;
			document.getElementById('searchStateText').innerText = items[0].text;
			resetPageInfo();
		});
	}).on('tap', '.toBackPage', function() {
		window.history.back();
	}).on('tap', '.fileBox', function() {
		console.log('fileUrl', DMS_BASE_RUL + "/proxy_dms" + this.dataset.fileUrl)
		openRemoteFile(DMS_BASE_RUL + "/proxy_dms" + this.dataset.fileUrl);
	}).on('tap', '.openMyPhoneMap', function() {
		console.log("导航到：", this.dataset.lat, this.dataset.lng);
		openMyPhoneMap(this.dataset.lat, this.dataset.lng);
	}).on('tap', '.arrowdown', function() {
		if (this.dataset.state == 0) {
			mui.confirm('关闭后将不会保留表单信息，是否关闭？', '系统提示', ['确定', '取消'], function(val) {
				if (val.index == 0) {
					localStorage.setItem('showMyMarkerBottomBox', 'false');
					document.getElementById('mapBottomBox').style.bottom = "-100%";
				}
			})
		} else {
			localStorage.setItem('showMyMarkerBottomBox', 'false');
			document.getElementById('mapBottomBox').style.bottom = "-100%";
		}
	}).on('tap', '.paperplane', function() {
		let serverDataMap = JSON.parse(localStorage.getItem('serverDataMap'));
		let myMarkerData = serverDataMap[document.getElementById("myMarkerId").value];
		let fileList_ = localStorage.getItem("markerDataPropertiesFileList") != 'undefined' ?
			JSON.parse(
				localStorage.getItem("markerDataPropertiesFileList")) : {};
		Object.assign(fileList_, fileList);
		if (myMarkerData.c_content) {
			let c_content = JSON.parse(myMarkerData.c_content);
			c_content.properties.desc = document.getElementById("mapTextArea").value;
			c_content.properties.state = 1;
			c_content.properties.fileList = fileList_;
			myMarkerData.c_content = c_content;
		} else if (myMarkerData.c_doubtful_points) {
			let c_doubtful_points = JSON.parse(myMarkerData.c_doubtful_points);
			c_doubtful_points.properties.desc = document.getElementById("mapTextArea").value;
			c_doubtful_points.properties.state = 1;
			c_doubtful_points.properties.fileList = fileList_;
			myMarkerData.c_doubtful_points = c_doubtful_points;
		} else {
			mui.alert('空间信息获取失败，请检查代码后重试！', '系统异常')
			return false;
		}
		let content = {
			"id": myMarkerData.id,
			"title": myMarkerData.title,
			"content": myMarkerData.content
		};
		for (let key in myMarkerData) {
			if (key.indexOf('c_') == 0) {
				if (typeof myMarkerData[key] == 'object') {
					content[key + ""] = JSON.stringify(myMarkerData[key]);
				} else {
					content[key + ""] = myMarkerData[key];
				}
			}
		}
		let columnId = Number(myMarkerData.column_id);
		let modelId = Number(myMarkerData.model_id);
		let paramData = new FormData();
		paramData.append("content", JSON.stringify(content));
		paramData.append("columnId", columnId);
		paramData.append("modelId", modelId);
		paramData.append("id", myMarkerData.id);
		paramData.append("state", 1);
		let paramData2 = new FormData();
		paramData2.append("columnId", columnId);
		paramData2.append("id", myMarkerData.id);
		paramData2.append("state", 1);
		updateContentData({
			data: paramData
		}, function(res) {
			let resData = JSON.parse(res);
			if (resData.code == 200) {
				document.getElementById('mapBottomBox').style.bottom = "-100%";
				mui.toast('提交成功');
				sessionStorage.clear();
				updateAuditState({
					data: paramData2
				}, function(res) {
					let resData = JSON.parse(res);
					if (resData.code == 200) {
						window.history.back();
					}
				}, function(e) {
					console.log(e)
				})
			}
		}, function(e) {
			console.log(e)
		})
	}).on('tap', '#uploadImage', function() {
		// 触发文件上传按钮
		document.getElementById("uploadFileInput").click();
	}).on('tap', '.removeImage', function() {
		let that = this;
		delete fileList[this.id];
		mui.confirm('是否删除该图片', '系统提示', ['确定', '取消'], function(val) {
			if (val.index == 0) {
				that.remove();
				if (!document.getElementById("uploadImage")) {
					let addInput = document.createElement('div');
					addInput.id = "uploadImage";
					addInput.innerHTML = `<div><span class="mui-icon mui-icon-plus"></span></div>
									<div><span>上传照片</span></div>`;
					document.getElementById('mapImageList').append(addInput);
				}
			}
		})
	}).on('change', '#uploadFileInput', function(e) {
		// 获取上传的文件列表
		let mapImageListDom = document.getElementById('mapImageList');
		const file = e.target.files[0]
		this.fullFile = file
		if (fileList[file.name]) {
			mui.alert('请不要上传重复的图片', '系统提示');
			return false;
		} else if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
			mui.alert('请上传.png/.jpg/.jpeg格式的图片', '系统提示');
			return false;
		} else if (this.fullFile.size / 1024 / 1024 > 1) {
			// mui.alert('请上传不超过1MB的图片', '系统提示');
			mask.show(); //显示遮罩
			mui.toast('图片过大,压缩中!!!');
			imageConversion.compressAccurately(file, {
				size: 1024
			}).then(res => {
				// var file1 = new File([res], file.name, {
				// 	type: 'application/json',
				// 	lastModified: Date.now()
				// });
				blobToDataURI(res, function(base64) {
					// fileList[file.name] = base64;
					// 文件上传
					let content = {
						title: "appUploadFile-" + new Date().getTime(),
						content: file.name,
						c_file_base64: base64
					}
					fileList[file.name] = content.title;
					let paramData = new FormData();
					paramData.append("columnId", "1793");
					paramData.append("modelId", "1128");
					paramData.append("content", JSON.stringify(content));
					addContentData({
						data: paramData
					}, function(res) {
						console.log(res);
						mui.toast('文件上传成功！');
					}, function(e) {
						console.log(e);
						mui.toast('文件上传失败！');
					});
					document.getElementById("uploadFileInput").value = "";
					let imgInnerHtml =
						`<img src="${base64}"/>`;
					let cDom = document.createElement('div');
					cDom.innerHTML = imgInnerHtml;
					cDom.className = "removeImage";
					cDom.id = file.name;
					if (mapImageListDom.getElementsByTagName('img').length ==
						3) {
						document.getElementById('uploadImage').remove();
						document.getElementById('mapImageList').append(cDom);
						mask.close(); //关闭遮罩
					} else {
						document.getElementById('mapImageList').insertBefore(
							cDom, document
							.getElementById(
								'uploadImage'));
						mask.close(); //关闭遮罩
					}
				});
			});
		} else {
			fileToBase64Async(file).then(item => {
				// fileList[file.name] = item;
				// 文件上传
				let content = {
					title: "appUploadFile-" + new Date().getTime(),
					content: file.name,
					c_file_base64: item
				}
				fileList[file.name] = content.title;
				let paramData = new FormData();
				paramData.append("columnId", "1793");
				paramData.append("modelId", "1128");
				paramData.append("content", JSON.stringify(content));
				addContentData({
					data: paramData
				}, function(res) {
					let resJson = JSON.parse(res);
					if (resJson.code == 200) {
						mui.toast('文件上传成功！');
					} else {
						mui.toast('文件上传失败！');
					}
				}, function(e) {
					console.log('文件上传失败！', e);
					mui.toast('文件上传失败！');
				});
				document.getElementById("uploadFileInput").value = "";
				let imgInnerHtml =
					`<img src="${item}"/>`;
				let cDom = document.createElement('div');
				cDom.innerHTML = imgInnerHtml;
				cDom.className = "removeImage";
				cDom.id = file.name;
				if (mapImageListDom.getElementsByTagName('img').length == 3) {
					document.getElementById('uploadImage').remove();
					document.getElementById('mapImageList').append(cDom);
				} else {
					document.getElementById('mapImageList').insertBefore(cDom, document
						.getElementById(
							'uploadImage'));
				}
			})
		}
	});
}
// -------------------------------------------------------------自定义请求
// 动态获取图片（点击疑点或标记marker时）
function getFileListUrl(fileList) {
	return new Promise((resolve, reject) => {
		if (fileList) {
			let fileUrlList = [];
			let index = 0;
			for (let fileName in fileList) {
				index++;
			}
			for (let fileName in fileList) {
				let paramData2 = new FormData();
				paramData2.append("columnId", 1793);
				paramData2.append("states", "0,1,2");
				paramData2.append("pageSize", 10);
				paramData2.append("page", 0);
				let searchParam = [];
				let paramItem = {
					field: "title",
					searchType: "1",
					content: {
						value: fileList[fileName]
					}
				};
				searchParam.push(paramItem);
				if (searchParam.length > 0) {
					paramData2.append("search", JSON.stringify(searchParam));
				}
				getDmsData({
					data: paramData2
				}, function funSuccess(res, textStatus, xhr) {
					let resJson2 = JSON.parse(res);
					if (resJson2.code == 200) {
						let fileBase = resJson2.content
							.data[0].c_file_base64;
						fileUrlList.push(fileBase);
						if (fileUrlList.length == index) {
							resolve(fileUrlList);
						}
					}
				}, function funerror(res, textStatus, xhr) {});
			}
		} else {
			resolve();
		}
	});
}
// 用户登录
function apiLogin(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + loginUrl, newSetting);
}
// token验证
function getUserInfo(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + getUserInfoUrl, newSetting);
}
// dms数据请求
function getDmsData(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + getDataListUrl, newSetting);
}
// dms数据更新
function updateContentData(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + updateContent, newSetting);
}
// dms状态更新
function updateAuditState(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + updateAudit, newSetting);
}
// dms添加数据
function addContentData(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + addContent, newSetting);
}
// 文件上传
function putFile(setting, funSuccess, funError) {
	requestSettins.success = funSuccess;
	requestSettins.error = funError;
	let newSetting = Object.assign(requestSettins, setting);
	mui.ajax(DMS_BASE_RUL + proxyDmsFileUploadFile, newSetting);
}
// 在线文档预览
function openRemoteFile(url) {
	if (plusStatus) {
		var wait = plus.nativeUI.showWaiting("正在打开文件...");
		var dtask = plus.downloader.createDownload(url, {
			method: "GET"
		}, function(d, status) {
			if (status == 200) {
				plus.runtime.openFile(d.filename, {}, function(e) {
					wait.close();
					mui.alert("无法打开此文件：" + e.emssage, "我的软件");
				});
				wait.close();
			} else {
				wait.close();
				mui.alert("文件打开失败: " + status, "我的软件");
			}
		});
		dtask.start();
	} else {
		mui.alert("plus未加载成功！", "系统提示")
	}
}

function getLocalAddr() {
	let user_latitude = "";
	let user_longitude = "";
	// 获取手机定位
	plus.geolocation.getCurrentPosition(function(res) {
		//成功回调
		user_latitude = wgs84togcj02(res.coords.longitude, res.coords.latitude)[1]; //纬度
		user_longitude = wgs84togcj02(res.coords.longitude, res.coords.latitude)[0]; //经度
		localStorage.setItem("user_longitude", user_longitude);
		localStorage.setItem("user_latitude", user_latitude);
		// mui.alert("经度：" + user_longitude + " 纬度：" + user_latitude);
	}, function(e) {
		console.log('Gelocation Error: code - ' + e.code + '; message - ' + e.message);
		switch (e.code) {
			case 10:
				mui.alert('请开启应用的定位权限', '温馨提示', '确定', function() {}, 'div');
				break;
			case 9:
				//mui.alert('请开启手机定位服务');
				mui.alert('请开启手机定位服务', '温馨提示', '确定', function() {}, 'div');
				break;
			case 2:
				if (e.message.indexOf("[geolocation:13]") > -1) {
					//如果网络开启，定位失败，提示检查定位权限
					mui.alert('请开启应用的定位权限', '温馨提示', '确定', function() {}, 'div');
				}
				if (e.message.indexOf("[geolocation:14]") > -1) {
					//如果应用的权限开了，提示网络异常
					mui.alert('请检查网络是否正常', '温馨提示', '确定', function() {}, 'div');
				}
				break;
			case e.PERMISSION_DENIED:
				mui.alert('请求定位被拒绝', '温馨提示', '确定', function() {}, 'div');
				break;
			case e.POSITION_UNAVAILABLE:
				mui.alert("位置信息不可用", '温馨提示', '确定', function() {}, 'div');
				break;
			case e.TIMEOUT:
				mui.alert("获取位置信息超时", '温馨提示', '确定', function() {}, 'div');
				break;
			case e.UNKNOWN_ERROR:
				mui.alert("未知错误", '温馨提示', '确定', function() {}, 'div');
				break;
		}
	}, {
		//超时未获取到经纬度信息 执行失败回调 (默认为5秒)
		timeout: 3000
	})
}
/**
 * file 转Base64 DataURL
 * @param {File} file
 * @returns
 */
function fileToBase64Async(file) {
	return new Promise((resolve, reject) => {
		let reader = new FileReader();
		reader.readAsDataURL(file);
		reader.onload = (e) => {
			resolve(e.target.result);
		};
	});
}
/**
 * Bolb 转Base64 DataURL
 * @param {blob} file blob
 * @returns callback
 */
function blobToDataURI(blob, callback) {
	var reader = new FileReader();
	reader.readAsDataURL(blob);
	reader.onload = function(e) {
		callback(e.target.result);
	}
}
// -------------------------------------------------------------自定义事件
// 登录请求
function login() {
	let docUserName = document.getElementById('userName').value;
	let docPassword = document.getElementById('passWord').value;
	// let docUserName = "user001";
	// let docPassword = "1234567890";
	if (!docUserName) {
		mui.alert('请输入用户名！', '表单校验', function() {
			return false;
		});
		return false;
	}
	if (!docPassword) {
		mui.alert('请输入密码！', '表单校验', function() {
			return false;
		});
		return false;
	}
	// 登录请求
	if (docUserName && docPassword) {
		// 创建formData对象
		let paramData = new FormData();
		paramData.append("userName", docUserName);
		paramData.append("password", docPassword);
		paramData.append("clientId", "1");
		console.log("登录参数", docUserName, docPassword);
		// 开始请求登录接口
		apiLogin({
			// params: paramData,
			data: paramData,
			dataType: "json"
		}, function success(res, textStatus, xhr) {
			if (res.code == 200) {
				// 如果用户选中了记住密码，则保存账户信息
				if (isActive) {
					localStorage.setItem('userName', docUserName);
					localStorage.setItem('passWord', docPassword);
				}
				// 缓存登录状态主要信息
				localStorage.setItem("userId", res.content.id);
				localStorage.setItem("userName", res.content.username);
				localStorage.setItem("token", res.message);
				// 提示信息
				mui.alert('登录成功！', '系统提示', function() {
					// 跳转到主页
					mui.openWindow("pages/home.html", "home");
				});
			} else {
				console.log(JSON.stringify(res),textStatus,JSON.stringify(xhr));
				mui.alert(res.message ? res.message : '登录失败！', '系统提示', function() {
					localStorage.setItem('isActive', false);
				});
			}
		}, function error(xhr, type, errorThrown) {
			console.log(JSON.stringify(xhr), type, errorThrown);
			mui.alert('登录失败！', '系统提示', function() {
				localStorage.setItem('isActive', false);
			});
		});
	}
}
// 请求我的任务列表(下一页)
function getMoveMyTaskList() {
	console.log("用户下拉刷新操作")
	page_e = this;
	getMyTaskList();
}
// 清空搜索框值
function clearSearchValue() {
	if (document.getElementById('searchInput')) {
		document.getElementById('searchInput').value = null;
	}
}
// 重置页面信息并查询
function resetPageInfo() {
	allCount = 0;
	pageSize = 10;
	page = 0;
	// 删除数据列表
	if (document.getElementsByClassName('displayFlex').length > 0) {
		let displayFlexDoms = document.getElementsByClassName('displayFlex');
		let displayFlexDomsLength = displayFlexDoms.length;
		for (let i = 0; i < displayFlexDomsLength; i++) {
			if (displayFlexDoms[0]) {
				displayFlexDoms[0].remove();
			}
		}
	}
	// 重新请求数据
	getMyTaskList();
	mui('#listMoveDom').pullRefresh().refresh(true);
};
// 请求我的任务列表
function getMyTaskList() {
	sessionStorage.clear();
	// 创建formData对象
	let paramData = new FormData();
	let pageName = document.getElementById('pageName') ? document.getElementById('pageName').value :
		'myTask';
	paramData.append("columnId", pageParam[pageName].columnId);
	if (pageParam[pageName].searchStateColumnName) {
		paramData.append("states", pageParam[pageName].states);
	} else {
		paramData.append("states", searchStateValue !== 0 ? searchStateValue : pageParam[pageName]
			.states);
	}

	paramData.append("pageSize", pageSize);
	paramData.append("page", page);
	let searchParam = [];
	if (pageName == "myTaskInfo") {
		let param = {
			field: "title",
			searchType: "1",
			content: {
				value: localStorage.getItem("taskName")
			}
		};
		searchParam.push(param);
	}
	if (document.getElementById('searchInput') && document.getElementById('searchInput').value) {
		let searchInputValue = document.getElementById('searchInput').value;
		if (searchInputValue) {
			let param = {
				field: pageParam[pageName].searchColumnName,
				searchType: "2",
				content: {
					value: searchInputValue
				}
			};
			searchParam.push(param);
		}
	}
	if (pageParam[pageName].params) {
		let paramItem = {
			field: pageParam[pageName].params.searchColumnName,
			searchType: pageParam[pageName].params.searchType ? pageParam[pageName].params
				.searchType : "2",
			content: {
				value: pageParam[pageName].params.value
			}
		};
		searchParam.push(paramItem);
	}
	if (pageParam[pageName].searchStateColumnName && searchStateValue !== 0) {
		let paramItem = {
			field: pageParam[pageName].searchStateColumnName,
			searchType: "1",
			content: {
				value: searchStateValue
			}
		};
		searchParam.push(paramItem);
	}
	if (searchParam.length > 0) {
		paramData.append("search", JSON.stringify(searchParam));
	}
	if (pageParam[pageName].orderColumnName && pageParam[pageName].orderByType) {
		let sortparam = [{
			field: pageParam[pageName].orderColumnName,
			orderByType: pageParam[pageName].orderByType
		}];
		paramData.append("orderBy", JSON.stringify(sortparam));
	}
	getDmsData({
		data: paramData
	}, function funSuccess(res, textStatus, xhr) {
		let resJson = {};
		try {
			let serverDataMap = {};
			if (typeof res === "object") {
				resJson = res;
			} else {
				resJson = JSON.parse(res);
			}
			if (resJson.code == 200 && resJson.content != null && resJson.content.data &&
				resJson.content.data
				.length > 0) {
				allCount = resJson.content.count;
				let listDom = document.getElementById('myTaskListDom') ? document
					.getElementById(
						'myTaskListDom') :
					document.getElementById('lawsAndRegulationsListDom');
				let geometrys = [];
				for (let i = 0; i < resJson.content.data.length; i++) {
					let moveDom = document.createElement('div');
					let createTime = new Date(resJson.content.data[i].create_time);
					let updateTime = new Date(resJson.content.data[i].update_time);
					if (pageName === 'myTask') {
						if (resJson.content.data[i].state == 0) {
							myTaskListStateFalse[resJson.content.data[i].c_task_id] = resJson
								.content.data[i];
						}
						// 我的任务页面
						moveDom.innerHTML = `<div data-task-name="${resJson.content.data[i].title}" data-task-id="${resJson.content.data[i].c_task_id}" class="displayFlex taskItem">
								<h4 class="${pageParam[pageName].taskStatusTag[resJson.content.data[i].state].class}">${resJson.content.data[i].title}
								<span class="list-tag">
								${pageParam[pageName].taskStatusTag[resJson.content.data[i].state].title}</span></h4>
								<p class="content">${resJson.content.data[i].content}</p>
								<div class="dataListHr">
								<p>创建时间：<span>${timeToStr(createTime)}</span></p>
								</div>								
							</div>`;
					} else if (pageName === 'myTaskInfo') {
						// 我的任务详情页面
						let cDoubtfulPoints = JSON.parse(resJson.content.data[i]
							.c_doubtful_points);
						cDoubtfulPoints.dataTitle = cDoubtfulPoints.name ? cDoubtfulPoints
							.name :
							cDoubtfulPoints.id;
						cDoubtfulPoints.id = resJson.content.data[i].id;
						serverDataMap[cDoubtfulPoints.id] = resJson.content.data[i];
						geometrys.push(cDoubtfulPoints);
						localStorage.setItem("geometrys", JSON.stringify(geometrys));
						moveDom.innerHTML = `<div data-marker-id="${resJson.content.data[i].id}" class="displayFlex toMapPage">
											<h4 class="${pageParam[pageName].taskStatusTag[resJson.content.data[i].state].class}">
											${cDoubtfulPoints.dataTitle ? `${cDoubtfulPoints.dataTitle}` : ``}
											<span class="list-tag">
											${pageParam[pageName].taskStatusTag[resJson.content.data[i].state].title}</span></h4>
											<p class="content">
											${cDoubtfulPoints.properties && cDoubtfulPoints.properties["Name"] ? `${cDoubtfulPoints.properties["Name"]}` : ``}
											</p>
											<div class="dataListHr">
											<p>创建时间：<span>${timeToStr(createTime)}</span></p>
											</div>
										</div>`;
					} else if (pageName === 'myMarks') {
						// 我的标记页面
						let cDoubtfulPoints = JSON.parse(resJson.content.data[i].c_content);
						// 暂存id，方便提交的时候得到原始数据
						cDoubtfulPoints.id = resJson.content.data[i].id;
						// 数据暂存到serverDataMap对象中
						serverDataMap[cDoubtfulPoints.id] = resJson.content.data[i];
						geometrys.push(cDoubtfulPoints);
						localStorage.setItem("geometrys", JSON.stringify(geometrys));
						moveDom.innerHTML = `<div data-marker-id="${resJson.content.data[i].id}" class="displayFlex toMapPage">
									<h4 class="BrandTag">${resJson.content.data[i].title}</h4>
									<p class="content">${cDoubtfulPoints.properties.desc +"-"+ cDoubtfulPoints.properties.title}</p>
									<div class="dataListHr">
									<p>创建时间：<span>${timeToStr(createTime)}</span></p>
									</div>
								</div>`;
					} else {
						// 知识检索页面
						moveDom.innerHTML = `<div class="displayFlex fileBox" data-file-url="${resJson.content.data[i].c_pdf || resJson.content.data[i].c_c_pdf}">
									<p class="fileTitle">${resJson.content.data[i].title}</p>
									<div class="dataListHr">
									<p class="nonePadding">发布日期：<span>${timeToStr(createTime)}</span></p>
									</div>
								</div>`;
					}
					// 恢复上拉刷新状态
					listDom.insertBefore(moveDom, document.getElementById(
						'listMoveDom'));
				}
				localStorage.setItem("serverDataMap", JSON.stringify(serverDataMap));
				// 分页配置
				if (page_e) {
					if (allCount > (page + 1) * pageSize) {
						document.getElementById("upTitle").innerHTML = "上拉加载更多……";
						page_e.endPullupToRefresh(false);
					} else {
						mui.toast('没有更多数据了');
						document.getElementById("upTitle").innerHTML = "没有更多数据了";
						page_e.endPullupToRefresh(true);
					}
				} else {
					console.log('page_e is null!')
				}
				page++;
			} else {
				// 请求失败！
				document.getElementById("upTitle").innerHTML = resJson.message;
				page_e.endPullupToRefresh(true);
				if (resJson.content === "无效token") {
					localStorage.removeItem("token");
					mui.openWindow("../index.html", "login");
				}
			}
		} catch (e) {
			// 处理异常
			//TODO handle the exception
			mui.alert('try处理异常！' + e, '系统提示', function() {
				document.getElementById("upTitle").innerHTML = "处理异常!";
				page_e.endPullupToRefresh(true);
			});
		}
	}, function error(xhr, type, errorThrown) {
		// request异常
		mui.alert('请求失败！' + JSON.stringify(xhr), '系统提示', function() {
			document.getElementById("upTitle").innerHTML = "请求失败!";
			page_e.endPullupToRefresh(true);
		});
	});
};

function getFileBase64ByTitle(fileTitle) {
	let paramData = new FormData();
	paramData.append("columnId", 1793);
	paramData.append("columnId", 1793);
	paramData.append("states", "0,1,2,3");

	paramData.append("pageSize", 10);
	paramData.append("page", 0);
	let searchParam = [];
	let param = {
		field: "title",
		searchType: "2",
		content: {
			value: fileTitle
		}
	};
	searchParam.push(param);
	paramData.append("search", JSON.stringify(searchParam));
	getDmsData({
		data: paramData
	}, function funSuccess(res, textStatus, xhr) {
		console.log(res);
	}, function funError(e) {
		console.log(e);
	})
}
// 时间戳转字符串
function timeToStr(date) {
	return date.getFullYear() + "-" + timeToTwo(date.getMonth() + 1) +
		"-" + timeToTwo(date.getDate()) + " " + timeToTwo(date.getHours()) + ":" + timeToTwo(date
			.getMinutes()) + ":" +
		timeToTwo(date.getSeconds());
}
// 时间单位(x|xx)转换
function timeToTwo(number) {
	return number < 10 ? '0' + number : number
}
//定义一些常量
var x_PI = 3.14159265358979324 * 3000.0 / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0;
var ee = 0.00669342162296594323;
/**
 * 百度坐标系 (BD-09) 与 火星坐标系 (GCJ-02)的转换
 * 即 百度 转 谷歌、高德
 * @param bd_lon
 * @param bd_lat
 * @returns {*[]}
 */
function bd09togcj02(bd_lon, bd_lat) {
	var bd_lon = +bd_lon;
	var bd_lat = +bd_lat;
	var x = bd_lon - 0.0065;
	var y = bd_lat - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_PI);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_PI);
	var gg_lng = z * Math.cos(theta);
	var gg_lat = z * Math.sin(theta);
	return [gg_lng, gg_lat]
};
/**
 * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
 * 即谷歌、高德 转 百度
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gcj02tobd09(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_PI);
	var theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_PI);
	var bd_lng = z * Math.cos(theta) + 0.0065;
	var bd_lat = z * Math.sin(theta) + 0.006;
	return [bd_lng, bd_lat]
};
/**
 * WGS84转GCj02
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function wgs84togcj02(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var dlat = transformlat(lng - 105.0, lat - 35.0);
	var dlng = transformlng(lng - 105.0, lat - 35.0);
	var radlat = lat / 180.0 * PI;
	var magic = Math.sin(radlat);
	magic = 1 - ee * magic * magic;
	var sqrtmagic = Math.sqrt(magic);
	dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
	dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
	var mglat = lat + dlat;
	var mglng = lng + dlng;
	return [mglng, mglat]
};
/**
 * GCJ02 转换为 WGS84
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function gcj02towgs84(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var dlat = transformlat(lng - 105.0, lat - 35.0);
	var dlng = transformlng(lng - 105.0, lat - 35.0);
	var radlat = lat / 180.0 * PI;
	var magic = Math.sin(radlat);
	magic = 1 - ee * magic * magic;
	var sqrtmagic = Math.sqrt(magic);
	dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
	dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
	var mglat = lat + dlat;
	var mglng = lng + dlng;
	return [lng * 2 - mglng, lat * 2 - mglat]

};
/**
 * 百度坐标系 (BD-09) 转换为 WGS84
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function bd09towgs84(bd_lon, bd_lat) {
	//百度经纬度坐标转国测局坐标
	var bd09togcj02_arr = bd09togcj02(bd_lon, bd_lat);
	//国测局坐标转wgs84坐标
	var gcj02towgs84_arr = gcj02towgs84(bd09togcj02_arr[0], bd09togcj02_arr[1]);
	return [gcj02towgs84_arr[0], gcj02towgs84_arr[1]]
};
/**
 * WGS84 转换为 百度坐标系 (BD-09)
 * @param lng
 * @param lat
 * @returns {*[]}
 */
function wgs84tobd09(lng, lat) {
	//wgs84转国测局坐标
	var wgs84togcj02_arr = wgs84togcj02(lng, lat);
	//国测局坐标转百度经纬度坐标
	var gcj02tobd09_arr = gcj02tobd09(wgs84togcj02_arr[0], wgs84togcj02_arr[1]);
	return [gcj02tobd09_arr[0], gcj02tobd09_arr[1]]
};

function transformlat(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(
		Math.abs(lng));
	ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
	ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
	ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
	return ret
};

function transformlng(lng, lat) {
	var lat = +lat;
	var lng = +lng;
	var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math
		.abs(lng));
	ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
	ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
	ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
	return ret
};
// 唤起导航
function openMyPhoneMap(lat,lng) {
	if (lat && lng) {
		// var lng = parseFloat(localStorage.getItem("user_longitude")); //目标经度
		// var lat = parseFloat(localStorage.getItem("user_latitude")); //目标纬度
		//把百度坐标系bd09转国测局坐标系wgs84
		var sopt = [lng, lat];
		//经测试腾讯地图必须使用火星坐标系gcj02，顾单独转换
		var coordQQ = wgs84togcj02(lng, lat);
		//如果还知道其他地图的包名，也可以放这个数组里
		var mapsPackageNames = ['com.baidu.BaiduMap', 'com.autonavi.minimap', 'com.tencent.map'];
		//iOS与Android的判断第三方程序不一样，Android是包名，iOS是action属性（Scheme）
		var iosURLTypes = ['baidumap://', 'iosamap://', 'qqmap://'];
		if (plus.os.name == "iOS") {
			mapsPackageNames = iosURLTypes
		};
		app.base.operationAfterCheckInstall(mapsPackageNames, function(res) { //res(object)
			// alert(JSON.stringify(res))
			var m = 0,
				gotoUrl = ""; //m:记录本机地图app个数，gotoUrl：记录实际直接跳转地址
			var btnArray = []; //实际显示按钮数组
			var btnTitle = ["使用百度地图导航", "使用高德地图导航", "使用腾讯地图导航"];
			var urlArray = []; //实际显示跳转地址数组
			//百度api文档：http://lbsyun.baidu.com/index.php?title=uri/api/android
			//高德api文档：https://lbs.amap.com/api/amap-mobile/guide/ios/route
			//腾讯api文档：https://lbs.qq.com/webApi/uriV1/uriGuide/uriMobileRoute
			var andrUrl = [
				"baidumap://map/direction?origin=&destination=" + sopt[1] + "," + sopt[0] +
				"&coord_type=wgs84&mode=driving&src=andr.baidu.openAPIdemo",
				"amapuri://route/plan/?slat=&slon=&dlat=" + sopt[1] + "&dlon=" + sopt[0] +
				"&dev=1&t=0",
				"qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=" +
				coordQQ[1] + "," +
				coordQQ[
					0] + "&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"
			]
			var iosUrl = [
				"baidumap://map/direction?origin=&destination=" + sopt[1] + "," + sopt[0] +
				"&coord_type=wgs84&mode=driving&src=ios.baidu.openAPIdemo",
				"iosamap://path?sourceApplication=applicationNameslat=&slon=&dlat=" + sopt[
					1] + "&dlon=" +
				sopt[
					0] +
				"&dev=1&t=0",
				"qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=" +
				coordQQ[1] + "," +
				coordQQ[
					0] + "&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77"
			]
			//根据手机型号确定跳转数组var 
			if (plus.os.name == "iOS") {
				urlArray = iosUrl;
			} else {
				urlArray = andrUrl;
			}
			var gotoUrlArr = [];
			for (k in res) {
				if (res[k]) {
					m++;
					gotoUrl = urlArray[k];
					btnArray.push({
						title: btnTitle[k]
					})
					gotoUrlArr.push(urlArray[k])
				}
			}
			//当只有一个地图APP时，直接跳转；不止一个时弹出原生选择框
			if (m > 1) {
				plus.nativeUI.actionSheet({
					title: "请选择地图",
					cancel: "取消",
					buttons: btnArray
				}, function(e) {
					if (e.index > 0) { //=0:取消，1：百度，2：高德，3：腾讯
						plus.runtime.openURL(gotoUrlArr[e.index - 1]);
					}
				});
			} else {
				plus.runtime.openURL(gotoUrl);
			}
			// plus.maps.openSysMap(dst, name, src);//直接默认跳转第三方，无回调，已弃用
		}, function() {
			alert("您未安装百度地图、高德地图、腾讯地图,请前往应用市场下载");
		})
	}
}

//传入包名，检查手机上是否安装了这个应用
function isInstall(packageName) {
	try {
		if (plus.os.name == "iOS") {
			var UIApplication = plus.ios.importClass("UIApplication");
			var NSURL = plus.ios.importClass("NSURL");

			var app = UIApplication.sharedApplication();
			var bdScheme = NSURL.URLWithString(packageName);
			var install = app.canOpenURL(bdScheme);

			plus.ios.deleteObject(bdScheme);
			plus.ios.deleteObject(app);
			return install
		} else {
			var main = plus.android.runtimeMainActivity();
			var packageManager = main.getPackageManager();
			var PackageManager = plus.android.importClass(packageManager);
			var packageinfo = packageManager.getPackageInfo(packageName, PackageManager.GET_ACTIVITIES)
			if (packageinfo) {
				return true;
			} else {
				return false;
			}
		}
	} catch (e) {
		return false;
	}
}
//批量传入包名，检查一系列应用是否安装，如果有任意一个安装了，就执行success，否认执行fai
function operationAfterCheckInstall(mapsPackageNames, success, fail) {
	var res = mapsPackageNames.map(function(item) {
		return app.base.isInstall(item);
	})
	if (eval(res.join("||"))) {
		success(res);
	} else {
		fail();
	}
}
// plus注释区域
// 	}
// }, true);