package org.jeecg.modules.stm.baosong.controller;

import java.io.File;
import java.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.stm.baosong.entity.BaosongTask;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskRecord;
import org.jeecg.modules.stm.baosong.entity.BaosongTplItem;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskRecordService;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskService;
import org.jeecg.modules.stm.baosong.service.IBaosongTplItemService;


import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
 
import org.jeecg.modules.stm.utils.UserUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;



@RestController
@RequestMapping("/baosong/baosongTask")
@Slf4j
public class BaosongImportDataController extends JeecgController<BaosongTask, IBaosongTaskService> {
	@Autowired
	private IBaosongTaskService baosongTaskService;
	@Autowired
	private IBaosongTplItemService baosongTplItemService;
	@Autowired
	private IBaosongTaskRecordService baosongTaskRecordService;

	@GetMapping(value = "/importData")
	public Result<String> importData(@RequestParam(required = true) Integer taskId,
									 @RequestParam(required = true) String folderPath ) {

		Map<String, BaosongTplItem> codeTplItemMap = getItemCodeMap();

		File folder = new File(folderPath);
		if (!folder.exists() || !folder.isDirectory()) {
			return Result.error("指定的文件夹不存在或不是目录");
		}
		File[] xmlFiles = folder.listFiles((dir, name) -> name.toLowerCase().endsWith(".xml"));
		if (xmlFiles == null || xmlFiles.length == 0) {
			return Result.error("文件夹中没有找到XML文件");
		}
		List<BaosongTaskRecord> retList = new ArrayList<>();

		for (File xmlFile : xmlFiles) {
			List<Map<String,String>> nodeInfoList = parseXML(xmlFile);
			for (Map<String,String> valMap : nodeInfoList) {
				for (Map.Entry<String,String> entry : valMap.entrySet()) {
					BaosongTaskRecord taskRecord = new BaosongTaskRecord();
					String strKey = entry.getKey();
					String value = entry.getValue();
					if(value==null||value.isEmpty()||value.equals(",")){
						continue;
					}

					BaosongTplItem tplItem = codeTplItemMap.get(strKey);
					if(tplItem==null)continue;

					if(tplItem.getFormTp()!=null && tplItem.getFormTp().equals("checkbox")){
						value = removeFirstAndLastChar(value);
					}

					if (tplItem.getFormTp() != null && tplItem.getFormTp().equals("checkbox")) {
						value = removeFirstAndLastChar(value);
					}

					taskRecord.setCreateTime(new Date());
					taskRecord.setCreateBy(UserUtil.getUserCode());
					taskRecord.setTaskid(taskId);
					taskRecord.setRind(1);
					taskRecord.setItemid(tplItem.getId());
					taskRecord.setItempid(tplItem.getPid());
					taskRecord.setTplcode(tplItem.getCode());
					taskRecord.setTplid(tplItem.getTplid());
					taskRecord.setContent(value);
					retList.add(taskRecord);
				}
			}
		}
		deleteTaskAllRecord(taskId);
		baosongTaskRecordService.saveBatch(retList);
		return Result.OK("导入成功！");
	}

	private List<Map<String,String>> parseXML(File xmlFile) {
		List<Map<String,String>> nodeList = new ArrayList<>();
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document document = builder.parse(xmlFile);
			document.getDocumentElement().normalize();
			Element root = document.getDocumentElement();
			// 递归解析所有子节点
			parseElement(root, null, nodeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nodeList;
	}

	private  void parseElement(Element element, String parentCode, List<Map<String,String>> nodeList) {
		String currentCode = element.getNodeName();
		String comment = "";
		Node prevSibling = element.getPreviousSibling();
		while (prevSibling != null && prevSibling.getNodeType() != Node.COMMENT_NODE) {
			prevSibling = prevSibling.getPreviousSibling();
		}
		if (prevSibling != null && prevSibling.getNodeType() == Node.COMMENT_NODE) {
			comment = prevSibling.getTextContent().trim();
		}
		String value = "";
		if (element.getChildNodes().getLength() == 1 &&
				element.getFirstChild().getNodeType() == Node.TEXT_NODE) {
			value = element.getFirstChild().getTextContent().trim();
		}

		Map<String,String> tmpMap = new HashMap<>();

		if(parentCode==null||parentCode.equals("")) {
			parentCode = "0";
		}
		tmpMap.put(parentCode+":"+currentCode,value);

		nodeList.add(tmpMap);
		// 递归处理子元素
		NodeList childNodes = element.getChildNodes();
		for (int i = 0; i < childNodes.getLength(); i++) {
			Node node = childNodes.item(i);
			if (node.getNodeType() == Node.ELEMENT_NODE) {
				parseElement((Element) node, currentCode, nodeList);
			}
		}
	}

	private Map<String,BaosongTplItem> getItemCodeMap() {
		Map<String,BaosongTplItem> retMap =  new HashMap<>();
		try {
			List<BaosongTplItem> tplItemList = baosongTplItemService.list();
			for(BaosongTplItem tplItem:tplItemList) {
				String key = tplItem.getPcode()+":"+tplItem.getCode();
				retMap.put(key,tplItem);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return retMap;
	}


	public void deleteTaskAllRecord(Integer taskId) {
		QueryWrapper<BaosongTaskRecord> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("taskid",taskId);
		this.baosongTaskRecordService.remove(queryWrapper);

	}

	private String removeFirstAndLastChar(String curStr) {
		if (curStr == null || curStr.isEmpty()) {
			return "";
		}

		int start = 0;
		int end = curStr.length();

		// 如果第一个字符是逗号，跳过
		if (curStr.charAt(0) == ',') {
			start = 1;
		}

		// 如果最后一个字符是逗号，跳过
		if (curStr.charAt(curStr.length() - 1) == ',') {
			end = end - 1;
		}

		// 如果剩下的长度为0或负数，返回空字符串
		if (start >= end) {
			return "";
		}
		return curStr.substring(start, end);
	}

}
