// json格式化
function syntaxHighlight(json) {

	if (typeof json != 'string') {

		json = JSON.stringify(json, undefined, 2);

	}

	json = json.replace(/&/g, '&').replace(/>/g, '>').replace(/</g, '<');

	return json.replace(
		/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
		function(match) {

			var cls = 'number';

			if (/^"/.test(match)) {

				if (/:$/.test(match)) {

					cls = 'key';

				} else {

					cls = 'string';

				}

			} else if (/true|false/.test(match)) {

				cls = 'boolean';

			} else if (/null/.test(match)) {

				cls = 'null';

			}

			return '' + match + '';

		});

}
// 方法调用
function requestMethod() {
	// url + port
	let methodObj = localStorage.getItem('methodParamsObj')
	let methodJson = false,
		baseUrl = ''
	if (methodObj) {
		methodJson = JSON.parse(methodObj)
		console.warn('methodJson', methodJson)
		if (!methodJson.ip) {
			window.alert('请输入ip')
		}
		if (!methodJson.method) {
			methodJson.method = 'get'
		}
		if (methodJson.port) {
			if (methodJson.path) {
				baseUrl = methodJson.ip + ':' + methodJson.port + '' + methodJson.path
			} else {
				baseUrl = methodJson.ip + ':' + methodJson.port
			}
		} else {
			if (methodJson.path) {
				baseUrl = methodJson.ip + '' + methodJson.path
			} else {
				baseUrl = methodJson.ip
			}
		}
	} else {
		window.alert('请输入 IP地址 port端口 path路径')
	}
	console.warn('baseUrl', baseUrl)

	// header参数和body参数
	let headerParamsObj = localStorage.getItem('headerParamsObj')
	let bodyParamsObj = localStorage.getItem('bodyParamsObj')
	let headerParamsObjJson = headerParamsObj ? JSON.parse(headerParamsObj) : false
	let bodyParamsObjJson = headerParamsObj ? JSON.parse(bodyParamsObj) : false
	let headerParams = {},
		bodyParams = {}
	if (headerParamsObjJson) {
		for (let loc = 0, length = headerParamsObjJson.array.length; loc < length; ++loc) {
			if (headerParamsObjJson.array[loc].key && headerParamsObjJson.array[loc].value) {
				headerParams[headerParamsObjJson.array[loc].key] = headerParamsObjJson.array[loc].value
			}
		}
	}
	if (bodyParamsObjJson) {
		for (let loc = 0, length = bodyParamsObjJson.array.length; loc < length; ++loc) {
			if (bodyParamsObjJson.array[loc].key && bodyParamsObjJson.array[loc].value) {
				bodyParams[bodyParamsObjJson.array[loc].key] = bodyParamsObjJson.array[loc].value
			}
		}
	}
	console.warn('header', headerParams)
	console.warn('body', bodyParams)
	console.warn('methodJson.method', methodJson.method)
	if (methodJson.method) {
		console.warn('methodJson.method', methodJson.method)
		switch (methodJson.method) {
			case 'get':
				axios.get(baseUrl, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseUrl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				})
				break;
			case 'post':
				axios.post(baseUrl, bodyParams, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseUrl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				})
				break
			case 'delete':
				axios.delete(baseUrl, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseUrl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				})
				break
			case 'put':
				axios.put(baseUrl, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseUrl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				})
				break
			case 'head':
				axios.head(baseUrl, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseUrl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				})
				break
			case 'option':
				axios.options(baseUrl, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseURl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				})
				break
			default:
				axios.get(baseUrl, params, {
					headers: headerParams
				}).then(res => {
					console.log('res', res)
					window.alert('请求成功：' + baseURl)
					document.getElementById('response-show-id').innerText = syntaxHighlight(res)
				}).catch(r => {
					window.alert('请求失败')
				}).catch(r => {
					window.alert('请求失败')
				})
				break;
		}
	}
}

