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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
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 org.jeecg.modules.stm.baosong.entity.TaskRecordVo;
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.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

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 java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @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());
		queryWrapper.ne("app_sta",9);
		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()==2){
			baosongTaskService.updateTaskSta(1,baosongTaskReview.getTaskid());
		} else if(baosongTaskReview.getAppSta()==1){
			baosongTaskService.updateTaskSta(4,baosongTaskReview.getTaskid());
		} else if(baosongTaskReview.getAppSta()==9){
			baosongTaskService.updateTaskSta(9,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 = "/downLoadTaskXml")
	public Result<String> downLoadTaskXml(HttpServletRequest request, BaosongTaskReview taskReview) {
		Integer tplId = taskReview.getTplid();
		Integer taskId = taskReview.getTaskid();
		List<TaskRecordVo> list = baosongTaskReviewService.queryTaskRecordForXml(taskReview);
		if(list==null||list.size()==0){
			return Result.error("未查询到数据");
		};
		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 Result.error("未知错误");
	}

	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 taskName = taskReview.getTaskname();
		taskName  = taskName==null?taskReview.getTaskid().toString():taskName;
		String tplName = taskReview.getTplname();
		tplName = tplName==null?taskReview.getTplid().toString():tplName;
		String strPath = "/baosong/report/"+taskName+"-"+tplName+".xml";
		return strPath;
	}

}
