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

import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskAllocService;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskReviewService;
import org.jeecg.modules.stm.baosong.service.IBaosongTaskService;
import org.jeecg.modules.stm.baosong.service.IBaosongTplService;
import org.springframework.beans.factory.annotation.Value;
import org.jeecg.modules.stm.baosong.entity.BaosongTask;
import org.jeecg.modules.stm.baosong.entity.BaosongTaskReview;
import org.jeecg.modules.stm.baosong.entity.BaosongTpl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.springframework.web.servlet.ModelAndView;
 
 
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

/**
 * @Description: 内容检查
 * @Author: jeecg-boot
 * @Date:   2024-12-17
 * @Version: V1.0
 */

@RestController
@RequestMapping("/baosong/baosongTaskReview")
@Slf4j
public class BaosongTaskReviewController extends JeecgController<BaosongTaskReview, IBaosongTaskReviewService> {
	@Autowired
	private IBaosongTaskReviewService baosongTaskReviewService;
	@Autowired
	private IBaosongTplService baosongTplService;
	@Autowired
	private IBaosongTaskService baosongTaskService;
	@Autowired
	private IBaosongTaskAllocService baosongTaskAllocService;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;
	
	/**
	 * 分页列表查询
	 *
	 * @param baosongTaskReview
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "内容检查-分页列表查询")

	@GetMapping(value = "/list")
	public Result<IPage<BaosongTaskReview>> queryPageList(BaosongTaskReview baosongTaskReview,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BaosongTaskReview> queryWrapper = QueryGenerator.initQueryWrapper(baosongTaskReview, req.getParameterMap());
		Page<BaosongTaskReview> page = new Page<BaosongTaskReview>(pageNo, pageSize);
		IPage<BaosongTaskReview> pageList = baosongTaskReviewService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param baosongTaskReview
	 * @return
	 */
	@AutoLog(value = "内容检查-添加")

	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BaosongTaskReview baosongTaskReview) {
		baosongTaskReviewService.save(baosongTaskReview);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param baosongTaskReview
	 * @return
	 */
	@AutoLog(value = "内容检查-编辑")

	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BaosongTaskReview baosongTaskReview) {
		baosongTaskReview.setAppTime(new Date());
		baosongTaskReviewService.updateById(baosongTaskReview);
		if(baosongTaskReview.getAppSta()==0){
			baosongTaskService.updateTaskSta(1,baosongTaskReview.getTaskid());
		}
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "内容检查-通过id删除")

	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		baosongTaskReviewService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "内容检查-批量删除")

	@RequiresPermissions("baosong:baosong_task_review:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.baosongTaskReviewService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "内容检查-通过id查询")

	@GetMapping(value = "/queryById")
	public Result<BaosongTaskReview> queryById(@RequestParam(name="id",required=true) String id) {
		BaosongTaskReview baosongTaskReview = baosongTaskReviewService.getById(id);
		if(baosongTaskReview==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(baosongTaskReview);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param baosongTaskReview
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BaosongTaskReview baosongTaskReview) {
        return super.exportXls(request, baosongTaskReview, BaosongTaskReview.class, "内容检查");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("baosong:baosong_task_review:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BaosongTaskReview.class);
    }


	@RequestMapping(value = "/downLoadTaskXml2")
	public Result<String> downLoadTaskXml2(HttpServletRequest request, BaosongTaskReview taskReview) {
		Integer tplId = taskReview.getTplid();
		List<Map<String,Object>> list = baosongTaskReviewService.queryTaskRecordForXml(taskReview);
		BaosongTpl baosongTpl = baosongTplService.getById(tplId);

		try {
			String rootPath = uploadpath;
			String newFileName = getReportFilePath(taskReview);
			String templateFileName = getTempleFilePath(taskReview.getTplid());
			String templetPath = rootPath+ templateFileName;
			String reportPath =  rootPath + newFileName;
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			File xmlFile = new File(templetPath);
			Document document = builder.parse(xmlFile);
			document.getDocumentElement().normalize();
			for(Map<String,Object> item:list) {
				String code = item.get("code").toString();
				String value  = item.get("content").toString();
				setNodeValue(document, code, value);
			}
			saveDocumentToFile(document, reportPath);
			return Result.OK(newFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/downLoadTaskXml")
	public Result<String> downLoadTaskXml(HttpServletRequest request, BaosongTaskReview taskReview) {
		Integer tplId = taskReview.getTplid();
		Integer taskId = taskReview.getTaskid();
		List<Map<String,Object>> list = baosongTaskReviewService.queryTaskRecordForXml(taskReview);
		BaosongTpl baosongTpl = baosongTplService.getById(tplId);
		BaosongTask baosongTask = baosongTaskService.getById(taskId);
		try {
			String fillUserNames = baosongTaskAllocService.getFillUsers(taskId,tplId);
			String rootPath = uploadpath;
			String newFileName = getReportFilePath(taskReview);
			String reportPath =  rootPath + newFileName;
			CreateXmlFile createXmlFile = new CreateXmlFile(baosongTpl,baosongTask,fillUserNames);
			createXmlFile.createXml(list,reportPath);

			return Result.OK(newFileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static void saveDocumentToFile(Document document, String filePath) {
		try {
			// 创建变换器实例
			TransformerFactory transformerFactory = TransformerFactory.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 缩进
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // 设置缩进空间
			DOMSource source = new DOMSource(document);
			StreamResult result = new StreamResult(new File(filePath));
			transformer.transform(source, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void setNodeValue(Document document, String tagName, String value) {
		NodeList nodeList = document.getElementsByTagName(tagName);
		if (nodeList.getLength() > 0) {
			// 设置节点值
			Element element = (Element) nodeList.item(0);
			element.setTextContent(value);
		} else {
			System.out.println(tagName + " 节点未找到.");
		}
	}

	private  String getTempleFilePath(Integer tplid) {
		BaosongTpl tpl = baosongTplService.getById(tplid);
		return tpl.getXmlfilePath();
	}

	private  String getReportFilePath(BaosongTaskReview taskReview) {
		String strPath = "/baosong/report/"+taskReview.getTaskname()+"-"+taskReview.getTplname()+".xml";
		return strPath;
	}

}
