const files = new Set()
function addSubProject() {
	const modal = document.querySelector('#modal-sub_project')
	const inputs = modal.querySelectorAll('.form-control')
	inputs.forEach((input) => {
		input.value = ''
	})
	modal.querySelector('#delete_old_data').checked = false
	modal.querySelector('#delete_old_data').parentNode.style.display = 'none'
	modal.querySelector('#sub_project_file').value = ''
	modal.querySelector('.file-list').innerHTML = ''
	files.clear()
	show_add_modal(modal)
}
function updateSubProject(row, id) {
	const modal = document.querySelector('#modal-sub_project')
	modal.querySelector('#sub_id').value = id
	modal.querySelector('#sub_project_name').value = row.querySelector('.sub_project_name .form-control').value
	modal.querySelector('#work_catalog').value = row.querySelector('.work_catalog .form-control').value
	// modal.querySelector('#work_content').value = row.querySelector('.work_content .form-control').value
	modal.querySelector('#delete_old_data').checked = false
	modal.querySelector('#delete_old_data').parentNode.style.display = 'block'
	modal.querySelector('#sub_project_file').value = ''
	modal.querySelector('.file-list').innerHTML = ''
	files.clear()
	show_edit_modal(modal)
}
function saveSubProject() {
	const id = document.getElementById('sub_id').value
	const project_id = document.getElementById('project_id').value
	const name = document.getElementById('sub_project_name').value
	const catalog = document.getElementById('work_catalog').value
	// const content = document.getElementById('work_content').value
	// const version = document.getElementById('new_standard_version').value
	const content = ''
	const version = '2'

	if (name === '') {
		alert('工程名称不能为空')
		return
	}
	if (files.length === 0 && !id) {
		alert('请选择工程数据文件')
		return
	}
	// if (catalog === '') {
	// 	alert('工作目录不能为空')
	// 	return
	// }
	// if (content === '') {
	// 	alert('工作内容不能为空')
	// 	return
	// }

	const formData = new FormData()
	formData.append('id', id)
	formData.append('project_id', project_id)
	formData.append('sub_project_name', name)
	files.forEach((file) => {
		formData.append('project_files', file)
	})
	formData.append('work_catalog', catalog)
	formData.append('work_content', content)
	formData.append('standard_version', version)
	if (document.getElementById('delete_old_data')) {
		formData.append('delete_old_data', document.getElementById('delete_old_data').checked)
	}

	fetch('/save_sub_project', {
		method: 'POST',
		body: formData,
	})
		.then((response) => response.json())
		.then((data) => {
			if (data.success) {
				alert('保存成功')
				window.location.reload()
			} else {
				alert('保存失败:' + data.error)
			}
		})
		.catch((error) => {
			console.error('保存失败:', error)
			alert('保存失败')
		})
}

function startSubProjectTask(id) {
	_confirm('确定要开始任务吗？', `/start_sub_project_task/${id}`)
}

function reStartSubProjectTask(id) {
	_confirm('确定要重新采集Excel的数据吗？', `/start_sub_project_task/${id}`)
}

function reStartProcessSubProjectTask(id) {
	_confirm('确定要重新处理数据吗？', `/start_process_sub_project/${id}`)
}

function reStartSendSubProjectTask(id) {
	_confirm('确定要开始上传数据吗？', `/start_send_sub_project/${id}`)
}

function deleteSubProject(id) {
	if (confirm('确定要删除该工程吗？')) {
		fetch(`/delete_sub_project/${id}`, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
			},
		})
			.then((response) => response.json())
			.then((data) => {
				if (data.success) {
					alert('删除成功')
					window.location.reload()
				} else {
					alert('删除失败:' + data.error)
				}
			})
			.catch((error) => {
				console.error('删除失败:', error)
				alert('删除失败')
			})
	}
}

function handleDragOver(e) {
	e.preventDefault()
	e.stopPropagation()
	const modal = document.querySelector('#modal-sub_project')
	modal.querySelector('.drag-drop-box').classList.add('dragover')
}

function handleDragLeave(e) {
	e.preventDefault()
	e.stopPropagation()
	const modal = document.querySelector('#modal-sub_project')
	modal.querySelector('.drag-drop-box').classList.remove('dragover')
}

function handleDrop(e) {
	e.preventDefault()
	e.stopPropagation()
	const modal = document.querySelector('#modal-sub_project')
	modal.querySelector('.drag-drop-box').classList.remove('dragover')
	const files = e.dataTransfer.files
	handleFiles(files)
}

function handleFileSelect(e) {
	const files = e.target.files
	handleFiles(files)
}

function handleFiles(newFiles) {
	const fileList = document.getElementById('fileList')
	const existingFiles = new Set()
	fileList.querySelectorAll('.file-item span:first-child').forEach((item) => {
		existingFiles.add(item.textContent)
	})

	Array.from(newFiles).forEach((file) => {
		if (existingFiles.has(file.name)) {
			alert('文件' + file.name + '已存在，请勿重复添加！')
			return
		}
		existingFiles.add(file.name)
		fileList.appendChild(createFileItem(file))
		files.add(file)
	})
	document.getElementById('sub_project_file').value = ''
}
function createFileItem(file) {
	const item = document.createElement('div')
	item.className = 'file-item'
	item.innerHTML = `
			<span>${file.name}</span>
			<span class="del" onclick="removeFileItem(this)">×</span>
	`
	return item
}

function removeFileItem(element) {
	const fileItem = element.closest('.file-item')
	fileItem.remove()
	// 清除文件输入框的值
	document.getElementById('sub_project_file').value = ''
}

document.addEventListener('DOMContentLoaded', function () {
	document.getElementById('dragDropArea').addEventListener('click', function () {
		document.getElementById('sub_project_file').click()
	})
})
