document.addEventListener('DOMContentLoaded', function () {
	const palletsInput = document.getElementById('pallets');
	const dateFirstRadio = document.getElementById('date-first');
	const feeFirstRadio = document.getElementById('fee-first');
	const dateModeDynamicRadio = document.getElementById('date-mode-dynamic');
	const dateModeFixedRadio = document.getElementById('date-mode-fixed');
	const minRateInput = document.getElementById('min-rate');
	const maxRateInput = document.getElementById('max-rate');
	const startInput = document.getElementById('start');
	const endInput = document.getElementById('end');
	const today = new Date().toISOString().split('T')[0];
	const startFixedInput = document.getElementById('start-fixed');
	startFixedInput.min = today;
	const endFixedInput = document.getElementById('end-fixed');
	endFixedInput.min = today;
	const cancelBtn = document.getElementById('cancel-btn');
	const saveBtn = document.getElementById('save-btn');
	const error = document.getElementById('error');
	let palletRadio = document.getElementById('pallet');
	let webNowUrl = {};
	let params = {};
	let isStart = {};
	let tabActiveId = 0;
	let token = '';
	let notWarehouseData = {};
	let warsehouseList = {};
	let transitWarsehouseList = {};
	
	$('.modleEm').hide();
		// 获取当前用户的相关信息
	let getUserInfo = function (){
		return new Promise((resolve, reject) => {
			let userInfoPort = chrome.runtime.connect({name: 'userInfo'});
			userInfoPort.postMessage({'status': 1});
			userInfoPort.onMessage.addListener(function (message){
				resolve(message);
			});
			userInfoPort.disconnect;
		});
	};
	getUserInfo()

	dateFirstRadio.addEventListener('click', function () {
		document.getElementById('rate-group').style.display = 'none';
	});

	feeFirstRadio.addEventListener('click', function () {
		document.getElementById('rate-group').style.display = 'block';
	});

	dateModeDynamicRadio.addEventListener('click', function () {
		document.getElementById('date-mode-dynamic-group').style.display = 'block';
		document.getElementById('date-mode-fixed-group').style.display = 'none';
	});

	dateModeFixedRadio.addEventListener('click', function () {
		document.getElementById('date-mode-dynamic-group').style.display = 'none';
		document.getElementById('date-mode-fixed-group').style.display = 'block';
	});

	// 开始监控
	saveBtn.addEventListener('click', async function () {
		let nowUrl = await checkUrl();
		if(!nowUrl.includes('/new-supply/goods')) {
			alert('当前页面不在货品供应页');
			return;
		}
		if(notWarehouseData[tabActiveId] && notWarehouseData[tabActiveId] === true) {
			alert('请先将货物添加到交货中');
			return;
		}

		const pallets = parseInt(palletsInput.value.trim());
		let taskName = $('#task-name').val();
		let monitorType;
		let dateMode;

		if (dateFirstRadio?.checked) {
			monitorType = 1;
		}
		if (feeFirstRadio?.checked) {
			monitorType = 2;
		}

		if (dateModeDynamicRadio?.checked) {
			dateMode = 1;
		}
		if (dateModeFixedRadio?.checked) {
			dateMode = 2;
		}
		
		if(taskName === '') {
			error.innerHTML = '请输入任务名称';
			return;
		}

		let targetWarehouseId = '';
		let targetWarehouseName = '';
		let transitWarehouseId = '';
		let transitWarehouseName = '';
		let warehouseEl = $('#search-warehouse');
		let transitWarehouseEl = $('#search-transit-warehouse');

		if(warehouseEl.val()) {
			targetWarehouseId = warehouseEl.attr('data-value');
			targetWarehouseName = warehouseEl.val();
		}
		
		if(transitWarehouseEl.val())
		transitWarehouseId = transitWarehouseEl.attr('data-value');
		transitWarehouseName = transitWarehouseEl.val();

		if(!targetWarehouseId) {
			error.innerHTML = '请选择目标仓库';
			return;
		}

		if(palletRadio?.checked && (pallets <= 0 || Number.isNaN(pallets))) {
			error.innerHTML = '请输入有效的托盘数量';
			return;
		}

		const start = parseInt(startInput.value.trim());
		const end = parseInt(endInput.value.trim());
		if(dateMode == 1) {
			if (start < 0 || end < 0 || Number.isNaN(start) || Number.isNaN(end)) {
				error.innerHTML = '请输入有效的预约时间段';
				return;
			}
			if (start > end) {
				error.innerHTML = '结束天数不能小于开始天数';
				return;
			}
		}

		const startFixed = startFixedInput.value.trim();
		const endFixed = endFixedInput.value.trim();
		if (dateMode == 2) {
			if (startFixed === '' || endFixed === '') {
				error.innerHTML = '请选择有效的预约时间段';
				return;
			}
			if(startFixed > endFixed) {
				error.innerHTML = '结束日期不能小于开始日期';
				return;
			}
		}

		const minRate = parseInt(minRateInput.value.trim());
		const maxRate = parseInt(maxRateInput.value.trim());
		if (monitorType == 2) {
			if (minRate < 0 || maxRate < 0 || Number.isNaN(minRate) || Number.isNaN(maxRate)) {
				error.innerHTML = '请输入有效的费率系数';
				return;
			}
			if (minRate > maxRate) {
				error.innerHTML = '请输入有效的费率系数';
				return;
			}
		}

		error.innerHTML = '';
		// 校验邮箱 modleEm
		const messageEmail = await getStorageValue('messageEmail');
		if(!(messageEmail.messageEmail)){
			$('.modleEm').show();
			$(".ruleError").hide();
			return;
		}

		let deliveryType = document.querySelectorAll('.monitor-type[type="radio"]:checked')[0].value;

		params[tabActiveId] = { "monitorType": monitorType, "minRate": minRate, "maxRate": maxRate, "dateMode": dateMode, "startFixed": startFixed, "endFixed": endFixed, "warehouseId": targetWarehouseId, targetWarehouseName, deliveryType, taskName, transitWarehouseId, transitWarehouseName, "start": start, "end": end, }
		if(deliveryType === '1') {
			params[tabActiveId]["pallets"] = pallets;
		}

		$('#save-btn').hide();
		$('#cancel-btn').show();
		chrome.tabs.sendMessage(tabActiveId, {type: 'start', params: params[tabActiveId], tabActiveId});
		isStart[tabActiveId] = true;
		isReviewData = true;
		btnLimitation();
	});

	cancelBtn.addEventListener('click', async function () {
		isStart[tabActiveId] = false;
		$('#save-btn').show();
		$('#cancel-btn').hide();
		btnLimitation();
		chrome.tabs.sendMessage(tabActiveId, {type: 'cancel', params: params[tabActiveId]});
	});

	let btnLimitation = () => {
		if((!webNowUrl[tabActiveId] || !webNowUrl[tabActiveId].includes('/new-supply/goods') || !notWarehouseData[tabActiveId]) && !isStart[tabActiveId]) {
			$('#search-warehouse').val('').attr('disabled', true);
			$('#search-transit-warehouse').val('').attr('disabled', true);
		} else {
			$('#search-warehouse').attr('disabled', isStart[tabActiveId] || false);
			$('#search-transit-warehouse').attr('disabled', isStart[tabActiveId] || false);
		}
		$('#task-name').attr('disabled', isStart[tabActiveId] || false);
		$('#box').attr('disabled', isStart[tabActiveId] || false);
		$('#pallet').attr('disabled', isStart[tabActiveId] || false);
		$('#single-pallet').attr('disabled', isStart[tabActiveId] || false);
		$('#pallets').attr('disabled', isStart[tabActiveId] || false);
		$('#date-first').attr('disabled', isStart[tabActiveId] || false);
		$('#fee-first').attr('disabled', isStart[tabActiveId] || false);
		$('#date-mode-fixed').attr('disabled', isStart[tabActiveId] || false);
		$('#date-mode-dynamic').attr('disabled', isStart[tabActiveId] || false);
		$('#start').attr('disabled', isStart[tabActiveId] || false);
		$('#end').attr('disabled', isStart[tabActiveId] || false);
		$('#start-fixed').attr('disabled', isStart[tabActiveId] || false);
		$('#end-fixed').attr('disabled', isStart[tabActiveId] || false);
		$('#min-rate').attr('disabled', isStart[tabActiveId] || false);
		$('#max-rate').attr('disabled', isStart[tabActiveId] || false);
	}

	// 绑定邮箱
	$(".confirm-notification").off("click").on("click", async function () {
		console.log('userInfouserInfouserInfouserInfo');
		const tokenResult = await getStorageValue('accessToken');
		const email = $(".mailbox").val().trim();
		const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
		if (!emailRegex.test(email)) {
			$(".ruleError").show();
			return;
		} else {
			$(".ruleError").hide();
			let apiUrl = "https://www.seerfar.cn/user-center/browserPlugin/wbAppointmentStock/user/bindMessageEmail"
			let res = await customFetch(apiUrl, {
				method: 'POST',
				headers: {
					"Content-Type": "application/json",
					Authorization: "Bearer " + tokenResult.token,
				},
				body: JSON.stringify({'email':email}),
			});
			if(res.code === 200){
				getUserInfo().then((message) => {
					chrome.storage.sync.set({'messageEmail': message.userInfo.messageEmail}) 
				})
				$(".modleEm").hide();
			}else{
				toastErrorMsg($('body'), res.msg  , true);
			}
		}
	});
	// form 输入限制
	$(document).on('input', '#pallets, #min-rate, #max-rate, #end, #start', function () {   
		this.value = this.value.replace(/[^\d]/g, '');
		if(this.id ==='min-rate' || this.id ==='max-rate'){
			if(this.value >999){
				this.value =999;
			}
		}
		if(this.id ==='pallets'){
			if(this.value > 999){
				this.value =999;
			}
		}
		if(this.id ==='end' || this.id ==='start'){
			if(this.value >30){
				this.value =30;
			}
		}
	});
	let toastErrorMsg = function (container, content, isBody = false){
		let toastOptions = {
			'background': '#fff',
			'color': '#000',
			'content': `<div class="d-flex align-items-center"><span class="fa fa-close" style="color:red;font-size:1.2rem;margin-right:5px"></span>${content}</div>`
		};
		if (isBody){
			toastOptions = {...toastOptions, 'position':'fixed'};
		}
		container.toast(toastOptions);
	};

	let checkUrl = () => {
		return new Promise((resolve, reject) => {
			chrome.tabs.sendMessage(tabActiveId, {type: 'checkUrl'});
			chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
				if(message.action === 'url') {
					resolve(message.url);
				}
			});
		})
	}

	// 接收来自内容脚本的 draftID 和 token
	chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
		if(message.tabId !== tabActiveId) {
			return;
		}
		if (message.action === 'warehouseInfo') {
			token = message.token;
			getWarehouseList(message);
		}
		if(message.action === 'url') {
			if(sender.tab.id === tabActiveId) {
				webNowUrl[tabActiveId] = message?.url || webNowUrl;
			}
		}
		if(message && message.action === 'finish') {
			isStart[tabActiveId] = false;
			$('#save-btn').show();
			$('#cancel-btn').hide();
			warsehouseList[tabActiveId] = [];
			$('#search-warehouse').attr('disabled', true);
			$('#target-warehouse .list-box').html('<div style="text-align: center;">加载中...</div>');
			btnLimitation();
		}
		if(message && message.action === 'cancel') {			
			isStart[tabActiveId] = false;
			$('#save-btn').show();
			$('#cancel-btn').hide();
			btnLimitation();
		}
	});

	$('#pallet').on('click', function() {
		$('#pallets-number').show();
	})
	$('#box, #single-pallet').on('click', function() {
		$('#pallets-number').hide();
	})

	$('#task-name').on('input', function() {
		let val = $(this).val();
		if(val.length > 20) {
			$(this).val(val.substring(0, 20));
		}
	})

	chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
		if (tabs[0]) {
			tabActiveId = tabs[0].id;
			chrome.tabs.sendMessage(tabActiveId, {type: 'getWarsehouseInfo', tabActiveId});
		}
	});
	
	chrome.tabs.onActivated.addListener((tab) => {
		// tabActiveId = tab.tabId;
		// if(!warsehouseList[tabActiveId]) {
		// 	$('#target-warehouse .list-box').html('<div style="text-align: center;">加载中...</div>');
		// }
		chrome.tabs.sendMessage(tab.tabId, {type: 'getWarsehouseInfo', tabActiveId: tab.tabId});
		// changeTab(tabActiveId);
		// btnLimitation();
	})
	chrome.sidePanel.onClosed.addListener(({ windowId }) => {
		chrome.tabs.sendMessage(tabActiveId, {type: 'cancel', params: params[tabActiveId]});
	});

	let isReviewData = false;
	// 切换tab重新赋值表单
	let changeTab = (tabId) => {
		if(params[tabId]) {
			isReviewData = true;
			$('#task-name').val(params[tabId].taskName);
			handleData(warsehouseList[tabId]);
			$('#search-warehouse').val(params[tabId].targetWarehouseName);
			$('#search-transit-warehouse').val(params[tabId].transitWarehouseName);
			$('.monitor-type')[params[tabId].deliveryType].checked = true;
			if(params[tabId].deliveryType === '1') {
				$('#pallets').val(params[tabId].pallets);
			}
			if(params[tabId].monitorType === 1) {
				dateFirstRadio.checked = true;
			} else {
				feeFirstRadio.checked = true;
				minRateInput.value = params[tabId].minRate;
				maxRateInput.value = params[tabId].maxRate;
			}
			if(params[tabId].dateMode === 1) {
				dateModeDynamicRadio.checked = true;
			} else {
				dateModeFixedRadio.checked = true;
			}
			startFixedInput.value = params[tabId].startFixed;
			endFixedInput.value = params[tabId].endFixed;
			if(isStart[tabId]) {
				$('#save-btn').hide();
				$('#cancel-btn').show();
			} else {
				$('#save-btn').show();
				$('#cancel-btn').hide();
			}
			return;
		}
		if(isReviewData) {
			isReviewData = false;
			$('#task-name').val('');
			$('#search-warehouse').val('').attr('disabled', 'disabled');
			$('#search-transit-warehouse').val('').attr('disabled', 'disabled');
			$('.monitor-type')[0].checked = true;
			$('#pallets').val('');
			dateFirstRadio.checked = true;
			minRateInput.value = '';
			maxRateInput.value = '';
			dateModeFixedRadio.checked = true;
			startFixedInput.value = '';
			endFixedInput.value = '';
			startInput.value = '';
			endInput.value = '';
			$('#save-btn').show();
			$('#cancel-btn').hide();
		}
	}

	$('#search-warehouse').focus(function() {
		$('#target-warehouse').show();
	})
	$('#search-warehouse').blur(function() {
		setTimeout(function() {
			$('#target-warehouse').hide();
		}, 150)
	})
	$('#search-warehouse').on('input', function() {
		let value = $(this).val().toLowerCase();
		$('#target-warehouse .list-box div').filter(function() {
			$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);;
		})
	})
	
	// 目标仓选择后与中转仓联动获取数据
	$('#target-warehouse .list-box').click(function(e) {
		if(e.target.className === 'list-box') {
			return;
		}
		$('#search-warehouse').val(e.target.innerText);
		let warehouseID = e.target.dataset.value;
		$('#search-warehouse').attr('data-value', warehouseID);
		getTranferWarehouse(warehouseID);
	})

	$('#search-transit-warehouse').focus(function() {
		$('#target-transit-warehouse').show();
	})
	$('#search-transit-warehouse').blur(function() {
		setTimeout(function() {
			$('#target-transit-warehouse').hide();
		}, 150)
	})
	$('#search-transit-warehouse').on('input', function() {
		let value = $(this).val().toLowerCase();
		$('#target-transit-warehouse .list-box div').filter(function() {
			$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
		})
	})
	
	$('#target-transit-warehouse .list-box').click(function(e) {
		if(e.target.className === 'list-box') {
			return;
		}
		$('#search-transit-warehouse').val(e.target.innerText);
		let warehouseID = e.target.dataset.value;
		$('#search-transit-warehouse').attr('data-value', warehouseID);
	})

	// 处理目标仓库数据
	let handleData = (data, type) => {
		$('#target-warehouse .list-box').html('<div style="text-align: center;">加载中...</div>');
		let html = '';
		warsehouseList[tabActiveId] = [];
		data.forEach((item) => {
			if(item.isActive) {
				if(type === 'init') {
					warsehouseList[tabActiveId].push(item);
				}
				html += `<div data-value="${item.warehouseID}">${item.warehouseName}</div>`;
			}
		});
		$('#target-warehouse .list-box').html(html);
		$('#search-warehouse').removeAttr('disabled');
	}

	// 获取仓库列表
	async function getWarehouseList(message) {
		if (!message || isStart[tabActiveId]) return;

		const apiUrl = `https://seller-supply.wildberries.ru/ns/sm-recommendations/supply-manager/api/v1/recommendations/getRecommendationsForWarehouses`;
		let res = await customFetch(apiUrl, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', 'authorizev3': message.token },
			credentials: 'include',
			body: JSON.stringify({ jsonrpc: "2.0", params: { draftID: message.draftID, useNewRecommendations: true } })
		});
		if (res && res.result && Array.isArray(res.result.warehouses)) {
			notWarehouseData[tabActiveId] = false;
			warsehouseList[tabActiveId] = [];
			handleData(res.result.warehouses, 'init');
		} else {
			notWarehouseData[tabActiveId] = true;
		}
	}
	let getTranferWarehouse = async (warehouseID) => {
	  const apiUrl = `https://seller-supply.wildberries.ru/ns/sm/supply-manager/api/v1/plan/transitTariffsV2`;
		let responseData = await customFetch(apiUrl, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', 'authorizev3': token },
			credentials: 'include',
			body: JSON.stringify({ jsonrpc: "2.0", params: { warehouseID: Number(warehouseID) } })
		});
		$('#search-transit-warehouse').val('');
		if (responseData && responseData.result.items.length > 0) {
			transitWarsehouseList[tabActiveId] = responseData.result.items;
			let html = '';
			transitWarsehouseList[tabActiveId].map(item => {
				html += `<div data-value="${item.transitWarehouseId}">${item.transitWarehouseName}</div>`;
			})
			$('#target-transit-warehouse .list-box').html(html);
			$('#search-transit-warehouse').removeAttr('disabled');
		} else {
			transitWarsehouseList[tabActiveId] = [];
			$('#search-transit-warehouse').val('无中转仓库').attr('disabled', true);
			$('#target-transit-warehouse .list-box').html('<div style="text-align: center;">加载中...</div>');
		}
	}
});