// 初始化监听条件
function initItemDom() {
	console.log('initDom')
	// 清空headerParamsObj bodyParamsObj
	localStorage.removeItem('headerParamsObj')
	localStorage.removeItem('bodyParamsObj')
	localStorage.removeItem('methodParamsObj')
	let parentDom = document.getElementById('container-box-item')
	let selectDom = document.getElementById('select-dom-id')
	// 添加监听函数
	selectDom && selectDom.addEventListener('change', function() {
		let methodJson = null
		let methodObj = localStorage.getItem('methodParamsObj')
		if (methodObj) {
			methodJson = JSON.parse(methodObj)
			methodJson.method = this.value
		} else {
			methodJson = {
				method: this.value
			}
		}
		localStorage.setItem('methodParamsObj', JSON.stringify(methodJson))
	})
	// 
	let ipDom = document.getElementById('base-url-ip-id')
	ipDom && ipDom.addEventListener('change', function() {
		let methodJson = null
		let methodObj = localStorage.getItem('methodParamsObj')
		if (methodObj) {
			methodJson = JSON.parse(methodObj)
			methodJson.ip = this.value
		} else {
			methodJson = {
				ip: this.value
			}
		}
		localStorage.setItem('methodParamsObj', JSON.stringify(methodJson))
	})
	let portDom = document.getElementById('base-url-port-id')
	portDom && portDom.addEventListener('change', function() {
		let methodJson = null
		let methodObj = localStorage.getItem('methodParamsObj')
		if (methodObj) {
			methodJson = JSON.parse(methodObj)
			methodJson.port = this.value
		} else {
			methodJson = {
				port: this.value
			}
		}
		localStorage.setItem('methodParamsObj', JSON.stringify(methodJson))
	})
	let pathDom = document.getElementById('base-url-path-id')
	pathDom && pathDom.addEventListener('change', function() {
		let methodJson = null
		let methodObj = localStorage.getItem('methodParamsObj')
		if (methodObj) {
			methodJson = JSON.parse(methodObj)
			methodJson.path = this.value
		} else {
			methodJson = {
				path: this.value
			}
		}
		localStorage.setItem('methodParamsObj', JSON.stringify(methodJson))
	})
	// header的dom
	let headerAddBtnDom = document.getElementById('header-params-add-btn')
	headerAddBtnDom.addEventListener('click', async function() {
		// 时间撮-标识作为 id
		let time = new Date()
		let timestemp = time.valueOf(),
			headerParamsObjJson = null,
			flag = false;
		let headerParamsObj = localStorage.getItem('headerParamsObj')
		if (headerParamsObj) {
			console.log('type headerParamsObj', typeof headerParamsObj)
			headerParamsObjJson = JSON.parse(headerParamsObj)
			console.log('type headerParamsObjJson', typeof headerParamsObjJson, headerParamsObjJson)
			flag = !flag
		} else {
			flag = flag
		}
		if (flag) {
			console.info('存在 json', headerParamsObjJson)
			//存在加一
			headerParamsObjJson.array && headerParamsObjJson.array.push({
				key: '',
				value: '',
				timestemp: timestemp.toString() //时间撮唯一标识
			})
			headerParamsObjJson.arrayLength = headerParamsObjJson.arrayLength + 1
			// update
			localStorage.setItem('headerParamsObj', JSON.stringify(headerParamsObjJson))
		} else {
			// 不存在 声明在storage
			headerParamsObjJson = {
				name: 'headerParamsObjJson',
				array: [{
					key: '',
					value: '',
					timestemp: timestemp.toString() //时间撮唯一标识
				}],
				arrayLength: 1
			}
			localStorage.setItem('headerParamsObj', JSON.stringify(headerParamsObjJson))

		}

		// header的div
		let parentDom = document.getElementById('header-params-dom')
		let divDom = document.createElement('div')
		divDom.className = 'flex-params-grid'
		divDom.id = timestemp + '-header-div-dom'
		// key
		let inputKeyDom = document.createElement('input')
		inputKeyDom.className = 'input-params'
		inputKeyDom.placeholder = 'key'
		inputKeyDom.id = timestemp + '-header-input-key-id'
		// key change
		inputKeyDom.addEventListener('change', function() {
			let domTimestemp = this.getAttribute('id').split('-')[0]
			let headerParamsObj = localStorage.getItem('headerParamsObj')
			let headerParamsObjJson = JSON.parse(headerParamsObj)
			for (let loc = 0, length = headerParamsObjJson.array.length; loc < length; ++
				loc) {
				if (domTimestemp === headerParamsObjJson.array[loc].timestemp) {
					headerParamsObjJson.array[loc].key = this.value
					break
				}
			}
			localStorage.setItem('headerParamsObj', JSON.stringify(headerParamsObjJson))
		})
		// =
		let spanDom = document.createElement('span')
		spanDom.className = 'params-span-class'
		spanDom.innerHTML = " = "
		// value
		let inputValueDom = document.createElement('input')
		inputValueDom.className = 'input-params'
		inputValueDom.placeholder = 'value'
		inputValueDom.id = timestemp + '-header-input-value-id'
		// value change
		inputValueDom.addEventListener('change', function() {
			let domTimestemp = this.getAttribute('id').split('-')[0]
			let headerParamsObj = localStorage.getItem('headerParamsObj')
			let headerParamsObjJson = JSON.parse(headerParamsObj)
			for (let loc = 0, length = headerParamsObjJson.array.length; loc < length; ++
				loc) {
				if (domTimestemp === headerParamsObjJson.array[loc].timestemp) {
					headerParamsObjJson.array[loc].value = this.value
					break
				}
			}
			localStorage.setItem('headerParamsObj', JSON.stringify(headerParamsObjJson))
		})
		// delete
		let spanCloseDom = document.createElement('button')
		spanCloseDom.className = 'params-close-class'
		spanCloseDom.innerText = "x"
		spanCloseDom.id = timestemp + '-header-params-close-id'
		spanCloseDom.addEventListener('click', function() {
			// 删除dom
			let domTimestemp = this.getAttribute('id').split('-')[0]
			let headerParamsObj = localStorage.getItem('headerParamsObj')
			let headerParamsObjJson = JSON.parse(headerParamsObj)
			let itemArray = []
			for (let loc = 0, length = headerParamsObjJson.array.length; loc < length; ++
				loc) {
				if (domTimestemp !== headerParamsObjJson.array[loc].timestemp) {
					itemArray.push(headerParamsObjJson.array[loc])
				}
			}
			headerParamsObjJson.array = itemArray
			localStorage.setItem('headerParamsObj', JSON.stringify(headerParamsObjJson))
			this.parentNode.remove()
		})
		divDom && divDom.appendChild(inputKeyDom) && divDom.appendChild(inputKeyDom) && divDom
			.appendChild(
				spanDom) && divDom.appendChild(inputValueDom) &&
			divDom.appendChild(spanCloseDom);
		parentDom.appendChild(divDom)
	})
	// body的dom
	let bodyParamsAddBtn = document.getElementById('body-params-dom-add-btn')
	bodyParamsAddBtn.addEventListener('click', function() {
		// 时间撮-标识作为 id
		let time = new Date()
		let timestemp = time.valueOf(),
			bodyParamsObjJson = null,
			flag = false;
		let bodyParamsObj = localStorage.getItem('bodyParamsObj')
		if (bodyParamsObj) {
			console.log('type bodyParamsObj', typeof bodyParamsObj)
			bodyParamsObjJson = JSON.parse(bodyParamsObj)
			console.log('type bodyParamsObjJson', typeof bodyParamsObjJson, bodyParamsObjJson)
			flag = !flag
		} else {
			flag = flag
		}
		if (flag) {
			console.info('存在 json', bodyParamsObjJson)
			//存在加一
			bodyParamsObjJson.array && bodyParamsObjJson.array.push({
				key: '',
				value: '',
				timestemp: timestemp.toString() //时间撮唯一标识
			})
			bodyParamsObjJson.arrayLength = bodyParamsObjJson.arrayLength + 1
			// update
			localStorage.setItem('bodyParamsObj', JSON.stringify(bodyParamsObjJson))
		} else {
			// 不存在 声明在storage
			bodyParamsObjJson = {
				name: 'bodyParamsObjJson',
				array: [{
					key: '',
					value: '',
					timestemp: timestemp.toString() //时间撮唯一标识
				}],
				arrayLength: 1
			}
			localStorage.setItem('bodyParamsObj', JSON.stringify(bodyParamsObjJson))

		}

		// header的div
		let parentDom = document.getElementById('body-params-dom')
		let divDom = document.createElement('div')
		divDom.className = 'flex-params-grid'
		divDom.id = timestemp + '-body-div-dom'
		// key
		let inputKeyDom = document.createElement('input')
		inputKeyDom.className = 'input-params'
		inputKeyDom.placeholder = 'key'
		inputKeyDom.id = timestemp + '-body-input-key-id'
		// key change
		inputKeyDom.addEventListener('change', function() {
			let domTimestemp = this.getAttribute('id').split('-')[0]
			let bodyParamsObj = localStorage.getItem('bodyParamsObj')
			let bodyParamsObjJson = JSON.parse(bodyParamsObj)
			for (let loc = 0, length = bodyParamsObjJson.array.length; loc < length; ++
				loc) {
				if (domTimestemp === bodyParamsObjJson.array[loc].timestemp) {
					bodyParamsObjJson.array[loc].key = this.value
					break
				}
			}
			localStorage.setItem('bodyParamsObj', JSON.stringify(bodyParamsObjJson))
		})
		// =
		let spanDom = document.createElement('span')
		spanDom.className = 'params-span-class'
		spanDom.innerHTML = " = "
		// value
		let inputValueDom = document.createElement('input')
		inputValueDom.className = 'input-params'
		inputValueDom.placeholder = 'value'
		inputValueDom.id = timestemp + '-body-input-value-id'
		// value change
		inputValueDom.addEventListener('change', function() {
			let domTimestemp = this.getAttribute('id').split('-')[0]
			let bodyParamsObj = localStorage.getItem('bodyParamsObj')
			let bodyParamsObjJson = JSON.parse(bodyParamsObj)
			for (let loc = 0, length = bodyParamsObjJson.array.length; loc < length; ++
				loc) {
				if (domTimestemp === bodyParamsObjJson.array[loc].timestemp) {
					bodyParamsObjJson.array[loc].value = this.value
					break
				}
			}
			localStorage.setItem('bodyParamsObj', JSON.stringify(bodyParamsObjJson))
		})
		// delete
		let spanCloseDom = document.createElement('button')
		spanCloseDom.className = 'params-close-class'
		spanCloseDom.innerText = "x"
		spanCloseDom.id = timestemp + '-body-params-close-id'
		spanCloseDom.addEventListener('click', function() {
			// 删除dom
			let domTimestemp = this.getAttribute('id').split('-')[0]
			let bodyParamsObj = localStorage.getItem('bodyParamsObj')
			let bodyParamsObjJson = JSON.parse(bodyParamsObj)
			let itemArray = []
			for (let loc = 0, length = bodyParamsObjJson.array.length; loc < length; ++
				loc) {
				if (domTimestemp !== bodyParamsObjJson.array[loc].timestemp) {
					itemArray.push(bodyParamsObjJson.array[loc])
				}
			}
			bodyParamsObjJson.array = itemArray
			localStorage.setItem('bodyParamsObj', JSON.stringify(bodyParamsObjJson))
			this.parentNode.remove()
		})
		divDom && divDom.appendChild(inputKeyDom) && divDom.appendChild(inputKeyDom) && divDom
			.appendChild(
				spanDom) && divDom.appendChild(inputValueDom) &&
			divDom.appendChild(spanCloseDom);
		parentDom.appendChild(divDom)
	})
	// 提交
	let submitBtn = document.getElementById('submit-request-btn')
	submitBtn && submitBtn.addEventListener('click', function() {
		requestMethod() //post
	})
}

chrome.runtime.onInstalled.addListener(() => {
	console.log('chrome init')
	let color = '#3aa757';
	chrome.storage.sync.set({
		color
	});
	console.info('chrome');
	console.log('Default background color set to %cgreen', `color: ${color}`);
});
$(function() {
	initItemDom(); //数据初始化
})
